sqlite3.c 4.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.7.15.2. 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. /*
  283. ** Include standard header files as necessary
  284. */
  285. #ifdef HAVE_STDINT_H
  286. #include <stdint.h>
  287. #endif
  288. #ifdef HAVE_INTTYPES_H
  289. #include <inttypes.h>
  290. #endif
  291. /*
  292. ** The following macros are used to cast pointers to integers and
  293. ** integers to pointers. The way you do this varies from one compiler
  294. ** to the next, so we have developed the following set of #if statements
  295. ** to generate appropriate macros for a wide range of compilers.
  296. **
  297. ** The correct "ANSI" way to do this is to use the intptr_t type.
  298. ** Unfortunately, that typedef is not available on all compilers, or
  299. ** if it is available, it requires an #include of specific headers
  300. ** that vary from one machine to the next.
  301. **
  302. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  303. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  304. ** So we have to define the macros in different ways depending on the
  305. ** compiler.
  306. */
  307. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  308. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  309. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  310. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  311. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  312. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  313. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  314. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  315. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  316. #else /* Generates a warning - but it always works */
  317. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  318. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  319. #endif
  320. /*
  321. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  322. ** 0 means mutexes are permanently disable and the library is never
  323. ** threadsafe. 1 means the library is serialized which is the highest
  324. ** level of threadsafety. 2 means the libary is multithreaded - multiple
  325. ** threads can use SQLite as long as no two threads try to use the same
  326. ** database connection at the same time.
  327. **
  328. ** Older versions of SQLite used an optional THREADSAFE macro.
  329. ** We support that for legacy.
  330. */
  331. #if !defined(SQLITE_THREADSAFE)
  332. #if defined(THREADSAFE)
  333. # define SQLITE_THREADSAFE THREADSAFE
  334. #else
  335. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  336. #endif
  337. #endif
  338. /*
  339. ** Powersafe overwrite is on by default. But can be turned off using
  340. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  341. */
  342. #ifndef SQLITE_POWERSAFE_OVERWRITE
  343. # define SQLITE_POWERSAFE_OVERWRITE 1
  344. #endif
  345. /*
  346. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  347. ** It determines whether or not the features related to
  348. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  349. ** be overridden at runtime using the sqlite3_config() API.
  350. */
  351. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  352. # define SQLITE_DEFAULT_MEMSTATUS 1
  353. #endif
  354. /*
  355. ** Exactly one of the following macros must be defined in order to
  356. ** specify which memory allocation subsystem to use.
  357. **
  358. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  359. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  360. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  361. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  362. **
  363. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  364. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  365. ** will cause HeapValidate to be called. If heap validation should fail, an
  366. ** assertion will be triggered.
  367. **
  368. ** (Historical note: There used to be several other options, but we've
  369. ** pared it down to just these three.)
  370. **
  371. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  372. ** the default.
  373. */
  374. #if defined(SQLITE_SYSTEM_MALLOC) \
  375. + defined(SQLITE_WIN32_MALLOC) \
  376. + defined(SQLITE_ZERO_MALLOC) \
  377. + defined(SQLITE_MEMDEBUG)>1
  378. # error "Two or more of the following compile-time configuration options\
  379. are defined but at most one is allowed:\
  380. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  381. SQLITE_ZERO_MALLOC"
  382. #endif
  383. #if defined(SQLITE_SYSTEM_MALLOC) \
  384. + defined(SQLITE_WIN32_MALLOC) \
  385. + defined(SQLITE_ZERO_MALLOC) \
  386. + defined(SQLITE_MEMDEBUG)==0
  387. # define SQLITE_SYSTEM_MALLOC 1
  388. #endif
  389. /*
  390. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  391. ** sizes of memory allocations below this value where possible.
  392. */
  393. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  394. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  395. #endif
  396. /*
  397. ** We need to define _XOPEN_SOURCE as follows in order to enable
  398. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  399. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  400. ** so it is omitted there. See ticket #2673.
  401. **
  402. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  403. ** implemented on some systems. So we avoid defining it at all
  404. ** if it is already defined or if it is unneeded because we are
  405. ** not doing a threadsafe build. Ticket #2681.
  406. **
  407. ** See also ticket #2741.
  408. */
  409. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  410. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  411. #endif
  412. /*
  413. ** The TCL headers are only needed when compiling the TCL bindings.
  414. */
  415. #if defined(SQLITE_TCL) || defined(TCLSH)
  416. # include <tcl.h>
  417. #endif
  418. /*
  419. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  420. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  421. ** make it true by defining or undefining NDEBUG.
  422. **
  423. ** Setting NDEBUG makes the code smaller and run faster by disabling the
  424. ** number assert() statements in the code. So we want the default action
  425. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  426. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  427. ** feature.
  428. */
  429. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  430. # define NDEBUG 1
  431. #endif
  432. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  433. # undef NDEBUG
  434. #endif
  435. /*
  436. ** The testcase() macro is used to aid in coverage testing. When
  437. ** doing coverage testing, the condition inside the argument to
  438. ** testcase() must be evaluated both true and false in order to
  439. ** get full branch coverage. The testcase() macro is inserted
  440. ** to help ensure adequate test coverage in places where simple
  441. ** condition/decision coverage is inadequate. For example, testcase()
  442. ** can be used to make sure boundary values are tested. For
  443. ** bitmask tests, testcase() can be used to make sure each bit
  444. ** is significant and used at least once. On switch statements
  445. ** where multiple cases go to the same block of code, testcase()
  446. ** can insure that all cases are evaluated.
  447. **
  448. */
  449. #ifdef SQLITE_COVERAGE_TEST
  450. SQLITE_PRIVATE void sqlite3Coverage(int);
  451. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  452. #else
  453. # define testcase(X)
  454. #endif
  455. /*
  456. ** The TESTONLY macro is used to enclose variable declarations or
  457. ** other bits of code that are needed to support the arguments
  458. ** within testcase() and assert() macros.
  459. */
  460. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  461. # define TESTONLY(X) X
  462. #else
  463. # define TESTONLY(X)
  464. #endif
  465. /*
  466. ** Sometimes we need a small amount of code such as a variable initialization
  467. ** to setup for a later assert() statement. We do not want this code to
  468. ** appear when assert() is disabled. The following macro is therefore
  469. ** used to contain that setup code. The "VVA" acronym stands for
  470. ** "Verification, Validation, and Accreditation". In other words, the
  471. ** code within VVA_ONLY() will only run during verification processes.
  472. */
  473. #ifndef NDEBUG
  474. # define VVA_ONLY(X) X
  475. #else
  476. # define VVA_ONLY(X)
  477. #endif
  478. /*
  479. ** The ALWAYS and NEVER macros surround boolean expressions which
  480. ** are intended to always be true or false, respectively. Such
  481. ** expressions could be omitted from the code completely. But they
  482. ** are included in a few cases in order to enhance the resilience
  483. ** of SQLite to unexpected behavior - to make the code "self-healing"
  484. ** or "ductile" rather than being "brittle" and crashing at the first
  485. ** hint of unplanned behavior.
  486. **
  487. ** In other words, ALWAYS and NEVER are added for defensive code.
  488. **
  489. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  490. ** be true and false so that the unreachable code then specify will
  491. ** not be counted as untested code.
  492. */
  493. #if defined(SQLITE_COVERAGE_TEST)
  494. # define ALWAYS(X) (1)
  495. # define NEVER(X) (0)
  496. #elif !defined(NDEBUG)
  497. # define ALWAYS(X) ((X)?1:(assert(0),0))
  498. # define NEVER(X) ((X)?(assert(0),1):0)
  499. #else
  500. # define ALWAYS(X) (X)
  501. # define NEVER(X) (X)
  502. #endif
  503. /*
  504. ** Return true (non-zero) if the input is a integer that is too large
  505. ** to fit in 32-bits. This macro is used inside of various testcase()
  506. ** macros to verify that we have tested SQLite for large-file support.
  507. */
  508. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  509. /*
  510. ** The macro unlikely() is a hint that surrounds a boolean
  511. ** expression that is usually false. Macro likely() surrounds
  512. ** a boolean expression that is usually true. GCC is able to
  513. ** use these hints to generate better code, sometimes.
  514. */
  515. #if defined(__GNUC__) && 0
  516. # define likely(X) __builtin_expect((X),1)
  517. # define unlikely(X) __builtin_expect((X),0)
  518. #else
  519. # define likely(X) !!(X)
  520. # define unlikely(X) !!(X)
  521. #endif
  522. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  523. /************** Begin file sqlite3.h *****************************************/
  524. /*
  525. ** 2001 September 15
  526. **
  527. ** The author disclaims copyright to this source code. In place of
  528. ** a legal notice, here is a blessing:
  529. **
  530. ** May you do good and not evil.
  531. ** May you find forgiveness for yourself and forgive others.
  532. ** May you share freely, never taking more than you give.
  533. **
  534. *************************************************************************
  535. ** This header file defines the interface that the SQLite library
  536. ** presents to client programs. If a C-function, structure, datatype,
  537. ** or constant definition does not appear in this file, then it is
  538. ** not a published API of SQLite, is subject to change without
  539. ** notice, and should not be referenced by programs that use SQLite.
  540. **
  541. ** Some of the definitions that are in this file are marked as
  542. ** "experimental". Experimental interfaces are normally new
  543. ** features recently added to SQLite. We do not anticipate changes
  544. ** to experimental interfaces but reserve the right to make minor changes
  545. ** if experience from use "in the wild" suggest such changes are prudent.
  546. **
  547. ** The official C-language API documentation for SQLite is derived
  548. ** from comments in this file. This file is the authoritative source
  549. ** on how SQLite interfaces are suppose to operate.
  550. **
  551. ** The name of this file under configuration management is "sqlite.h.in".
  552. ** The makefile makes some minor changes to this file (such as inserting
  553. ** the version number) and changes its name to "sqlite3.h" as
  554. ** part of the build process.
  555. */
  556. #ifndef _SQLITE3_H_
  557. #define _SQLITE3_H_
  558. #include <stdarg.h> /* Needed for the definition of va_list */
  559. /*
  560. ** Make sure we can call this stuff from C++.
  561. */
  562. #if 0
  563. extern "C" {
  564. #endif
  565. /*
  566. ** Add the ability to override 'extern'
  567. */
  568. #ifndef SQLITE_EXTERN
  569. # define SQLITE_EXTERN extern
  570. #endif
  571. #ifndef SQLITE_API
  572. # define SQLITE_API
  573. #endif
  574. /*
  575. ** These no-op macros are used in front of interfaces to mark those
  576. ** interfaces as either deprecated or experimental. New applications
  577. ** should not use deprecated interfaces - they are support for backwards
  578. ** compatibility only. Application writers should be aware that
  579. ** experimental interfaces are subject to change in point releases.
  580. **
  581. ** These macros used to resolve to various kinds of compiler magic that
  582. ** would generate warning messages when they were used. But that
  583. ** compiler magic ended up generating such a flurry of bug reports
  584. ** that we have taken it all out and gone back to using simple
  585. ** noop macros.
  586. */
  587. #define SQLITE_DEPRECATED
  588. #define SQLITE_EXPERIMENTAL
  589. /*
  590. ** Ensure these symbols were not defined by some previous header file.
  591. */
  592. #ifdef SQLITE_VERSION
  593. # undef SQLITE_VERSION
  594. #endif
  595. #ifdef SQLITE_VERSION_NUMBER
  596. # undef SQLITE_VERSION_NUMBER
  597. #endif
  598. /*
  599. ** CAPI3REF: Compile-Time Library Version Numbers
  600. **
  601. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  602. ** evaluates to a string literal that is the SQLite version in the
  603. ** format "X.Y.Z" where X is the major version number (always 3 for
  604. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  605. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  606. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  607. ** numbers used in [SQLITE_VERSION].)^
  608. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  609. ** be larger than the release from which it is derived. Either Y will
  610. ** be held constant and Z will be incremented or else Y will be incremented
  611. ** and Z will be reset to zero.
  612. **
  613. ** Since version 3.6.18, SQLite source code has been stored in the
  614. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  615. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  616. ** a string which identifies a particular check-in of SQLite
  617. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  618. ** string contains the date and time of the check-in (UTC) and an SHA1
  619. ** hash of the entire source tree.
  620. **
  621. ** See also: [sqlite3_libversion()],
  622. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  623. ** [sqlite_version()] and [sqlite_source_id()].
  624. */
  625. #define SQLITE_VERSION "3.7.15.2"
  626. #define SQLITE_VERSION_NUMBER 3007015
  627. #define SQLITE_SOURCE_ID "2013-01-09 11:53:05 c0e09560d26f0a6456be9dd3447f5311eb4f238f"
  628. /*
  629. ** CAPI3REF: Run-Time Library Version Numbers
  630. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  631. **
  632. ** These interfaces provide the same information as the [SQLITE_VERSION],
  633. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  634. ** but are associated with the library instead of the header file. ^(Cautious
  635. ** programmers might include assert() statements in their application to
  636. ** verify that values returned by these interfaces match the macros in
  637. ** the header, and thus insure that the application is
  638. ** compiled with matching library and header files.
  639. **
  640. ** <blockquote><pre>
  641. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  642. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  643. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  644. ** </pre></blockquote>)^
  645. **
  646. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  647. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  648. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  649. ** function is provided for use in DLLs since DLL users usually do not have
  650. ** direct access to string constants within the DLL. ^The
  651. ** sqlite3_libversion_number() function returns an integer equal to
  652. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  653. ** a pointer to a string constant whose value is the same as the
  654. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  655. **
  656. ** See also: [sqlite_version()] and [sqlite_source_id()].
  657. */
  658. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  659. SQLITE_API const char *sqlite3_libversion(void);
  660. SQLITE_API const char *sqlite3_sourceid(void);
  661. SQLITE_API int sqlite3_libversion_number(void);
  662. /*
  663. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  664. **
  665. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  666. ** indicating whether the specified option was defined at
  667. ** compile time. ^The SQLITE_ prefix may be omitted from the
  668. ** option name passed to sqlite3_compileoption_used().
  669. **
  670. ** ^The sqlite3_compileoption_get() function allows iterating
  671. ** over the list of options that were defined at compile time by
  672. ** returning the N-th compile time option string. ^If N is out of range,
  673. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  674. ** prefix is omitted from any strings returned by
  675. ** sqlite3_compileoption_get().
  676. **
  677. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  678. ** and sqlite3_compileoption_get() may be omitted by specifying the
  679. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  680. **
  681. ** See also: SQL functions [sqlite_compileoption_used()] and
  682. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  683. */
  684. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  685. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  686. SQLITE_API const char *sqlite3_compileoption_get(int N);
  687. #endif
  688. /*
  689. ** CAPI3REF: Test To See If The Library Is Threadsafe
  690. **
  691. ** ^The sqlite3_threadsafe() function returns zero if and only if
  692. ** SQLite was compiled with mutexing code omitted due to the
  693. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  694. **
  695. ** SQLite can be compiled with or without mutexes. When
  696. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  697. ** are enabled and SQLite is threadsafe. When the
  698. ** [SQLITE_THREADSAFE] macro is 0,
  699. ** the mutexes are omitted. Without the mutexes, it is not safe
  700. ** to use SQLite concurrently from more than one thread.
  701. **
  702. ** Enabling mutexes incurs a measurable performance penalty.
  703. ** So if speed is of utmost importance, it makes sense to disable
  704. ** the mutexes. But for maximum safety, mutexes should be enabled.
  705. ** ^The default behavior is for mutexes to be enabled.
  706. **
  707. ** This interface can be used by an application to make sure that the
  708. ** version of SQLite that it is linking against was compiled with
  709. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  710. **
  711. ** This interface only reports on the compile-time mutex setting
  712. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  713. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  714. ** can be fully or partially disabled using a call to [sqlite3_config()]
  715. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  716. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  717. ** sqlite3_threadsafe() function shows only the compile-time setting of
  718. ** thread safety, not any run-time changes to that setting made by
  719. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  720. ** is unchanged by calls to sqlite3_config().)^
  721. **
  722. ** See the [threading mode] documentation for additional information.
  723. */
  724. SQLITE_API int sqlite3_threadsafe(void);
  725. /*
  726. ** CAPI3REF: Database Connection Handle
  727. ** KEYWORDS: {database connection} {database connections}
  728. **
  729. ** Each open SQLite database is represented by a pointer to an instance of
  730. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  731. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  732. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  733. ** and [sqlite3_close_v2()] are its destructors. There are many other
  734. ** interfaces (such as
  735. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  736. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  737. ** sqlite3 object.
  738. */
  739. typedef struct sqlite3 sqlite3;
  740. /*
  741. ** CAPI3REF: 64-Bit Integer Types
  742. ** KEYWORDS: sqlite_int64 sqlite_uint64
  743. **
  744. ** Because there is no cross-platform way to specify 64-bit integer types
  745. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  746. **
  747. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  748. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  749. ** compatibility only.
  750. **
  751. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  752. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  753. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  754. ** between 0 and +18446744073709551615 inclusive.
  755. */
  756. #ifdef SQLITE_INT64_TYPE
  757. typedef SQLITE_INT64_TYPE sqlite_int64;
  758. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  759. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  760. typedef __int64 sqlite_int64;
  761. typedef unsigned __int64 sqlite_uint64;
  762. #else
  763. typedef long long int sqlite_int64;
  764. typedef unsigned long long int sqlite_uint64;
  765. #endif
  766. typedef sqlite_int64 sqlite3_int64;
  767. typedef sqlite_uint64 sqlite3_uint64;
  768. /*
  769. ** If compiling for a processor that lacks floating point support,
  770. ** substitute integer for floating-point.
  771. */
  772. #ifdef SQLITE_OMIT_FLOATING_POINT
  773. # define double sqlite3_int64
  774. #endif
  775. /*
  776. ** CAPI3REF: Closing A Database Connection
  777. **
  778. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  779. ** for the [sqlite3] object.
  780. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  781. ** the [sqlite3] object is successfully destroyed and all associated
  782. ** resources are deallocated.
  783. **
  784. ** ^If the database connection is associated with unfinalized prepared
  785. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  786. ** will leave the database connection open and return [SQLITE_BUSY].
  787. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  788. ** and unfinished sqlite3_backups, then the database connection becomes
  789. ** an unusable "zombie" which will automatically be deallocated when the
  790. ** last prepared statement is finalized or the last sqlite3_backup is
  791. ** finished. The sqlite3_close_v2() interface is intended for use with
  792. ** host languages that are garbage collected, and where the order in which
  793. ** destructors are called is arbitrary.
  794. **
  795. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  796. ** [sqlite3_blob_close | close] all [BLOB handles], and
  797. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  798. ** with the [sqlite3] object prior to attempting to close the object. ^If
  799. ** sqlite3_close() is called on a [database connection] that still has
  800. ** outstanding [prepared statements], [BLOB handles], and/or
  801. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  802. ** of resources is deferred until all [prepared statements], [BLOB handles],
  803. ** and [sqlite3_backup] objects are also destroyed.
  804. **
  805. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  806. ** the transaction is automatically rolled back.
  807. **
  808. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  809. ** must be either a NULL
  810. ** pointer or an [sqlite3] object pointer obtained
  811. ** from [sqlite3_open()], [sqlite3_open16()], or
  812. ** [sqlite3_open_v2()], and not previously closed.
  813. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  814. ** argument is a harmless no-op.
  815. */
  816. SQLITE_API int sqlite3_close(sqlite3*);
  817. SQLITE_API int sqlite3_close_v2(sqlite3*);
  818. /*
  819. ** The type for a callback function.
  820. ** This is legacy and deprecated. It is included for historical
  821. ** compatibility and is not documented.
  822. */
  823. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  824. /*
  825. ** CAPI3REF: One-Step Query Execution Interface
  826. **
  827. ** The sqlite3_exec() interface is a convenience wrapper around
  828. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  829. ** that allows an application to run multiple statements of SQL
  830. ** without having to use a lot of C code.
  831. **
  832. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  833. ** semicolon-separate SQL statements passed into its 2nd argument,
  834. ** in the context of the [database connection] passed in as its 1st
  835. ** argument. ^If the callback function of the 3rd argument to
  836. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  837. ** coming out of the evaluated SQL statements. ^The 4th argument to
  838. ** sqlite3_exec() is relayed through to the 1st argument of each
  839. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  840. ** is NULL, then no callback is ever invoked and result rows are
  841. ** ignored.
  842. **
  843. ** ^If an error occurs while evaluating the SQL statements passed into
  844. ** sqlite3_exec(), then execution of the current statement stops and
  845. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  846. ** is not NULL then any error message is written into memory obtained
  847. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  848. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  849. ** on error message strings returned through the 5th parameter of
  850. ** of sqlite3_exec() after the error message string is no longer needed.
  851. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  852. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  853. ** NULL before returning.
  854. **
  855. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  856. ** routine returns SQLITE_ABORT without invoking the callback again and
  857. ** without running any subsequent SQL statements.
  858. **
  859. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  860. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  861. ** callback is an array of pointers to strings obtained as if from
  862. ** [sqlite3_column_text()], one for each column. ^If an element of a
  863. ** result row is NULL then the corresponding string pointer for the
  864. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  865. ** sqlite3_exec() callback is an array of pointers to strings where each
  866. ** entry represents the name of corresponding result column as obtained
  867. ** from [sqlite3_column_name()].
  868. **
  869. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  870. ** to an empty string, or a pointer that contains only whitespace and/or
  871. ** SQL comments, then no SQL statements are evaluated and the database
  872. ** is not changed.
  873. **
  874. ** Restrictions:
  875. **
  876. ** <ul>
  877. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  878. ** is a valid and open [database connection].
  879. ** <li> The application must not close [database connection] specified by
  880. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  881. ** <li> The application must not modify the SQL statement text passed into
  882. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  883. ** </ul>
  884. */
  885. SQLITE_API int sqlite3_exec(
  886. sqlite3*, /* An open database */
  887. const char *sql, /* SQL to be evaluated */
  888. int (*callback)(void*,int,char**,char**), /* Callback function */
  889. void *, /* 1st argument to callback */
  890. char **errmsg /* Error msg written here */
  891. );
  892. /*
  893. ** CAPI3REF: Result Codes
  894. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  895. ** KEYWORDS: {result code} {result codes}
  896. **
  897. ** Many SQLite functions return an integer result code from the set shown
  898. ** here in order to indicate success or failure.
  899. **
  900. ** New error codes may be added in future versions of SQLite.
  901. **
  902. ** See also: [SQLITE_IOERR_READ | extended result codes],
  903. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  904. */
  905. #define SQLITE_OK 0 /* Successful result */
  906. /* beginning-of-error-codes */
  907. #define SQLITE_ERROR 1 /* SQL error or missing database */
  908. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  909. #define SQLITE_PERM 3 /* Access permission denied */
  910. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  911. #define SQLITE_BUSY 5 /* The database file is locked */
  912. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  913. #define SQLITE_NOMEM 7 /* A malloc() failed */
  914. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  915. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  916. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  917. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  918. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  919. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  920. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  921. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  922. #define SQLITE_EMPTY 16 /* Database is empty */
  923. #define SQLITE_SCHEMA 17 /* The database schema changed */
  924. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  925. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  926. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  927. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  928. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  929. #define SQLITE_AUTH 23 /* Authorization denied */
  930. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  931. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  932. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  933. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  934. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  935. /* end-of-error-codes */
  936. /*
  937. ** CAPI3REF: Extended Result Codes
  938. ** KEYWORDS: {extended error code} {extended error codes}
  939. ** KEYWORDS: {extended result code} {extended result codes}
  940. **
  941. ** In its default configuration, SQLite API routines return one of 26 integer
  942. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  943. ** these result codes are too coarse-grained. They do not provide as
  944. ** much information about problems as programmers might like. In an effort to
  945. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  946. ** support for additional result codes that provide more detailed information
  947. ** about errors. The extended result codes are enabled or disabled
  948. ** on a per database connection basis using the
  949. ** [sqlite3_extended_result_codes()] API.
  950. **
  951. ** Some of the available extended result codes are listed here.
  952. ** One may expect the number of extended result codes will be expand
  953. ** over time. Software that uses extended result codes should expect
  954. ** to see new result codes in future releases of SQLite.
  955. **
  956. ** The SQLITE_OK result code will never be extended. It will always
  957. ** be exactly zero.
  958. */
  959. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  960. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  961. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  962. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  963. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  964. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  965. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  966. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  967. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  968. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  969. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  970. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  971. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  972. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  973. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  974. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  975. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  976. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  977. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  978. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  979. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  980. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  981. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  982. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  983. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  984. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  985. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  986. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  987. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  988. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  989. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  990. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  991. /*
  992. ** CAPI3REF: Flags For File Open Operations
  993. **
  994. ** These bit values are intended for use in the
  995. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  996. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  997. */
  998. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  999. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1000. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1001. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1002. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1003. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1004. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1005. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1006. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1007. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1008. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1009. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1010. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1011. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1012. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1013. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1014. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1015. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1016. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1017. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1018. /* Reserved: 0x00F00000 */
  1019. /*
  1020. ** CAPI3REF: Device Characteristics
  1021. **
  1022. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1023. ** object returns an integer which is a vector of these
  1024. ** bit values expressing I/O characteristics of the mass storage
  1025. ** device that holds the file that the [sqlite3_io_methods]
  1026. ** refers to.
  1027. **
  1028. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1029. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1030. ** mean that writes of blocks that are nnn bytes in size and
  1031. ** are aligned to an address which is an integer multiple of
  1032. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1033. ** that when data is appended to a file, the data is appended
  1034. ** first then the size of the file is extended, never the other
  1035. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1036. ** information is written to disk in the same order as calls
  1037. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1038. ** after reboot following a crash or power loss, the only bytes in a
  1039. ** file that were written at the application level might have changed
  1040. ** and that adjacent bytes, even bytes within the same sector are
  1041. ** guaranteed to be unchanged.
  1042. */
  1043. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1044. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1045. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1046. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1047. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1048. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1049. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1050. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1051. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1052. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1053. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1054. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1055. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1056. /*
  1057. ** CAPI3REF: File Locking Levels
  1058. **
  1059. ** SQLite uses one of these integer values as the second
  1060. ** argument to calls it makes to the xLock() and xUnlock() methods
  1061. ** of an [sqlite3_io_methods] object.
  1062. */
  1063. #define SQLITE_LOCK_NONE 0
  1064. #define SQLITE_LOCK_SHARED 1
  1065. #define SQLITE_LOCK_RESERVED 2
  1066. #define SQLITE_LOCK_PENDING 3
  1067. #define SQLITE_LOCK_EXCLUSIVE 4
  1068. /*
  1069. ** CAPI3REF: Synchronization Type Flags
  1070. **
  1071. ** When SQLite invokes the xSync() method of an
  1072. ** [sqlite3_io_methods] object it uses a combination of
  1073. ** these integer values as the second argument.
  1074. **
  1075. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1076. ** sync operation only needs to flush data to mass storage. Inode
  1077. ** information need not be flushed. If the lower four bits of the flag
  1078. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1079. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1080. ** to use Mac OS X style fullsync instead of fsync().
  1081. **
  1082. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1083. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1084. ** settings. The [synchronous pragma] determines when calls to the
  1085. ** xSync VFS method occur and applies uniformly across all platforms.
  1086. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1087. ** energetic or rigorous or forceful the sync operations are and
  1088. ** only make a difference on Mac OSX for the default SQLite code.
  1089. ** (Third-party VFS implementations might also make the distinction
  1090. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1091. ** operating systems natively supported by SQLite, only Mac OSX
  1092. ** cares about the difference.)
  1093. */
  1094. #define SQLITE_SYNC_NORMAL 0x00002
  1095. #define SQLITE_SYNC_FULL 0x00003
  1096. #define SQLITE_SYNC_DATAONLY 0x00010
  1097. /*
  1098. ** CAPI3REF: OS Interface Open File Handle
  1099. **
  1100. ** An [sqlite3_file] object represents an open file in the
  1101. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1102. ** implementations will
  1103. ** want to subclass this object by appending additional fields
  1104. ** for their own use. The pMethods entry is a pointer to an
  1105. ** [sqlite3_io_methods] object that defines methods for performing
  1106. ** I/O operations on the open file.
  1107. */
  1108. typedef struct sqlite3_file sqlite3_file;
  1109. struct sqlite3_file {
  1110. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1111. };
  1112. /*
  1113. ** CAPI3REF: OS Interface File Virtual Methods Object
  1114. **
  1115. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1116. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1117. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1118. ** This object defines the methods used to perform various operations
  1119. ** against the open file represented by the [sqlite3_file] object.
  1120. **
  1121. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1122. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1123. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1124. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1125. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1126. ** to NULL.
  1127. **
  1128. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1129. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1130. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1131. ** flag may be ORed in to indicate that only the data of the file
  1132. ** and not its inode needs to be synced.
  1133. **
  1134. ** The integer values to xLock() and xUnlock() are one of
  1135. ** <ul>
  1136. ** <li> [SQLITE_LOCK_NONE],
  1137. ** <li> [SQLITE_LOCK_SHARED],
  1138. ** <li> [SQLITE_LOCK_RESERVED],
  1139. ** <li> [SQLITE_LOCK_PENDING], or
  1140. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1141. ** </ul>
  1142. ** xLock() increases the lock. xUnlock() decreases the lock.
  1143. ** The xCheckReservedLock() method checks whether any database connection,
  1144. ** either in this process or in some other process, is holding a RESERVED,
  1145. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1146. ** if such a lock exists and false otherwise.
  1147. **
  1148. ** The xFileControl() method is a generic interface that allows custom
  1149. ** VFS implementations to directly control an open file using the
  1150. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1151. ** integer opcode. The third argument is a generic pointer intended to
  1152. ** point to a structure that may contain arguments or space in which to
  1153. ** write return values. Potential uses for xFileControl() might be
  1154. ** functions to enable blocking locks with timeouts, to change the
  1155. ** locking strategy (for example to use dot-file locks), to inquire
  1156. ** about the status of a lock, or to break stale locks. The SQLite
  1157. ** core reserves all opcodes less than 100 for its own use.
  1158. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  1159. ** Applications that define a custom xFileControl method should use opcodes
  1160. ** greater than 100 to avoid conflicts. VFS implementations should
  1161. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1162. ** recognize.
  1163. **
  1164. ** The xSectorSize() method returns the sector size of the
  1165. ** device that underlies the file. The sector size is the
  1166. ** minimum write that can be performed without disturbing
  1167. ** other bytes in the file. The xDeviceCharacteristics()
  1168. ** method returns a bit vector describing behaviors of the
  1169. ** underlying device:
  1170. **
  1171. ** <ul>
  1172. ** <li> [SQLITE_IOCAP_ATOMIC]
  1173. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1174. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1175. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1176. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1177. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1178. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1179. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1180. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1181. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1182. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1183. ** </ul>
  1184. **
  1185. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1186. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1187. ** mean that writes of blocks that are nnn bytes in size and
  1188. ** are aligned to an address which is an integer multiple of
  1189. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1190. ** that when data is appended to a file, the data is appended
  1191. ** first then the size of the file is extended, never the other
  1192. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1193. ** information is written to disk in the same order as calls
  1194. ** to xWrite().
  1195. **
  1196. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1197. ** in the unread portions of the buffer with zeros. A VFS that
  1198. ** fails to zero-fill short reads might seem to work. However,
  1199. ** failure to zero-fill short reads will eventually lead to
  1200. ** database corruption.
  1201. */
  1202. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1203. struct sqlite3_io_methods {
  1204. int iVersion;
  1205. int (*xClose)(sqlite3_file*);
  1206. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1207. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1208. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1209. int (*xSync)(sqlite3_file*, int flags);
  1210. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1211. int (*xLock)(sqlite3_file*, int);
  1212. int (*xUnlock)(sqlite3_file*, int);
  1213. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1214. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1215. int (*xSectorSize)(sqlite3_file*);
  1216. int (*xDeviceCharacteristics)(sqlite3_file*);
  1217. /* Methods above are valid for version 1 */
  1218. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1219. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1220. void (*xShmBarrier)(sqlite3_file*);
  1221. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1222. /* Methods above are valid for version 2 */
  1223. /* Additional methods may be added in future releases */
  1224. };
  1225. /*
  1226. ** CAPI3REF: Standard File Control Opcodes
  1227. **
  1228. ** These integer constants are opcodes for the xFileControl method
  1229. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1230. ** interface.
  1231. **
  1232. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1233. ** opcode causes the xFileControl method to write the current state of
  1234. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1235. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1236. ** into an integer that the pArg argument points to. This capability
  1237. ** is used during testing and only needs to be supported when SQLITE_TEST
  1238. ** is defined.
  1239. ** <ul>
  1240. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1241. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1242. ** layer a hint of how large the database file will grow to be during the
  1243. ** current transaction. This hint is not guaranteed to be accurate but it
  1244. ** is often close. The underlying VFS might choose to preallocate database
  1245. ** file space based on this hint in order to help writes to the database
  1246. ** file run faster.
  1247. **
  1248. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1249. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1250. ** extends and truncates the database file in chunks of a size specified
  1251. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1252. ** point to an integer (type int) containing the new chunk-size to use
  1253. ** for the nominated database. Allocating database file space in large
  1254. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1255. ** improve performance on some systems.
  1256. **
  1257. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1258. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1259. ** to the [sqlite3_file] object associated with a particular database
  1260. ** connection. See the [sqlite3_file_control()] documentation for
  1261. ** additional information.
  1262. **
  1263. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1264. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  1265. ** SQLite and sent to all VFSes in place of a call to the xSync method
  1266. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  1267. ** Some specialized VFSes need this signal in order to operate correctly
  1268. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  1269. ** VFSes do not need this signal and should silently ignore this opcode.
  1270. ** Applications should not call [sqlite3_file_control()] with this
  1271. ** opcode as doing so may disrupt the operation of the specialized VFSes
  1272. ** that do require it.
  1273. **
  1274. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1275. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1276. ** retry counts and intervals for certain disk I/O operations for the
  1277. ** windows [VFS] in order to provide robustness in the presence of
  1278. ** anti-virus programs. By default, the windows VFS will retry file read,
  1279. ** file write, and file delete operations up to 10 times, with a delay
  1280. ** of 25 milliseconds before the first retry and with the delay increasing
  1281. ** by an additional 25 milliseconds with each subsequent retry. This
  1282. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1283. ** to be adjusted. The values are changed for all database connections
  1284. ** within the same process. The argument is a pointer to an array of two
  1285. ** integers where the first integer i the new retry count and the second
  1286. ** integer is the delay. If either integer is negative, then the setting
  1287. ** is not changed but instead the prior value of that setting is written
  1288. ** into the array entry, allowing the current retry settings to be
  1289. ** interrogated. The zDbName parameter is ignored.
  1290. **
  1291. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1292. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1293. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1294. ** write ahead log and shared memory files used for transaction control
  1295. ** are automatically deleted when the latest connection to the database
  1296. ** closes. Setting persistent WAL mode causes those files to persist after
  1297. ** close. Persisting the files is useful when other processes that do not
  1298. ** have write permission on the directory containing the database file want
  1299. ** to read the database file, as the WAL and shared memory files must exist
  1300. ** in order for the database to be readable. The fourth parameter to
  1301. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1302. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1303. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1304. ** WAL persistence setting.
  1305. **
  1306. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1307. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1308. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1309. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1310. ** xDeviceCharacteristics methods. The fourth parameter to
  1311. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1312. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1313. ** mode. If the integer is -1, then it is overwritten with the current
  1314. ** zero-damage mode setting.
  1315. **
  1316. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1317. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1318. ** a write transaction to indicate that, unless it is rolled back for some
  1319. ** reason, the entire database file will be overwritten by the current
  1320. ** transaction. This is used by VACUUM operations.
  1321. **
  1322. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1323. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1324. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1325. ** final bottom-level VFS are written into memory obtained from
  1326. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1327. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1328. ** The caller is responsible for freeing the memory when done. As with
  1329. ** all file-control actions, there is no guarantee that this will actually
  1330. ** do anything. Callers should initialize the char* variable to a NULL
  1331. ** pointer in case this file-control is not implemented. This file-control
  1332. ** is intended for diagnostic use only.
  1333. **
  1334. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1335. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1336. ** file control is sent to the open [sqlite3_file] object corresponding
  1337. ** to the database file to which the pragma statement refers. ^The argument
  1338. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1339. ** pointers to strings (char**) in which the second element of the array
  1340. ** is the name of the pragma and the third element is the argument to the
  1341. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1342. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1343. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1344. ** or the equivalent and that string will become the result of the pragma or
  1345. ** the error message if the pragma fails. ^If the
  1346. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1347. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1348. ** file control returns [SQLITE_OK], then the parser assumes that the
  1349. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1350. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1351. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1352. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1353. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1354. ** file control occurs at the beginning of pragma statement analysis and so
  1355. ** it is able to override built-in [PRAGMA] statements.
  1356. **
  1357. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1358. ** ^This file-control may be invoked by SQLite on the database file handle
  1359. ** shortly after it is opened in order to provide a custom VFS with access
  1360. ** to the connections busy-handler callback. The argument is of type (void **)
  1361. ** - an array of two (void *) values. The first (void *) actually points
  1362. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1363. ** busy-handler, this function should be invoked with the second (void *) in
  1364. ** the array as the only argument. If it returns non-zero, then the operation
  1365. ** should be retried. If it returns zero, the custom VFS should abandon the
  1366. ** current operation.
  1367. **
  1368. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1369. ** ^Application can invoke this file-control to have SQLite generate a
  1370. ** temporary filename using the same algorithm that is followed to generate
  1371. ** temporary filenames for TEMP tables and other internal uses. The
  1372. ** argument should be a char** which will be filled with the filename
  1373. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1374. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1375. **
  1376. ** </ul>
  1377. */
  1378. #define SQLITE_FCNTL_LOCKSTATE 1
  1379. #define SQLITE_GET_LOCKPROXYFILE 2
  1380. #define SQLITE_SET_LOCKPROXYFILE 3
  1381. #define SQLITE_LAST_ERRNO 4
  1382. #define SQLITE_FCNTL_SIZE_HINT 5
  1383. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1384. #define SQLITE_FCNTL_FILE_POINTER 7
  1385. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1386. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1387. #define SQLITE_FCNTL_PERSIST_WAL 10
  1388. #define SQLITE_FCNTL_OVERWRITE 11
  1389. #define SQLITE_FCNTL_VFSNAME 12
  1390. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1391. #define SQLITE_FCNTL_PRAGMA 14
  1392. #define SQLITE_FCNTL_BUSYHANDLER 15
  1393. #define SQLITE_FCNTL_TEMPFILENAME 16
  1394. /*
  1395. ** CAPI3REF: Mutex Handle
  1396. **
  1397. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1398. ** abstract type for a mutex object. The SQLite core never looks
  1399. ** at the internal representation of an [sqlite3_mutex]. It only
  1400. ** deals with pointers to the [sqlite3_mutex] object.
  1401. **
  1402. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1403. */
  1404. typedef struct sqlite3_mutex sqlite3_mutex;
  1405. /*
  1406. ** CAPI3REF: OS Interface Object
  1407. **
  1408. ** An instance of the sqlite3_vfs object defines the interface between
  1409. ** the SQLite core and the underlying operating system. The "vfs"
  1410. ** in the name of the object stands for "virtual file system". See
  1411. ** the [VFS | VFS documentation] for further information.
  1412. **
  1413. ** The value of the iVersion field is initially 1 but may be larger in
  1414. ** future versions of SQLite. Additional fields may be appended to this
  1415. ** object when the iVersion value is increased. Note that the structure
  1416. ** of the sqlite3_vfs object changes in the transaction between
  1417. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1418. ** modified.
  1419. **
  1420. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1421. ** structure used by this VFS. mxPathname is the maximum length of
  1422. ** a pathname in this VFS.
  1423. **
  1424. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1425. ** the pNext pointer. The [sqlite3_vfs_register()]
  1426. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1427. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1428. ** searches the list. Neither the application code nor the VFS
  1429. ** implementation should use the pNext pointer.
  1430. **
  1431. ** The pNext field is the only field in the sqlite3_vfs
  1432. ** structure that SQLite will ever modify. SQLite will only access
  1433. ** or modify this field while holding a particular static mutex.
  1434. ** The application should never modify anything within the sqlite3_vfs
  1435. ** object once the object has been registered.
  1436. **
  1437. ** The zName field holds the name of the VFS module. The name must
  1438. ** be unique across all VFS modules.
  1439. **
  1440. ** [[sqlite3_vfs.xOpen]]
  1441. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1442. ** is either a NULL pointer or string obtained
  1443. ** from xFullPathname() with an optional suffix added.
  1444. ** ^If a suffix is added to the zFilename parameter, it will
  1445. ** consist of a single "-" character followed by no more than
  1446. ** 11 alphanumeric and/or "-" characters.
  1447. ** ^SQLite further guarantees that
  1448. ** the string will be valid and unchanged until xClose() is
  1449. ** called. Because of the previous sentence,
  1450. ** the [sqlite3_file] can safely store a pointer to the
  1451. ** filename if it needs to remember the filename for some reason.
  1452. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1453. ** must invent its own temporary name for the file. ^Whenever the
  1454. ** xFilename parameter is NULL it will also be the case that the
  1455. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1456. **
  1457. ** The flags argument to xOpen() includes all bits set in
  1458. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1459. ** or [sqlite3_open16()] is used, then flags includes at least
  1460. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1461. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1462. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1463. **
  1464. ** ^(SQLite will also add one of the following flags to the xOpen()
  1465. ** call, depending on the object being opened:
  1466. **
  1467. ** <ul>
  1468. ** <li> [SQLITE_OPEN_MAIN_DB]
  1469. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1470. ** <li> [SQLITE_OPEN_TEMP_DB]
  1471. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1472. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1473. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1474. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1475. ** <li> [SQLITE_OPEN_WAL]
  1476. ** </ul>)^
  1477. **
  1478. ** The file I/O implementation can use the object type flags to
  1479. ** change the way it deals with files. For example, an application
  1480. ** that does not care about crash recovery or rollback might make
  1481. ** the open of a journal file a no-op. Writes to this journal would
  1482. ** also be no-ops, and any attempt to read the journal would return
  1483. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1484. ** file will be doing page-aligned sector reads and writes in a random
  1485. ** order and set up its I/O subsystem accordingly.
  1486. **
  1487. ** SQLite might also add one of the following flags to the xOpen method:
  1488. **
  1489. ** <ul>
  1490. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1491. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1492. ** </ul>
  1493. **
  1494. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1495. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1496. ** will be set for TEMP databases and their journals, transient
  1497. ** databases, and subjournals.
  1498. **
  1499. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1500. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1501. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1502. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1503. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1504. ** be created, and that it is an error if it already exists.
  1505. ** It is <i>not</i> used to indicate the file should be opened
  1506. ** for exclusive access.
  1507. **
  1508. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1509. ** to hold the [sqlite3_file] structure passed as the third
  1510. ** argument to xOpen. The xOpen method does not have to
  1511. ** allocate the structure; it should just fill it in. Note that
  1512. ** the xOpen method must set the sqlite3_file.pMethods to either
  1513. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1514. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1515. ** element will be valid after xOpen returns regardless of the success
  1516. ** or failure of the xOpen call.
  1517. **
  1518. ** [[sqlite3_vfs.xAccess]]
  1519. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1520. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1521. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1522. ** to test whether a file is at least readable. The file can be a
  1523. ** directory.
  1524. **
  1525. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1526. ** output buffer xFullPathname. The exact size of the output buffer
  1527. ** is also passed as a parameter to both methods. If the output buffer
  1528. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1529. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1530. ** to prevent this by setting mxPathname to a sufficiently large value.
  1531. **
  1532. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1533. ** interfaces are not strictly a part of the filesystem, but they are
  1534. ** included in the VFS structure for completeness.
  1535. ** The xRandomness() function attempts to return nBytes bytes
  1536. ** of good-quality randomness into zOut. The return value is
  1537. ** the actual number of bytes of randomness obtained.
  1538. ** The xSleep() method causes the calling thread to sleep for at
  1539. ** least the number of microseconds given. ^The xCurrentTime()
  1540. ** method returns a Julian Day Number for the current date and time as
  1541. ** a floating point value.
  1542. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1543. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1544. ** a 24-hour day).
  1545. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1546. ** date and time if that method is available (if iVersion is 2 or
  1547. ** greater and the function pointer is not NULL) and will fall back
  1548. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1549. **
  1550. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1551. ** are not used by the SQLite core. These optional interfaces are provided
  1552. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1553. ** system calls with functions under its control, a test program can
  1554. ** simulate faults and error conditions that would otherwise be difficult
  1555. ** or impossible to induce. The set of system calls that can be overridden
  1556. ** varies from one VFS to another, and from one version of the same VFS to the
  1557. ** next. Applications that use these interfaces must be prepared for any
  1558. ** or all of these interfaces to be NULL or for their behavior to change
  1559. ** from one release to the next. Applications must not attempt to access
  1560. ** any of these methods if the iVersion of the VFS is less than 3.
  1561. */
  1562. typedef struct sqlite3_vfs sqlite3_vfs;
  1563. typedef void (*sqlite3_syscall_ptr)(void);
  1564. struct sqlite3_vfs {
  1565. int iVersion; /* Structure version number (currently 3) */
  1566. int szOsFile; /* Size of subclassed sqlite3_file */
  1567. int mxPathname; /* Maximum file pathname length */
  1568. sqlite3_vfs *pNext; /* Next registered VFS */
  1569. const char *zName; /* Name of this virtual file system */
  1570. void *pAppData; /* Pointer to application-specific data */
  1571. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1572. int flags, int *pOutFlags);
  1573. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1574. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1575. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1576. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1577. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1578. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1579. void (*xDlClose)(sqlite3_vfs*, void*);
  1580. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1581. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1582. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1583. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1584. /*
  1585. ** The methods above are in version 1 of the sqlite_vfs object
  1586. ** definition. Those that follow are added in version 2 or later
  1587. */
  1588. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1589. /*
  1590. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1591. ** Those below are for version 3 and greater.
  1592. */
  1593. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1594. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1595. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1596. /*
  1597. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1598. ** New fields may be appended in figure versions. The iVersion
  1599. ** value will increment whenever this happens.
  1600. */
  1601. };
  1602. /*
  1603. ** CAPI3REF: Flags for the xAccess VFS method
  1604. **
  1605. ** These integer constants can be used as the third parameter to
  1606. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1607. ** what kind of permissions the xAccess method is looking for.
  1608. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1609. ** simply checks whether the file exists.
  1610. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1611. ** checks whether the named directory is both readable and writable
  1612. ** (in other words, if files can be added, removed, and renamed within
  1613. ** the directory).
  1614. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1615. ** [temp_store_directory pragma], though this could change in a future
  1616. ** release of SQLite.
  1617. ** With SQLITE_ACCESS_READ, the xAccess method
  1618. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1619. ** currently unused, though it might be used in a future release of
  1620. ** SQLite.
  1621. */
  1622. #define SQLITE_ACCESS_EXISTS 0
  1623. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1624. #define SQLITE_ACCESS_READ 2 /* Unused */
  1625. /*
  1626. ** CAPI3REF: Flags for the xShmLock VFS method
  1627. **
  1628. ** These integer constants define the various locking operations
  1629. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1630. ** following are the only legal combinations of flags to the
  1631. ** xShmLock method:
  1632. **
  1633. ** <ul>
  1634. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1635. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1636. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1637. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1638. ** </ul>
  1639. **
  1640. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1641. ** was given no the corresponding lock.
  1642. **
  1643. ** The xShmLock method can transition between unlocked and SHARED or
  1644. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1645. ** and EXCLUSIVE.
  1646. */
  1647. #define SQLITE_SHM_UNLOCK 1
  1648. #define SQLITE_SHM_LOCK 2
  1649. #define SQLITE_SHM_SHARED 4
  1650. #define SQLITE_SHM_EXCLUSIVE 8
  1651. /*
  1652. ** CAPI3REF: Maximum xShmLock index
  1653. **
  1654. ** The xShmLock method on [sqlite3_io_methods] may use values
  1655. ** between 0 and this upper bound as its "offset" argument.
  1656. ** The SQLite core will never attempt to acquire or release a
  1657. ** lock outside of this range
  1658. */
  1659. #define SQLITE_SHM_NLOCK 8
  1660. /*
  1661. ** CAPI3REF: Initialize The SQLite Library
  1662. **
  1663. ** ^The sqlite3_initialize() routine initializes the
  1664. ** SQLite library. ^The sqlite3_shutdown() routine
  1665. ** deallocates any resources that were allocated by sqlite3_initialize().
  1666. ** These routines are designed to aid in process initialization and
  1667. ** shutdown on embedded systems. Workstation applications using
  1668. ** SQLite normally do not need to invoke either of these routines.
  1669. **
  1670. ** A call to sqlite3_initialize() is an "effective" call if it is
  1671. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1672. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1673. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1674. ** of sqlite3_initialize() does any initialization. All other calls
  1675. ** are harmless no-ops.)^
  1676. **
  1677. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1678. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1679. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1680. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1681. **
  1682. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1683. ** is not. The sqlite3_shutdown() interface must only be called from a
  1684. ** single thread. All open [database connections] must be closed and all
  1685. ** other SQLite resources must be deallocated prior to invoking
  1686. ** sqlite3_shutdown().
  1687. **
  1688. ** Among other things, ^sqlite3_initialize() will invoke
  1689. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1690. ** will invoke sqlite3_os_end().
  1691. **
  1692. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1693. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1694. ** the library (perhaps it is unable to allocate a needed resource such
  1695. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1696. **
  1697. ** ^The sqlite3_initialize() routine is called internally by many other
  1698. ** SQLite interfaces so that an application usually does not need to
  1699. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1700. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1701. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1702. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1703. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1704. ** are omitted and the application must call sqlite3_initialize() directly
  1705. ** prior to using any other SQLite interface. For maximum portability,
  1706. ** it is recommended that applications always invoke sqlite3_initialize()
  1707. ** directly prior to using any other SQLite interface. Future releases
  1708. ** of SQLite may require this. In other words, the behavior exhibited
  1709. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1710. ** default behavior in some future release of SQLite.
  1711. **
  1712. ** The sqlite3_os_init() routine does operating-system specific
  1713. ** initialization of the SQLite library. The sqlite3_os_end()
  1714. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1715. ** performed by these routines include allocation or deallocation
  1716. ** of static resources, initialization of global variables,
  1717. ** setting up a default [sqlite3_vfs] module, or setting up
  1718. ** a default configuration using [sqlite3_config()].
  1719. **
  1720. ** The application should never invoke either sqlite3_os_init()
  1721. ** or sqlite3_os_end() directly. The application should only invoke
  1722. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1723. ** interface is called automatically by sqlite3_initialize() and
  1724. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1725. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1726. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1727. ** When [custom builds | built for other platforms]
  1728. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1729. ** option) the application must supply a suitable implementation for
  1730. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1731. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1732. ** must return [SQLITE_OK] on success and some other [error code] upon
  1733. ** failure.
  1734. */
  1735. SQLITE_API int sqlite3_initialize(void);
  1736. SQLITE_API int sqlite3_shutdown(void);
  1737. SQLITE_API int sqlite3_os_init(void);
  1738. SQLITE_API int sqlite3_os_end(void);
  1739. /*
  1740. ** CAPI3REF: Configuring The SQLite Library
  1741. **
  1742. ** The sqlite3_config() interface is used to make global configuration
  1743. ** changes to SQLite in order to tune SQLite to the specific needs of
  1744. ** the application. The default configuration is recommended for most
  1745. ** applications and so this routine is usually not necessary. It is
  1746. ** provided to support rare applications with unusual needs.
  1747. **
  1748. ** The sqlite3_config() interface is not threadsafe. The application
  1749. ** must insure that no other SQLite interfaces are invoked by other
  1750. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1751. ** may only be invoked prior to library initialization using
  1752. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1753. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1754. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1755. ** Note, however, that ^sqlite3_config() can be called as part of the
  1756. ** implementation of an application-defined [sqlite3_os_init()].
  1757. **
  1758. ** The first argument to sqlite3_config() is an integer
  1759. ** [configuration option] that determines
  1760. ** what property of SQLite is to be configured. Subsequent arguments
  1761. ** vary depending on the [configuration option]
  1762. ** in the first argument.
  1763. **
  1764. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1765. ** ^If the option is unknown or SQLite is unable to set the option
  1766. ** then this routine returns a non-zero [error code].
  1767. */
  1768. SQLITE_API int sqlite3_config(int, ...);
  1769. /*
  1770. ** CAPI3REF: Configure database connections
  1771. **
  1772. ** The sqlite3_db_config() interface is used to make configuration
  1773. ** changes to a [database connection]. The interface is similar to
  1774. ** [sqlite3_config()] except that the changes apply to a single
  1775. ** [database connection] (specified in the first argument).
  1776. **
  1777. ** The second argument to sqlite3_db_config(D,V,...) is the
  1778. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1779. ** that indicates what aspect of the [database connection] is being configured.
  1780. ** Subsequent arguments vary depending on the configuration verb.
  1781. **
  1782. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1783. ** the call is considered successful.
  1784. */
  1785. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1786. /*
  1787. ** CAPI3REF: Memory Allocation Routines
  1788. **
  1789. ** An instance of this object defines the interface between SQLite
  1790. ** and low-level memory allocation routines.
  1791. **
  1792. ** This object is used in only one place in the SQLite interface.
  1793. ** A pointer to an instance of this object is the argument to
  1794. ** [sqlite3_config()] when the configuration option is
  1795. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1796. ** By creating an instance of this object
  1797. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1798. ** during configuration, an application can specify an alternative
  1799. ** memory allocation subsystem for SQLite to use for all of its
  1800. ** dynamic memory needs.
  1801. **
  1802. ** Note that SQLite comes with several [built-in memory allocators]
  1803. ** that are perfectly adequate for the overwhelming majority of applications
  1804. ** and that this object is only useful to a tiny minority of applications
  1805. ** with specialized memory allocation requirements. This object is
  1806. ** also used during testing of SQLite in order to specify an alternative
  1807. ** memory allocator that simulates memory out-of-memory conditions in
  1808. ** order to verify that SQLite recovers gracefully from such
  1809. ** conditions.
  1810. **
  1811. ** The xMalloc, xRealloc, and xFree methods must work like the
  1812. ** malloc(), realloc() and free() functions from the standard C library.
  1813. ** ^SQLite guarantees that the second argument to
  1814. ** xRealloc is always a value returned by a prior call to xRoundup.
  1815. **
  1816. ** xSize should return the allocated size of a memory allocation
  1817. ** previously obtained from xMalloc or xRealloc. The allocated size
  1818. ** is always at least as big as the requested size but may be larger.
  1819. **
  1820. ** The xRoundup method returns what would be the allocated size of
  1821. ** a memory allocation given a particular requested size. Most memory
  1822. ** allocators round up memory allocations at least to the next multiple
  1823. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1824. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1825. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1826. ** that causes the corresponding memory allocation to fail.
  1827. **
  1828. ** The xInit method initializes the memory allocator. (For example,
  1829. ** it might allocate any require mutexes or initialize internal data
  1830. ** structures. The xShutdown method is invoked (indirectly) by
  1831. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1832. ** by xInit. The pAppData pointer is used as the only parameter to
  1833. ** xInit and xShutdown.
  1834. **
  1835. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1836. ** the xInit method, so the xInit method need not be threadsafe. The
  1837. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1838. ** not need to be threadsafe either. For all other methods, SQLite
  1839. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1840. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1841. ** it is by default) and so the methods are automatically serialized.
  1842. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1843. ** methods must be threadsafe or else make their own arrangements for
  1844. ** serialization.
  1845. **
  1846. ** SQLite will never invoke xInit() more than once without an intervening
  1847. ** call to xShutdown().
  1848. */
  1849. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1850. struct sqlite3_mem_methods {
  1851. void *(*xMalloc)(int); /* Memory allocation function */
  1852. void (*xFree)(void*); /* Free a prior allocation */
  1853. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1854. int (*xSize)(void*); /* Return the size of an allocation */
  1855. int (*xRoundup)(int); /* Round up request size to allocation size */
  1856. int (*xInit)(void*); /* Initialize the memory allocator */
  1857. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1858. void *pAppData; /* Argument to xInit() and xShutdown() */
  1859. };
  1860. /*
  1861. ** CAPI3REF: Configuration Options
  1862. ** KEYWORDS: {configuration option}
  1863. **
  1864. ** These constants are the available integer configuration options that
  1865. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1866. **
  1867. ** New configuration options may be added in future releases of SQLite.
  1868. ** Existing configuration options might be discontinued. Applications
  1869. ** should check the return code from [sqlite3_config()] to make sure that
  1870. ** the call worked. The [sqlite3_config()] interface will return a
  1871. ** non-zero [error code] if a discontinued or unsupported configuration option
  1872. ** is invoked.
  1873. **
  1874. ** <dl>
  1875. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1876. ** <dd>There are no arguments to this option. ^This option sets the
  1877. ** [threading mode] to Single-thread. In other words, it disables
  1878. ** all mutexing and puts SQLite into a mode where it can only be used
  1879. ** by a single thread. ^If SQLite is compiled with
  1880. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1881. ** it is not possible to change the [threading mode] from its default
  1882. ** value of Single-thread and so [sqlite3_config()] will return
  1883. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1884. ** configuration option.</dd>
  1885. **
  1886. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1887. ** <dd>There are no arguments to this option. ^This option sets the
  1888. ** [threading mode] to Multi-thread. In other words, it disables
  1889. ** mutexing on [database connection] and [prepared statement] objects.
  1890. ** The application is responsible for serializing access to
  1891. ** [database connections] and [prepared statements]. But other mutexes
  1892. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1893. ** environment as long as no two threads attempt to use the same
  1894. ** [database connection] at the same time. ^If SQLite is compiled with
  1895. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1896. ** it is not possible to set the Multi-thread [threading mode] and
  1897. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1898. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1899. **
  1900. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1901. ** <dd>There are no arguments to this option. ^This option sets the
  1902. ** [threading mode] to Serialized. In other words, this option enables
  1903. ** all mutexes including the recursive
  1904. ** mutexes on [database connection] and [prepared statement] objects.
  1905. ** In this mode (which is the default when SQLite is compiled with
  1906. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1907. ** to [database connections] and [prepared statements] so that the
  1908. ** application is free to use the same [database connection] or the
  1909. ** same [prepared statement] in different threads at the same time.
  1910. ** ^If SQLite is compiled with
  1911. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1912. ** it is not possible to set the Serialized [threading mode] and
  1913. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1914. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1915. **
  1916. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1917. ** <dd> ^(This option takes a single argument which is a pointer to an
  1918. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1919. ** alternative low-level memory allocation routines to be used in place of
  1920. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1921. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1922. ** before the [sqlite3_config()] call returns.</dd>
  1923. **
  1924. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1925. ** <dd> ^(This option takes a single argument which is a pointer to an
  1926. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1927. ** structure is filled with the currently defined memory allocation routines.)^
  1928. ** This option can be used to overload the default memory allocation
  1929. ** routines with a wrapper that simulations memory allocation failure or
  1930. ** tracks memory usage, for example. </dd>
  1931. **
  1932. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1933. ** <dd> ^This option takes single argument of type int, interpreted as a
  1934. ** boolean, which enables or disables the collection of memory allocation
  1935. ** statistics. ^(When memory allocation statistics are disabled, the
  1936. ** following SQLite interfaces become non-operational:
  1937. ** <ul>
  1938. ** <li> [sqlite3_memory_used()]
  1939. ** <li> [sqlite3_memory_highwater()]
  1940. ** <li> [sqlite3_soft_heap_limit64()]
  1941. ** <li> [sqlite3_status()]
  1942. ** </ul>)^
  1943. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1944. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1945. ** allocation statistics are disabled by default.
  1946. ** </dd>
  1947. **
  1948. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1949. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1950. ** scratch memory. There are three arguments: A pointer an 8-byte
  1951. ** aligned memory buffer from which the scratch allocations will be
  1952. ** drawn, the size of each scratch allocation (sz),
  1953. ** and the maximum number of scratch allocations (N). The sz
  1954. ** argument must be a multiple of 16.
  1955. ** The first argument must be a pointer to an 8-byte aligned buffer
  1956. ** of at least sz*N bytes of memory.
  1957. ** ^SQLite will use no more than two scratch buffers per thread. So
  1958. ** N should be set to twice the expected maximum number of threads.
  1959. ** ^SQLite will never require a scratch buffer that is more than 6
  1960. ** times the database page size. ^If SQLite needs needs additional
  1961. ** scratch memory beyond what is provided by this configuration option, then
  1962. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1963. **
  1964. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1965. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1966. ** the database page cache with the default page cache implementation.
  1967. ** This configuration should not be used if an application-define page
  1968. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1969. ** There are three arguments to this option: A pointer to 8-byte aligned
  1970. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1971. ** The sz argument should be the size of the largest database page
  1972. ** (a power of two between 512 and 32768) plus a little extra for each
  1973. ** page header. ^The page header size is 20 to 40 bytes depending on
  1974. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1975. ** to make sz a little too large. The first
  1976. ** argument should point to an allocation of at least sz*N bytes of memory.
  1977. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1978. ** memory needs for the first N pages that it adds to cache. ^If additional
  1979. ** page cache memory is needed beyond what is provided by this option, then
  1980. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1981. ** The pointer in the first argument must
  1982. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1983. ** will be undefined.</dd>
  1984. **
  1985. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1986. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1987. ** for all of its dynamic memory allocation needs beyond those provided
  1988. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1989. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1990. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1991. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1992. ** to using its default memory allocator (the system malloc() implementation),
  1993. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1994. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1995. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1996. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1997. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1998. ** boundary or subsequent behavior of SQLite will be undefined.
  1999. ** The minimum allocation size is capped at 2**12. Reasonable values
  2000. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2001. **
  2002. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2003. ** <dd> ^(This option takes a single argument which is a pointer to an
  2004. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  2005. ** alternative low-level mutex routines to be used in place
  2006. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  2007. ** content of the [sqlite3_mutex_methods] structure before the call to
  2008. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2009. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2010. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2011. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2012. ** return [SQLITE_ERROR].</dd>
  2013. **
  2014. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2015. ** <dd> ^(This option takes a single argument which is a pointer to an
  2016. ** instance of the [sqlite3_mutex_methods] structure. The
  2017. ** [sqlite3_mutex_methods]
  2018. ** structure is filled with the currently defined mutex routines.)^
  2019. ** This option can be used to overload the default mutex allocation
  2020. ** routines with a wrapper used to track mutex usage for performance
  2021. ** profiling or testing, for example. ^If SQLite is compiled with
  2022. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2023. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2024. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2025. ** return [SQLITE_ERROR].</dd>
  2026. **
  2027. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2028. ** <dd> ^(This option takes two arguments that determine the default
  2029. ** memory allocation for the lookaside memory allocator on each
  2030. ** [database connection]. The first argument is the
  2031. ** size of each lookaside buffer slot and the second is the number of
  2032. ** slots allocated to each database connection.)^ ^(This option sets the
  2033. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2034. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  2035. ** configuration on individual connections.)^ </dd>
  2036. **
  2037. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2038. ** <dd> ^(This option takes a single argument which is a pointer to
  2039. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  2040. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  2041. ** object and uses it for page cache memory allocations.</dd>
  2042. **
  2043. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2044. ** <dd> ^(This option takes a single argument which is a pointer to an
  2045. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  2046. ** page cache implementation into that object.)^ </dd>
  2047. **
  2048. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2049. ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2050. ** function with a call signature of void(*)(void*,int,const char*),
  2051. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2052. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2053. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2054. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2055. ** passed through as the first parameter to the application-defined logger
  2056. ** function whenever that function is invoked. ^The second parameter to
  2057. ** the logger function is a copy of the first parameter to the corresponding
  2058. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2059. ** [extended result code]. ^The third parameter passed to the logger is
  2060. ** log message after formatting via [sqlite3_snprintf()].
  2061. ** The SQLite logging interface is not reentrant; the logger function
  2062. ** supplied by the application must not invoke any SQLite interface.
  2063. ** In a multi-threaded application, the application-defined logger
  2064. ** function must be threadsafe. </dd>
  2065. **
  2066. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2067. ** <dd> This option takes a single argument of type int. If non-zero, then
  2068. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  2069. ** is globally disabled. If URI handling is globally enabled, all filenames
  2070. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  2071. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2072. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2073. ** connection is opened. If it is globally disabled, filenames are
  2074. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2075. ** database connection is opened. By default, URI handling is globally
  2076. ** disabled. The default value may be changed by compiling with the
  2077. ** [SQLITE_USE_URI] symbol defined.
  2078. **
  2079. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2080. ** <dd> This option takes a single integer argument which is interpreted as
  2081. ** a boolean in order to enable or disable the use of covering indices for
  2082. ** full table scans in the query optimizer. The default setting is determined
  2083. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2084. ** if that compile-time option is omitted.
  2085. ** The ability to disable the use of covering indices for full table scans
  2086. ** is because some incorrectly coded legacy applications might malfunction
  2087. ** malfunction when the optimization is enabled. Providing the ability to
  2088. ** disable the optimization allows the older, buggy application code to work
  2089. ** without change even with newer versions of SQLite.
  2090. **
  2091. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2092. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2093. ** <dd> These options are obsolete and should not be used by new code.
  2094. ** They are retained for backwards compatibility but are now no-ops.
  2095. ** </dl>
  2096. **
  2097. ** [[SQLITE_CONFIG_SQLLOG]]
  2098. ** <dt>SQLITE_CONFIG_SQLLOG
  2099. ** <dd>This option is only available if sqlite is compiled with the
  2100. ** SQLITE_ENABLE_SQLLOG pre-processor macro defined. The first argument should
  2101. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2102. ** The second should be of type (void*). The callback is invoked by the library
  2103. ** in three separate circumstances, identified by the value passed as the
  2104. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2105. ** passed as the second argument has just been opened. The third argument
  2106. ** points to a buffer containing the name of the main database file. If the
  2107. ** fourth parameter is 1, then the SQL statement that the third parameter
  2108. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2109. ** the connection being passed as the second parameter is being closed. The
  2110. ** third parameter is passed NULL In this case.
  2111. ** </dl>
  2112. */
  2113. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2114. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2115. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2116. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2117. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2118. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  2119. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2120. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2121. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2122. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2123. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2124. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2125. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2126. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2127. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2128. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2129. #define SQLITE_CONFIG_URI 17 /* int */
  2130. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2131. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2132. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2133. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2134. /*
  2135. ** CAPI3REF: Database Connection Configuration Options
  2136. **
  2137. ** These constants are the available integer configuration options that
  2138. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2139. **
  2140. ** New configuration options may be added in future releases of SQLite.
  2141. ** Existing configuration options might be discontinued. Applications
  2142. ** should check the return code from [sqlite3_db_config()] to make sure that
  2143. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2144. ** non-zero [error code] if a discontinued or unsupported configuration option
  2145. ** is invoked.
  2146. **
  2147. ** <dl>
  2148. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2149. ** <dd> ^This option takes three additional arguments that determine the
  2150. ** [lookaside memory allocator] configuration for the [database connection].
  2151. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2152. ** pointer to a memory buffer to use for lookaside memory.
  2153. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2154. ** may be NULL in which case SQLite will allocate the
  2155. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2156. ** size of each lookaside buffer slot. ^The third argument is the number of
  2157. ** slots. The size of the buffer in the first argument must be greater than
  2158. ** or equal to the product of the second and third arguments. The buffer
  2159. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2160. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2161. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2162. ** configuration for a database connection can only be changed when that
  2163. ** connection is not currently using lookaside memory, or in other words
  2164. ** when the "current value" returned by
  2165. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2166. ** Any attempt to change the lookaside memory configuration when lookaside
  2167. ** memory is in use leaves the configuration unchanged and returns
  2168. ** [SQLITE_BUSY].)^</dd>
  2169. **
  2170. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2171. ** <dd> ^This option is used to enable or disable the enforcement of
  2172. ** [foreign key constraints]. There should be two additional arguments.
  2173. ** The first argument is an integer which is 0 to disable FK enforcement,
  2174. ** positive to enable FK enforcement or negative to leave FK enforcement
  2175. ** unchanged. The second parameter is a pointer to an integer into which
  2176. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2177. ** following this call. The second parameter may be a NULL pointer, in
  2178. ** which case the FK enforcement setting is not reported back. </dd>
  2179. **
  2180. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2181. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2182. ** There should be two additional arguments.
  2183. ** The first argument is an integer which is 0 to disable triggers,
  2184. ** positive to enable triggers or negative to leave the setting unchanged.
  2185. ** The second parameter is a pointer to an integer into which
  2186. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2187. ** following this call. The second parameter may be a NULL pointer, in
  2188. ** which case the trigger setting is not reported back. </dd>
  2189. **
  2190. ** </dl>
  2191. */
  2192. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2193. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2194. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2195. /*
  2196. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2197. **
  2198. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2199. ** [extended result codes] feature of SQLite. ^The extended result
  2200. ** codes are disabled by default for historical compatibility.
  2201. */
  2202. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  2203. /*
  2204. ** CAPI3REF: Last Insert Rowid
  2205. **
  2206. ** ^Each entry in an SQLite table has a unique 64-bit signed
  2207. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2208. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2209. ** names are not also used by explicitly declared columns. ^If
  2210. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2211. ** is another alias for the rowid.
  2212. **
  2213. ** ^This routine returns the [rowid] of the most recent
  2214. ** successful [INSERT] into the database from the [database connection]
  2215. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  2216. ** records the last insert rowid of both ordinary tables and [virtual tables].
  2217. ** ^If no successful [INSERT]s
  2218. ** have ever occurred on that database connection, zero is returned.
  2219. **
  2220. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2221. ** method, then this routine will return the [rowid] of the inserted
  2222. ** row as long as the trigger or virtual table method is running.
  2223. ** But once the trigger or virtual table method ends, the value returned
  2224. ** by this routine reverts to what it was before the trigger or virtual
  2225. ** table method began.)^
  2226. **
  2227. ** ^An [INSERT] that fails due to a constraint violation is not a
  2228. ** successful [INSERT] and does not change the value returned by this
  2229. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2230. ** and INSERT OR ABORT make no changes to the return value of this
  2231. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2232. ** encounters a constraint violation, it does not fail. The
  2233. ** INSERT continues to completion after deleting rows that caused
  2234. ** the constraint problem so INSERT OR REPLACE will always change
  2235. ** the return value of this interface.)^
  2236. **
  2237. ** ^For the purposes of this routine, an [INSERT] is considered to
  2238. ** be successful even if it is subsequently rolled back.
  2239. **
  2240. ** This function is accessible to SQL statements via the
  2241. ** [last_insert_rowid() SQL function].
  2242. **
  2243. ** If a separate thread performs a new [INSERT] on the same
  2244. ** database connection while the [sqlite3_last_insert_rowid()]
  2245. ** function is running and thus changes the last insert [rowid],
  2246. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2247. ** unpredictable and might not equal either the old or the new
  2248. ** last insert [rowid].
  2249. */
  2250. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2251. /*
  2252. ** CAPI3REF: Count The Number Of Rows Modified
  2253. **
  2254. ** ^This function returns the number of database rows that were changed
  2255. ** or inserted or deleted by the most recently completed SQL statement
  2256. ** on the [database connection] specified by the first parameter.
  2257. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  2258. ** or [DELETE] statement are counted. Auxiliary changes caused by
  2259. ** triggers or [foreign key actions] are not counted.)^ Use the
  2260. ** [sqlite3_total_changes()] function to find the total number of changes
  2261. ** including changes caused by triggers and foreign key actions.
  2262. **
  2263. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  2264. ** are not counted. Only real table changes are counted.
  2265. **
  2266. ** ^(A "row change" is a change to a single row of a single table
  2267. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  2268. ** are changed as side effects of [REPLACE] constraint resolution,
  2269. ** rollback, ABORT processing, [DROP TABLE], or by any other
  2270. ** mechanisms do not count as direct row changes.)^
  2271. **
  2272. ** A "trigger context" is a scope of execution that begins and
  2273. ** ends with the script of a [CREATE TRIGGER | trigger].
  2274. ** Most SQL statements are
  2275. ** evaluated outside of any trigger. This is the "top level"
  2276. ** trigger context. If a trigger fires from the top level, a
  2277. ** new trigger context is entered for the duration of that one
  2278. ** trigger. Subtriggers create subcontexts for their duration.
  2279. **
  2280. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  2281. ** not create a new trigger context.
  2282. **
  2283. ** ^This function returns the number of direct row changes in the
  2284. ** most recent INSERT, UPDATE, or DELETE statement within the same
  2285. ** trigger context.
  2286. **
  2287. ** ^Thus, when called from the top level, this function returns the
  2288. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  2289. ** that also occurred at the top level. ^(Within the body of a trigger,
  2290. ** the sqlite3_changes() interface can be called to find the number of
  2291. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  2292. ** statement within the body of the same trigger.
  2293. ** However, the number returned does not include changes
  2294. ** caused by subtriggers since those have their own context.)^
  2295. **
  2296. ** See also the [sqlite3_total_changes()] interface, the
  2297. ** [count_changes pragma], and the [changes() SQL function].
  2298. **
  2299. ** If a separate thread makes changes on the same database connection
  2300. ** while [sqlite3_changes()] is running then the value returned
  2301. ** is unpredictable and not meaningful.
  2302. */
  2303. SQLITE_API int sqlite3_changes(sqlite3*);
  2304. /*
  2305. ** CAPI3REF: Total Number Of Rows Modified
  2306. **
  2307. ** ^This function returns the number of row changes caused by [INSERT],
  2308. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2309. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2310. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2311. ** [foreign key actions]. However,
  2312. ** the count does not include changes used to implement [REPLACE] constraints,
  2313. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2314. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2315. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2316. ** are counted.)^
  2317. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2318. ** the statement that makes them is completed (when the statement handle
  2319. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2320. **
  2321. ** See also the [sqlite3_changes()] interface, the
  2322. ** [count_changes pragma], and the [total_changes() SQL function].
  2323. **
  2324. ** If a separate thread makes changes on the same database connection
  2325. ** while [sqlite3_total_changes()] is running then the value
  2326. ** returned is unpredictable and not meaningful.
  2327. */
  2328. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2329. /*
  2330. ** CAPI3REF: Interrupt A Long-Running Query
  2331. **
  2332. ** ^This function causes any pending database operation to abort and
  2333. ** return at its earliest opportunity. This routine is typically
  2334. ** called in response to a user action such as pressing "Cancel"
  2335. ** or Ctrl-C where the user wants a long query operation to halt
  2336. ** immediately.
  2337. **
  2338. ** ^It is safe to call this routine from a thread different from the
  2339. ** thread that is currently running the database operation. But it
  2340. ** is not safe to call this routine with a [database connection] that
  2341. ** is closed or might close before sqlite3_interrupt() returns.
  2342. **
  2343. ** ^If an SQL operation is very nearly finished at the time when
  2344. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2345. ** to be interrupted and might continue to completion.
  2346. **
  2347. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2348. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2349. ** that is inside an explicit transaction, then the entire transaction
  2350. ** will be rolled back automatically.
  2351. **
  2352. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2353. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2354. ** that are started after the sqlite3_interrupt() call and before the
  2355. ** running statements reaches zero are interrupted as if they had been
  2356. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2357. ** that are started after the running statement count reaches zero are
  2358. ** not effected by the sqlite3_interrupt().
  2359. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2360. ** SQL statements is a no-op and has no effect on SQL statements
  2361. ** that are started after the sqlite3_interrupt() call returns.
  2362. **
  2363. ** If the database connection closes while [sqlite3_interrupt()]
  2364. ** is running then bad things will likely happen.
  2365. */
  2366. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2367. /*
  2368. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2369. **
  2370. ** These routines are useful during command-line input to determine if the
  2371. ** currently entered text seems to form a complete SQL statement or
  2372. ** if additional input is needed before sending the text into
  2373. ** SQLite for parsing. ^These routines return 1 if the input string
  2374. ** appears to be a complete SQL statement. ^A statement is judged to be
  2375. ** complete if it ends with a semicolon token and is not a prefix of a
  2376. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2377. ** string literals or quoted identifier names or comments are not
  2378. ** independent tokens (they are part of the token in which they are
  2379. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2380. ** and comments that follow the final semicolon are ignored.
  2381. **
  2382. ** ^These routines return 0 if the statement is incomplete. ^If a
  2383. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2384. **
  2385. ** ^These routines do not parse the SQL statements thus
  2386. ** will not detect syntactically incorrect SQL.
  2387. **
  2388. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2389. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2390. ** automatically by sqlite3_complete16(). If that initialization fails,
  2391. ** then the return value from sqlite3_complete16() will be non-zero
  2392. ** regardless of whether or not the input SQL is complete.)^
  2393. **
  2394. ** The input to [sqlite3_complete()] must be a zero-terminated
  2395. ** UTF-8 string.
  2396. **
  2397. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2398. ** UTF-16 string in native byte order.
  2399. */
  2400. SQLITE_API int sqlite3_complete(const char *sql);
  2401. SQLITE_API int sqlite3_complete16(const void *sql);
  2402. /*
  2403. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2404. **
  2405. ** ^This routine sets a callback function that might be invoked whenever
  2406. ** an attempt is made to open a database table that another thread
  2407. ** or process has locked.
  2408. **
  2409. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2410. ** is returned immediately upon encountering the lock. ^If the busy callback
  2411. ** is not NULL, then the callback might be invoked with two arguments.
  2412. **
  2413. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2414. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2415. ** the busy handler callback is the number of times that the busy handler has
  2416. ** been invoked for this locking event. ^If the
  2417. ** busy callback returns 0, then no additional attempts are made to
  2418. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2419. ** ^If the callback returns non-zero, then another attempt
  2420. ** is made to open the database for reading and the cycle repeats.
  2421. **
  2422. ** The presence of a busy handler does not guarantee that it will be invoked
  2423. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2424. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2425. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2426. ** Consider a scenario where one process is holding a read lock that
  2427. ** it is trying to promote to a reserved lock and
  2428. ** a second process is holding a reserved lock that it is trying
  2429. ** to promote to an exclusive lock. The first process cannot proceed
  2430. ** because it is blocked by the second and the second process cannot
  2431. ** proceed because it is blocked by the first. If both processes
  2432. ** invoke the busy handlers, neither will make any progress. Therefore,
  2433. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2434. ** will induce the first process to release its read lock and allow
  2435. ** the second process to proceed.
  2436. **
  2437. ** ^The default busy callback is NULL.
  2438. **
  2439. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2440. ** when SQLite is in the middle of a large transaction where all the
  2441. ** changes will not fit into the in-memory cache. SQLite will
  2442. ** already hold a RESERVED lock on the database file, but it needs
  2443. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2444. ** pages into the database file without harm to concurrent
  2445. ** readers. ^If it is unable to promote the lock, then the in-memory
  2446. ** cache will be left in an inconsistent state and so the error
  2447. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2448. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2449. ** forces an automatic rollback of the changes. See the
  2450. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2451. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2452. ** this is important.
  2453. **
  2454. ** ^(There can only be a single busy handler defined for each
  2455. ** [database connection]. Setting a new busy handler clears any
  2456. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2457. ** will also set or clear the busy handler.
  2458. **
  2459. ** The busy callback should not take any actions which modify the
  2460. ** database connection that invoked the busy handler. Any such actions
  2461. ** result in undefined behavior.
  2462. **
  2463. ** A busy handler must not close the database connection
  2464. ** or [prepared statement] that invoked the busy handler.
  2465. */
  2466. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2467. /*
  2468. ** CAPI3REF: Set A Busy Timeout
  2469. **
  2470. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2471. ** for a specified amount of time when a table is locked. ^The handler
  2472. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2473. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2474. ** the handler returns 0 which causes [sqlite3_step()] to return
  2475. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2476. **
  2477. ** ^Calling this routine with an argument less than or equal to zero
  2478. ** turns off all busy handlers.
  2479. **
  2480. ** ^(There can only be a single busy handler for a particular
  2481. ** [database connection] any any given moment. If another busy handler
  2482. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2483. ** this routine, that other busy handler is cleared.)^
  2484. */
  2485. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2486. /*
  2487. ** CAPI3REF: Convenience Routines For Running Queries
  2488. **
  2489. ** This is a legacy interface that is preserved for backwards compatibility.
  2490. ** Use of this interface is not recommended.
  2491. **
  2492. ** Definition: A <b>result table</b> is memory data structure created by the
  2493. ** [sqlite3_get_table()] interface. A result table records the
  2494. ** complete query results from one or more queries.
  2495. **
  2496. ** The table conceptually has a number of rows and columns. But
  2497. ** these numbers are not part of the result table itself. These
  2498. ** numbers are obtained separately. Let N be the number of rows
  2499. ** and M be the number of columns.
  2500. **
  2501. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2502. ** There are (N+1)*M elements in the array. The first M pointers point
  2503. ** to zero-terminated strings that contain the names of the columns.
  2504. ** The remaining entries all point to query results. NULL values result
  2505. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2506. ** string representation as returned by [sqlite3_column_text()].
  2507. **
  2508. ** A result table might consist of one or more memory allocations.
  2509. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2510. ** A result table should be deallocated using [sqlite3_free_table()].
  2511. **
  2512. ** ^(As an example of the result table format, suppose a query result
  2513. ** is as follows:
  2514. **
  2515. ** <blockquote><pre>
  2516. ** Name | Age
  2517. ** -----------------------
  2518. ** Alice | 43
  2519. ** Bob | 28
  2520. ** Cindy | 21
  2521. ** </pre></blockquote>
  2522. **
  2523. ** There are two column (M==2) and three rows (N==3). Thus the
  2524. ** result table has 8 entries. Suppose the result table is stored
  2525. ** in an array names azResult. Then azResult holds this content:
  2526. **
  2527. ** <blockquote><pre>
  2528. ** azResult&#91;0] = "Name";
  2529. ** azResult&#91;1] = "Age";
  2530. ** azResult&#91;2] = "Alice";
  2531. ** azResult&#91;3] = "43";
  2532. ** azResult&#91;4] = "Bob";
  2533. ** azResult&#91;5] = "28";
  2534. ** azResult&#91;6] = "Cindy";
  2535. ** azResult&#91;7] = "21";
  2536. ** </pre></blockquote>)^
  2537. **
  2538. ** ^The sqlite3_get_table() function evaluates one or more
  2539. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2540. ** string of its 2nd parameter and returns a result table to the
  2541. ** pointer given in its 3rd parameter.
  2542. **
  2543. ** After the application has finished with the result from sqlite3_get_table(),
  2544. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2545. ** release the memory that was malloced. Because of the way the
  2546. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2547. ** function must not try to call [sqlite3_free()] directly. Only
  2548. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2549. **
  2550. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2551. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2552. ** to any internal data structures of SQLite. It uses only the public
  2553. ** interface defined here. As a consequence, errors that occur in the
  2554. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2555. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2556. ** [sqlite3_errmsg()].
  2557. */
  2558. SQLITE_API int sqlite3_get_table(
  2559. sqlite3 *db, /* An open database */
  2560. const char *zSql, /* SQL to be evaluated */
  2561. char ***pazResult, /* Results of the query */
  2562. int *pnRow, /* Number of result rows written here */
  2563. int *pnColumn, /* Number of result columns written here */
  2564. char **pzErrmsg /* Error msg written here */
  2565. );
  2566. SQLITE_API void sqlite3_free_table(char **result);
  2567. /*
  2568. ** CAPI3REF: Formatted String Printing Functions
  2569. **
  2570. ** These routines are work-alikes of the "printf()" family of functions
  2571. ** from the standard C library.
  2572. **
  2573. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2574. ** results into memory obtained from [sqlite3_malloc()].
  2575. ** The strings returned by these two routines should be
  2576. ** released by [sqlite3_free()]. ^Both routines return a
  2577. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2578. ** memory to hold the resulting string.
  2579. **
  2580. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2581. ** the standard C library. The result is written into the
  2582. ** buffer supplied as the second parameter whose size is given by
  2583. ** the first parameter. Note that the order of the
  2584. ** first two parameters is reversed from snprintf().)^ This is an
  2585. ** historical accident that cannot be fixed without breaking
  2586. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2587. ** returns a pointer to its buffer instead of the number of
  2588. ** characters actually written into the buffer.)^ We admit that
  2589. ** the number of characters written would be a more useful return
  2590. ** value but we cannot change the implementation of sqlite3_snprintf()
  2591. ** now without breaking compatibility.
  2592. **
  2593. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2594. ** guarantees that the buffer is always zero-terminated. ^The first
  2595. ** parameter "n" is the total size of the buffer, including space for
  2596. ** the zero terminator. So the longest string that can be completely
  2597. ** written will be n-1 characters.
  2598. **
  2599. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2600. **
  2601. ** These routines all implement some additional formatting
  2602. ** options that are useful for constructing SQL statements.
  2603. ** All of the usual printf() formatting options apply. In addition, there
  2604. ** is are "%q", "%Q", and "%z" options.
  2605. **
  2606. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2607. ** string from the argument list. But %q also doubles every '\'' character.
  2608. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2609. ** character it escapes that character and allows it to be inserted into
  2610. ** the string.
  2611. **
  2612. ** For example, assume the string variable zText contains text as follows:
  2613. **
  2614. ** <blockquote><pre>
  2615. ** char *zText = "It's a happy day!";
  2616. ** </pre></blockquote>
  2617. **
  2618. ** One can use this text in an SQL statement as follows:
  2619. **
  2620. ** <blockquote><pre>
  2621. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2622. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2623. ** sqlite3_free(zSQL);
  2624. ** </pre></blockquote>
  2625. **
  2626. ** Because the %q format string is used, the '\'' character in zText
  2627. ** is escaped and the SQL generated is as follows:
  2628. **
  2629. ** <blockquote><pre>
  2630. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2631. ** </pre></blockquote>
  2632. **
  2633. ** This is correct. Had we used %s instead of %q, the generated SQL
  2634. ** would have looked like this:
  2635. **
  2636. ** <blockquote><pre>
  2637. ** INSERT INTO table1 VALUES('It's a happy day!');
  2638. ** </pre></blockquote>
  2639. **
  2640. ** This second example is an SQL syntax error. As a general rule you should
  2641. ** always use %q instead of %s when inserting text into a string literal.
  2642. **
  2643. ** ^(The %Q option works like %q except it also adds single quotes around
  2644. ** the outside of the total string. Additionally, if the parameter in the
  2645. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2646. ** single quotes).)^ So, for example, one could say:
  2647. **
  2648. ** <blockquote><pre>
  2649. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2650. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2651. ** sqlite3_free(zSQL);
  2652. ** </pre></blockquote>
  2653. **
  2654. ** The code above will render a correct SQL statement in the zSQL
  2655. ** variable even if the zText variable is a NULL pointer.
  2656. **
  2657. ** ^(The "%z" formatting option works like "%s" but with the
  2658. ** addition that after the string has been read and copied into
  2659. ** the result, [sqlite3_free()] is called on the input string.)^
  2660. */
  2661. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2662. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2663. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2664. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2665. /*
  2666. ** CAPI3REF: Memory Allocation Subsystem
  2667. **
  2668. ** The SQLite core uses these three routines for all of its own
  2669. ** internal memory allocation needs. "Core" in the previous sentence
  2670. ** does not include operating-system specific VFS implementation. The
  2671. ** Windows VFS uses native malloc() and free() for some operations.
  2672. **
  2673. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2674. ** of memory at least N bytes in length, where N is the parameter.
  2675. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2676. ** memory, it returns a NULL pointer. ^If the parameter N to
  2677. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2678. ** a NULL pointer.
  2679. **
  2680. ** ^Calling sqlite3_free() with a pointer previously returned
  2681. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2682. ** that it might be reused. ^The sqlite3_free() routine is
  2683. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2684. ** to sqlite3_free() is harmless. After being freed, memory
  2685. ** should neither be read nor written. Even reading previously freed
  2686. ** memory might result in a segmentation fault or other severe error.
  2687. ** Memory corruption, a segmentation fault, or other severe error
  2688. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2689. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2690. **
  2691. ** ^(The sqlite3_realloc() interface attempts to resize a
  2692. ** prior memory allocation to be at least N bytes, where N is the
  2693. ** second parameter. The memory allocation to be resized is the first
  2694. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2695. ** is a NULL pointer then its behavior is identical to calling
  2696. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2697. ** ^If the second parameter to sqlite3_realloc() is zero or
  2698. ** negative then the behavior is exactly the same as calling
  2699. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2700. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2701. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2702. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2703. ** of the prior allocation are copied into the beginning of buffer returned
  2704. ** by sqlite3_realloc() and the prior allocation is freed.
  2705. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2706. ** is not freed.
  2707. **
  2708. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2709. ** is always aligned to at least an 8 byte boundary, or to a
  2710. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2711. ** option is used.
  2712. **
  2713. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2714. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2715. ** implementation of these routines to be omitted. That capability
  2716. ** is no longer provided. Only built-in memory allocators can be used.
  2717. **
  2718. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2719. ** the system malloc() and free() directly when converting
  2720. ** filenames between the UTF-8 encoding used by SQLite
  2721. ** and whatever filename encoding is used by the particular Windows
  2722. ** installation. Memory allocation errors were detected, but
  2723. ** they were reported back as [SQLITE_CANTOPEN] or
  2724. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2725. **
  2726. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2727. ** must be either NULL or else pointers obtained from a prior
  2728. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2729. ** not yet been released.
  2730. **
  2731. ** The application must not read or write any part of
  2732. ** a block of memory after it has been released using
  2733. ** [sqlite3_free()] or [sqlite3_realloc()].
  2734. */
  2735. SQLITE_API void *sqlite3_malloc(int);
  2736. SQLITE_API void *sqlite3_realloc(void*, int);
  2737. SQLITE_API void sqlite3_free(void*);
  2738. /*
  2739. ** CAPI3REF: Memory Allocator Statistics
  2740. **
  2741. ** SQLite provides these two interfaces for reporting on the status
  2742. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2743. ** routines, which form the built-in memory allocation subsystem.
  2744. **
  2745. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2746. ** of memory currently outstanding (malloced but not freed).
  2747. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2748. ** value of [sqlite3_memory_used()] since the high-water mark
  2749. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2750. ** [sqlite3_memory_highwater()] include any overhead
  2751. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2752. ** but not overhead added by the any underlying system library
  2753. ** routines that [sqlite3_malloc()] may call.
  2754. **
  2755. ** ^The memory high-water mark is reset to the current value of
  2756. ** [sqlite3_memory_used()] if and only if the parameter to
  2757. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2758. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2759. ** prior to the reset.
  2760. */
  2761. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2762. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2763. /*
  2764. ** CAPI3REF: Pseudo-Random Number Generator
  2765. **
  2766. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2767. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2768. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2769. ** the build-in random() and randomblob() SQL functions. This interface allows
  2770. ** applications to access the same PRNG for other purposes.
  2771. **
  2772. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2773. **
  2774. ** ^The first time this routine is invoked (either internally or by
  2775. ** the application) the PRNG is seeded using randomness obtained
  2776. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2777. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2778. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2779. ** method.
  2780. */
  2781. SQLITE_API void sqlite3_randomness(int N, void *P);
  2782. /*
  2783. ** CAPI3REF: Compile-Time Authorization Callbacks
  2784. **
  2785. ** ^This routine registers an authorizer callback with a particular
  2786. ** [database connection], supplied in the first argument.
  2787. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2788. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2789. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2790. ** points during the compilation process, as logic is being created
  2791. ** to perform various actions, the authorizer callback is invoked to
  2792. ** see if those actions are allowed. ^The authorizer callback should
  2793. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2794. ** specific action but allow the SQL statement to continue to be
  2795. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2796. ** rejected with an error. ^If the authorizer callback returns
  2797. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2798. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2799. ** the authorizer will fail with an error message.
  2800. **
  2801. ** When the callback returns [SQLITE_OK], that means the operation
  2802. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2803. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2804. ** authorizer will fail with an error message explaining that
  2805. ** access is denied.
  2806. **
  2807. ** ^The first parameter to the authorizer callback is a copy of the third
  2808. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2809. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2810. ** the particular action to be authorized. ^The third through sixth parameters
  2811. ** to the callback are zero-terminated strings that contain additional
  2812. ** details about the action to be authorized.
  2813. **
  2814. ** ^If the action code is [SQLITE_READ]
  2815. ** and the callback returns [SQLITE_IGNORE] then the
  2816. ** [prepared statement] statement is constructed to substitute
  2817. ** a NULL value in place of the table column that would have
  2818. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2819. ** return can be used to deny an untrusted user access to individual
  2820. ** columns of a table.
  2821. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2822. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2823. ** [truncate optimization] is disabled and all rows are deleted individually.
  2824. **
  2825. ** An authorizer is used when [sqlite3_prepare | preparing]
  2826. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2827. ** do not try to access data they are not allowed to see, or that they do not
  2828. ** try to execute malicious statements that damage the database. For
  2829. ** example, an application may allow a user to enter arbitrary
  2830. ** SQL queries for evaluation by a database. But the application does
  2831. ** not want the user to be able to make arbitrary changes to the
  2832. ** database. An authorizer could then be put in place while the
  2833. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2834. ** disallows everything except [SELECT] statements.
  2835. **
  2836. ** Applications that need to process SQL from untrusted sources
  2837. ** might also consider lowering resource limits using [sqlite3_limit()]
  2838. ** and limiting database size using the [max_page_count] [PRAGMA]
  2839. ** in addition to using an authorizer.
  2840. **
  2841. ** ^(Only a single authorizer can be in place on a database connection
  2842. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2843. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2844. ** The authorizer is disabled by default.
  2845. **
  2846. ** The authorizer callback must not do anything that will modify
  2847. ** the database connection that invoked the authorizer callback.
  2848. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2849. ** database connections for the meaning of "modify" in this paragraph.
  2850. **
  2851. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2852. ** statement might be re-prepared during [sqlite3_step()] due to a
  2853. ** schema change. Hence, the application should ensure that the
  2854. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2855. **
  2856. ** ^Note that the authorizer callback is invoked only during
  2857. ** [sqlite3_prepare()] or its variants. Authorization is not
  2858. ** performed during statement evaluation in [sqlite3_step()], unless
  2859. ** as stated in the previous paragraph, sqlite3_step() invokes
  2860. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2861. */
  2862. SQLITE_API int sqlite3_set_authorizer(
  2863. sqlite3*,
  2864. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2865. void *pUserData
  2866. );
  2867. /*
  2868. ** CAPI3REF: Authorizer Return Codes
  2869. **
  2870. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2871. ** return either [SQLITE_OK] or one of these two constants in order
  2872. ** to signal SQLite whether or not the action is permitted. See the
  2873. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2874. ** information.
  2875. **
  2876. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2877. ** from the [sqlite3_vtab_on_conflict()] interface.
  2878. */
  2879. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2880. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2881. /*
  2882. ** CAPI3REF: Authorizer Action Codes
  2883. **
  2884. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2885. ** that is invoked to authorize certain SQL statement actions. The
  2886. ** second parameter to the callback is an integer code that specifies
  2887. ** what action is being authorized. These are the integer action codes that
  2888. ** the authorizer callback may be passed.
  2889. **
  2890. ** These action code values signify what kind of operation is to be
  2891. ** authorized. The 3rd and 4th parameters to the authorization
  2892. ** callback function will be parameters or NULL depending on which of these
  2893. ** codes is used as the second parameter. ^(The 5th parameter to the
  2894. ** authorizer callback is the name of the database ("main", "temp",
  2895. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2896. ** is the name of the inner-most trigger or view that is responsible for
  2897. ** the access attempt or NULL if this access attempt is directly from
  2898. ** top-level SQL code.
  2899. */
  2900. /******************************************* 3rd ************ 4th ***********/
  2901. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2902. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2903. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2904. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2905. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2906. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2907. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2908. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2909. #define SQLITE_DELETE 9 /* Table Name NULL */
  2910. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2911. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2912. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2913. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2914. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2915. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2916. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2917. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2918. #define SQLITE_INSERT 18 /* Table Name NULL */
  2919. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2920. #define SQLITE_READ 20 /* Table Name Column Name */
  2921. #define SQLITE_SELECT 21 /* NULL NULL */
  2922. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2923. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2924. #define SQLITE_ATTACH 24 /* Filename NULL */
  2925. #define SQLITE_DETACH 25 /* Database Name NULL */
  2926. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2927. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2928. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2929. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2930. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2931. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2932. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2933. #define SQLITE_COPY 0 /* No longer used */
  2934. /*
  2935. ** CAPI3REF: Tracing And Profiling Functions
  2936. **
  2937. ** These routines register callback functions that can be used for
  2938. ** tracing and profiling the execution of SQL statements.
  2939. **
  2940. ** ^The callback function registered by sqlite3_trace() is invoked at
  2941. ** various times when an SQL statement is being run by [sqlite3_step()].
  2942. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2943. ** SQL statement text as the statement first begins executing.
  2944. ** ^(Additional sqlite3_trace() callbacks might occur
  2945. ** as each triggered subprogram is entered. The callbacks for triggers
  2946. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2947. **
  2948. ** ^The callback function registered by sqlite3_profile() is invoked
  2949. ** as each SQL statement finishes. ^The profile callback contains
  2950. ** the original statement text and an estimate of wall-clock time
  2951. ** of how long that statement took to run. ^The profile callback
  2952. ** time is in units of nanoseconds, however the current implementation
  2953. ** is only capable of millisecond resolution so the six least significant
  2954. ** digits in the time are meaningless. Future versions of SQLite
  2955. ** might provide greater resolution on the profiler callback. The
  2956. ** sqlite3_profile() function is considered experimental and is
  2957. ** subject to change in future versions of SQLite.
  2958. */
  2959. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2960. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2961. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2962. /*
  2963. ** CAPI3REF: Query Progress Callbacks
  2964. **
  2965. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2966. ** function X to be invoked periodically during long running calls to
  2967. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2968. ** database connection D. An example use for this
  2969. ** interface is to keep a GUI updated during a large query.
  2970. **
  2971. ** ^The parameter P is passed through as the only parameter to the
  2972. ** callback function X. ^The parameter N is the number of
  2973. ** [virtual machine instructions] that are evaluated between successive
  2974. ** invocations of the callback X.
  2975. **
  2976. ** ^Only a single progress handler may be defined at one time per
  2977. ** [database connection]; setting a new progress handler cancels the
  2978. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2979. ** ^The progress handler is also disabled by setting N to a value less
  2980. ** than 1.
  2981. **
  2982. ** ^If the progress callback returns non-zero, the operation is
  2983. ** interrupted. This feature can be used to implement a
  2984. ** "Cancel" button on a GUI progress dialog box.
  2985. **
  2986. ** The progress handler callback must not do anything that will modify
  2987. ** the database connection that invoked the progress handler.
  2988. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2989. ** database connections for the meaning of "modify" in this paragraph.
  2990. **
  2991. */
  2992. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2993. /*
  2994. ** CAPI3REF: Opening A New Database Connection
  2995. **
  2996. ** ^These routines open an SQLite database file as specified by the
  2997. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2998. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2999. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  3000. ** returned in *ppDb, even if an error occurs. The only exception is that
  3001. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  3002. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  3003. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  3004. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  3005. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  3006. ** an English language description of the error following a failure of any
  3007. ** of the sqlite3_open() routines.
  3008. **
  3009. ** ^The default encoding for the database will be UTF-8 if
  3010. ** sqlite3_open() or sqlite3_open_v2() is called and
  3011. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  3012. **
  3013. ** Whether or not an error occurs when it is opened, resources
  3014. ** associated with the [database connection] handle should be released by
  3015. ** passing it to [sqlite3_close()] when it is no longer required.
  3016. **
  3017. ** The sqlite3_open_v2() interface works like sqlite3_open()
  3018. ** except that it accepts two additional parameters for additional control
  3019. ** over the new database connection. ^(The flags parameter to
  3020. ** sqlite3_open_v2() can take one of
  3021. ** the following three values, optionally combined with the
  3022. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  3023. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  3024. **
  3025. ** <dl>
  3026. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  3027. ** <dd>The database is opened in read-only mode. If the database does not
  3028. ** already exist, an error is returned.</dd>)^
  3029. **
  3030. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  3031. ** <dd>The database is opened for reading and writing if possible, or reading
  3032. ** only if the file is write protected by the operating system. In either
  3033. ** case the database must already exist, otherwise an error is returned.</dd>)^
  3034. **
  3035. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  3036. ** <dd>The database is opened for reading and writing, and is created if
  3037. ** it does not already exist. This is the behavior that is always used for
  3038. ** sqlite3_open() and sqlite3_open16().</dd>)^
  3039. ** </dl>
  3040. **
  3041. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  3042. ** combinations shown above optionally combined with other
  3043. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  3044. ** then the behavior is undefined.
  3045. **
  3046. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  3047. ** opens in the multi-thread [threading mode] as long as the single-thread
  3048. ** mode has not been set at compile-time or start-time. ^If the
  3049. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  3050. ** in the serialized [threading mode] unless single-thread was
  3051. ** previously selected at compile-time or start-time.
  3052. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  3053. ** eligible to use [shared cache mode], regardless of whether or not shared
  3054. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  3055. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  3056. ** participate in [shared cache mode] even if it is enabled.
  3057. **
  3058. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  3059. ** [sqlite3_vfs] object that defines the operating system interface that
  3060. ** the new database connection should use. ^If the fourth parameter is
  3061. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3062. **
  3063. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  3064. ** is created for the connection. ^This in-memory database will vanish when
  3065. ** the database connection is closed. Future versions of SQLite might
  3066. ** make use of additional special filenames that begin with the ":" character.
  3067. ** It is recommended that when a database filename actually does begin with
  3068. ** a ":" character you should prefix the filename with a pathname such as
  3069. ** "./" to avoid ambiguity.
  3070. **
  3071. ** ^If the filename is an empty string, then a private, temporary
  3072. ** on-disk database will be created. ^This private database will be
  3073. ** automatically deleted as soon as the database connection is closed.
  3074. **
  3075. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  3076. **
  3077. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3078. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3079. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3080. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3081. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3082. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3083. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3084. ** by default, but future releases of SQLite might enable URI filename
  3085. ** interpretation by default. See "[URI filenames]" for additional
  3086. ** information.
  3087. **
  3088. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3089. ** authority, then it must be either an empty string or the string
  3090. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3091. ** error is returned to the caller. ^The fragment component of a URI, if
  3092. ** present, is ignored.
  3093. **
  3094. ** ^SQLite uses the path component of the URI as the name of the disk file
  3095. ** which contains the database. ^If the path begins with a '/' character,
  3096. ** then it is interpreted as an absolute path. ^If the path does not begin
  3097. ** with a '/' (meaning that the authority section is omitted from the URI)
  3098. ** then the path is interpreted as a relative path.
  3099. ** ^On windows, the first component of an absolute path
  3100. ** is a drive specification (e.g. "C:").
  3101. **
  3102. ** [[core URI query parameters]]
  3103. ** The query component of a URI may contain parameters that are interpreted
  3104. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3105. ** SQLite interprets the following three query parameters:
  3106. **
  3107. ** <ul>
  3108. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3109. ** a VFS object that provides the operating system interface that should
  3110. ** be used to access the database file on disk. ^If this option is set to
  3111. ** an empty string the default VFS object is used. ^Specifying an unknown
  3112. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3113. ** present, then the VFS specified by the option takes precedence over
  3114. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3115. **
  3116. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3117. ** "rwc", or "memory". Attempting to set it to any other value is
  3118. ** an error)^.
  3119. ** ^If "ro" is specified, then the database is opened for read-only
  3120. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3121. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3122. ** "rw", then the database is opened for read-write (but not create)
  3123. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3124. ** been set. ^Value "rwc" is equivalent to setting both
  3125. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3126. ** set to "memory" then a pure [in-memory database] that never reads
  3127. ** or writes from disk is used. ^It is an error to specify a value for
  3128. ** the mode parameter that is less restrictive than that specified by
  3129. ** the flags passed in the third parameter to sqlite3_open_v2().
  3130. **
  3131. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3132. ** "private". ^Setting it to "shared" is equivalent to setting the
  3133. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3134. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3135. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3136. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3137. ** a URI filename, its value overrides any behaviour requested by setting
  3138. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3139. ** </ul>
  3140. **
  3141. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3142. ** error. Future versions of SQLite might understand additional query
  3143. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3144. ** additional information.
  3145. **
  3146. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3147. **
  3148. ** <table border="1" align=center cellpadding=5>
  3149. ** <tr><th> URI filenames <th> Results
  3150. ** <tr><td> file:data.db <td>
  3151. ** Open the file "data.db" in the current directory.
  3152. ** <tr><td> file:/home/fred/data.db<br>
  3153. ** file:///home/fred/data.db <br>
  3154. ** file://localhost/home/fred/data.db <br> <td>
  3155. ** Open the database file "/home/fred/data.db".
  3156. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3157. ** An error. "darkstar" is not a recognized authority.
  3158. ** <tr><td style="white-space:nowrap">
  3159. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3160. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3161. ** C:. Note that the %20 escaping in this example is not strictly
  3162. ** necessary - space characters can be used literally
  3163. ** in URI filenames.
  3164. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3165. ** Open file "data.db" in the current directory for read-only access.
  3166. ** Regardless of whether or not shared-cache mode is enabled by
  3167. ** default, use a private cache.
  3168. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  3169. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  3170. ** <tr><td> file:data.db?mode=readonly <td>
  3171. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3172. ** </table>
  3173. **
  3174. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3175. ** query components of a URI. A hexadecimal escape sequence consists of a
  3176. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3177. ** specifying an octet value. ^Before the path or query components of a
  3178. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3179. ** hexadecimal escape sequences replaced by a single byte containing the
  3180. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3181. ** the results are undefined.
  3182. **
  3183. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3184. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3185. ** codepage is currently defined. Filenames containing international
  3186. ** characters must be converted to UTF-8 prior to passing them into
  3187. ** sqlite3_open() or sqlite3_open_v2().
  3188. **
  3189. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3190. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3191. ** features that require the use of temporary files may fail.
  3192. **
  3193. ** See also: [sqlite3_temp_directory]
  3194. */
  3195. SQLITE_API int sqlite3_open(
  3196. const char *filename, /* Database filename (UTF-8) */
  3197. sqlite3 **ppDb /* OUT: SQLite db handle */
  3198. );
  3199. SQLITE_API int sqlite3_open16(
  3200. const void *filename, /* Database filename (UTF-16) */
  3201. sqlite3 **ppDb /* OUT: SQLite db handle */
  3202. );
  3203. SQLITE_API int sqlite3_open_v2(
  3204. const char *filename, /* Database filename (UTF-8) */
  3205. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3206. int flags, /* Flags */
  3207. const char *zVfs /* Name of VFS module to use */
  3208. );
  3209. /*
  3210. ** CAPI3REF: Obtain Values For URI Parameters
  3211. **
  3212. ** These are utility routines, useful to VFS implementations, that check
  3213. ** to see if a database file was a URI that contained a specific query
  3214. ** parameter, and if so obtains the value of that query parameter.
  3215. **
  3216. ** If F is the database filename pointer passed into the xOpen() method of
  3217. ** a VFS implementation when the flags parameter to xOpen() has one or
  3218. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3219. ** P is the name of the query parameter, then
  3220. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3221. ** parameter if it exists or a NULL pointer if P does not appear as a
  3222. ** query parameter on F. If P is a query parameter of F
  3223. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3224. ** a pointer to an empty string.
  3225. **
  3226. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3227. ** parameter and returns true (1) or false (0) according to the value
  3228. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3229. ** value of query parameter P is one of "yes", "true", or "on" in any
  3230. ** case or if the value begins with a non-zero number. The
  3231. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3232. ** query parameter P is one of "no", "false", or "off" in any case or
  3233. ** if the value begins with a numeric zero. If P is not a query
  3234. ** parameter on F or if the value of P is does not match any of the
  3235. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3236. **
  3237. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3238. ** 64-bit signed integer and returns that integer, or D if P does not
  3239. ** exist. If the value of P is something other than an integer, then
  3240. ** zero is returned.
  3241. **
  3242. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3243. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3244. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3245. ** VFS method, then the behavior of this routine is undefined and probably
  3246. ** undesirable.
  3247. */
  3248. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3249. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3250. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3251. /*
  3252. ** CAPI3REF: Error Codes And Messages
  3253. **
  3254. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  3255. ** [extended result code] for the most recent failed sqlite3_* API call
  3256. ** associated with a [database connection]. If a prior API call failed
  3257. ** but the most recent API call succeeded, the return value from
  3258. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  3259. ** interface is the same except that it always returns the
  3260. ** [extended result code] even when extended result codes are
  3261. ** disabled.
  3262. **
  3263. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3264. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3265. ** ^(Memory to hold the error message string is managed internally.
  3266. ** The application does not need to worry about freeing the result.
  3267. ** However, the error string might be overwritten or deallocated by
  3268. ** subsequent calls to other SQLite interface functions.)^
  3269. **
  3270. ** ^The sqlite3_errstr() interface returns the English-language text
  3271. ** that describes the [result code], as UTF-8.
  3272. ** ^(Memory to hold the error message string is managed internally
  3273. ** and must not be freed by the application)^.
  3274. **
  3275. ** When the serialized [threading mode] is in use, it might be the
  3276. ** case that a second error occurs on a separate thread in between
  3277. ** the time of the first error and the call to these interfaces.
  3278. ** When that happens, the second error will be reported since these
  3279. ** interfaces always report the most recent result. To avoid
  3280. ** this, each thread can obtain exclusive use of the [database connection] D
  3281. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3282. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3283. ** all calls to the interfaces listed here are completed.
  3284. **
  3285. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3286. ** was invoked incorrectly by the application. In that case, the
  3287. ** error code and message may or may not be set.
  3288. */
  3289. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3290. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3291. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3292. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3293. SQLITE_API const char *sqlite3_errstr(int);
  3294. /*
  3295. ** CAPI3REF: SQL Statement Object
  3296. ** KEYWORDS: {prepared statement} {prepared statements}
  3297. **
  3298. ** An instance of this object represents a single SQL statement.
  3299. ** This object is variously known as a "prepared statement" or a
  3300. ** "compiled SQL statement" or simply as a "statement".
  3301. **
  3302. ** The life of a statement object goes something like this:
  3303. **
  3304. ** <ol>
  3305. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3306. ** function.
  3307. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3308. ** interfaces.
  3309. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3310. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3311. ** to step 2. Do this zero or more times.
  3312. ** <li> Destroy the object using [sqlite3_finalize()].
  3313. ** </ol>
  3314. **
  3315. ** Refer to documentation on individual methods above for additional
  3316. ** information.
  3317. */
  3318. typedef struct sqlite3_stmt sqlite3_stmt;
  3319. /*
  3320. ** CAPI3REF: Run-time Limits
  3321. **
  3322. ** ^(This interface allows the size of various constructs to be limited
  3323. ** on a connection by connection basis. The first parameter is the
  3324. ** [database connection] whose limit is to be set or queried. The
  3325. ** second parameter is one of the [limit categories] that define a
  3326. ** class of constructs to be size limited. The third parameter is the
  3327. ** new limit for that construct.)^
  3328. **
  3329. ** ^If the new limit is a negative number, the limit is unchanged.
  3330. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3331. ** [limits | hard upper bound]
  3332. ** set at compile-time by a C preprocessor macro called
  3333. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3334. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3335. ** ^Attempts to increase a limit above its hard upper bound are
  3336. ** silently truncated to the hard upper bound.
  3337. **
  3338. ** ^Regardless of whether or not the limit was changed, the
  3339. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3340. ** ^Hence, to find the current value of a limit without changing it,
  3341. ** simply invoke this interface with the third parameter set to -1.
  3342. **
  3343. ** Run-time limits are intended for use in applications that manage
  3344. ** both their own internal database and also databases that are controlled
  3345. ** by untrusted external sources. An example application might be a
  3346. ** web browser that has its own databases for storing history and
  3347. ** separate databases controlled by JavaScript applications downloaded
  3348. ** off the Internet. The internal databases can be given the
  3349. ** large, default limits. Databases managed by external sources can
  3350. ** be given much smaller limits designed to prevent a denial of service
  3351. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3352. ** interface to further control untrusted SQL. The size of the database
  3353. ** created by an untrusted script can be contained using the
  3354. ** [max_page_count] [PRAGMA].
  3355. **
  3356. ** New run-time limit categories may be added in future releases.
  3357. */
  3358. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3359. /*
  3360. ** CAPI3REF: Run-Time Limit Categories
  3361. ** KEYWORDS: {limit category} {*limit categories}
  3362. **
  3363. ** These constants define various performance limits
  3364. ** that can be lowered at run-time using [sqlite3_limit()].
  3365. ** The synopsis of the meanings of the various limits is shown below.
  3366. ** Additional information is available at [limits | Limits in SQLite].
  3367. **
  3368. ** <dl>
  3369. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3370. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3371. **
  3372. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3373. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3374. **
  3375. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3376. ** <dd>The maximum number of columns in a table definition or in the
  3377. ** result set of a [SELECT] or the maximum number of columns in an index
  3378. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3379. **
  3380. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3381. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3382. **
  3383. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3384. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3385. **
  3386. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3387. ** <dd>The maximum number of instructions in a virtual machine program
  3388. ** used to implement an SQL statement. This limit is not currently
  3389. ** enforced, though that might be added in some future release of
  3390. ** SQLite.</dd>)^
  3391. **
  3392. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3393. ** <dd>The maximum number of arguments on a function.</dd>)^
  3394. **
  3395. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3396. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3397. **
  3398. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3399. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3400. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3401. ** [GLOB] operators.</dd>)^
  3402. **
  3403. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3404. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3405. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3406. **
  3407. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3408. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3409. ** </dl>
  3410. */
  3411. #define SQLITE_LIMIT_LENGTH 0
  3412. #define SQLITE_LIMIT_SQL_LENGTH 1
  3413. #define SQLITE_LIMIT_COLUMN 2
  3414. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3415. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3416. #define SQLITE_LIMIT_VDBE_OP 5
  3417. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3418. #define SQLITE_LIMIT_ATTACHED 7
  3419. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3420. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3421. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3422. /*
  3423. ** CAPI3REF: Compiling An SQL Statement
  3424. ** KEYWORDS: {SQL statement compiler}
  3425. **
  3426. ** To execute an SQL query, it must first be compiled into a byte-code
  3427. ** program using one of these routines.
  3428. **
  3429. ** The first argument, "db", is a [database connection] obtained from a
  3430. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3431. ** [sqlite3_open16()]. The database connection must not have been closed.
  3432. **
  3433. ** The second argument, "zSql", is the statement to be compiled, encoded
  3434. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3435. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3436. ** use UTF-16.
  3437. **
  3438. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3439. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3440. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3441. ** zSql string ends at either the first '\000' or '\u0000' character or
  3442. ** the nByte-th byte, whichever comes first. If the caller knows
  3443. ** that the supplied string is nul-terminated, then there is a small
  3444. ** performance advantage to be gained by passing an nByte parameter that
  3445. ** is equal to the number of bytes in the input string <i>including</i>
  3446. ** the nul-terminator bytes as this saves SQLite from having to
  3447. ** make a copy of the input string.
  3448. **
  3449. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3450. ** past the end of the first SQL statement in zSql. These routines only
  3451. ** compile the first statement in zSql, so *pzTail is left pointing to
  3452. ** what remains uncompiled.
  3453. **
  3454. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3455. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3456. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3457. ** string or a comment) then *ppStmt is set to NULL.
  3458. ** The calling procedure is responsible for deleting the compiled
  3459. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3460. ** ppStmt may not be NULL.
  3461. **
  3462. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3463. ** otherwise an [error code] is returned.
  3464. **
  3465. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3466. ** recommended for all new programs. The two older interfaces are retained
  3467. ** for backwards compatibility, but their use is discouraged.
  3468. ** ^In the "v2" interfaces, the prepared statement
  3469. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3470. ** original SQL text. This causes the [sqlite3_step()] interface to
  3471. ** behave differently in three ways:
  3472. **
  3473. ** <ol>
  3474. ** <li>
  3475. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3476. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3477. ** statement and try to run it again.
  3478. ** </li>
  3479. **
  3480. ** <li>
  3481. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3482. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3483. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3484. ** and the application would have to make a second call to [sqlite3_reset()]
  3485. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3486. ** interfaces, the underlying reason for the error is returned immediately.
  3487. ** </li>
  3488. **
  3489. ** <li>
  3490. ** ^If the specific value bound to [parameter | host parameter] in the
  3491. ** WHERE clause might influence the choice of query plan for a statement,
  3492. ** then the statement will be automatically recompiled, as if there had been
  3493. ** a schema change, on the first [sqlite3_step()] call following any change
  3494. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3495. ** ^The specific value of WHERE-clause [parameter] might influence the
  3496. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3497. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3498. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3499. ** the
  3500. ** </li>
  3501. ** </ol>
  3502. */
  3503. SQLITE_API int sqlite3_prepare(
  3504. sqlite3 *db, /* Database handle */
  3505. const char *zSql, /* SQL statement, UTF-8 encoded */
  3506. int nByte, /* Maximum length of zSql in bytes. */
  3507. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3508. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3509. );
  3510. SQLITE_API int sqlite3_prepare_v2(
  3511. sqlite3 *db, /* Database handle */
  3512. const char *zSql, /* SQL statement, UTF-8 encoded */
  3513. int nByte, /* Maximum length of zSql in bytes. */
  3514. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3515. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3516. );
  3517. SQLITE_API int sqlite3_prepare16(
  3518. sqlite3 *db, /* Database handle */
  3519. const void *zSql, /* SQL statement, UTF-16 encoded */
  3520. int nByte, /* Maximum length of zSql in bytes. */
  3521. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3522. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3523. );
  3524. SQLITE_API int sqlite3_prepare16_v2(
  3525. sqlite3 *db, /* Database handle */
  3526. const void *zSql, /* SQL statement, UTF-16 encoded */
  3527. int nByte, /* Maximum length of zSql in bytes. */
  3528. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3529. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3530. );
  3531. /*
  3532. ** CAPI3REF: Retrieving Statement SQL
  3533. **
  3534. ** ^This interface can be used to retrieve a saved copy of the original
  3535. ** SQL text used to create a [prepared statement] if that statement was
  3536. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3537. */
  3538. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3539. /*
  3540. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3541. **
  3542. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3543. ** and only if the [prepared statement] X makes no direct changes to
  3544. ** the content of the database file.
  3545. **
  3546. ** Note that [application-defined SQL functions] or
  3547. ** [virtual tables] might change the database indirectly as a side effect.
  3548. ** ^(For example, if an application defines a function "eval()" that
  3549. ** calls [sqlite3_exec()], then the following SQL statement would
  3550. ** change the database file through side-effects:
  3551. **
  3552. ** <blockquote><pre>
  3553. ** SELECT eval('DELETE FROM t1') FROM t2;
  3554. ** </pre></blockquote>
  3555. **
  3556. ** But because the [SELECT] statement does not change the database file
  3557. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3558. **
  3559. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3560. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3561. ** since the statements themselves do not actually modify the database but
  3562. ** rather they control the timing of when other statements modify the
  3563. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3564. ** sqlite3_stmt_readonly() to return true since, while those statements
  3565. ** change the configuration of a database connection, they do not make
  3566. ** changes to the content of the database files on disk.
  3567. */
  3568. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3569. /*
  3570. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3571. **
  3572. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3573. ** [prepared statement] S has been stepped at least once using
  3574. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3575. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3576. ** interface returns false if S is a NULL pointer. If S is not a
  3577. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3578. ** object, then the behavior is undefined and probably undesirable.
  3579. **
  3580. ** This interface can be used in combination [sqlite3_next_stmt()]
  3581. ** to locate all prepared statements associated with a database
  3582. ** connection that are in need of being reset. This can be used,
  3583. ** for example, in diagnostic routines to search for prepared
  3584. ** statements that are holding a transaction open.
  3585. */
  3586. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3587. /*
  3588. ** CAPI3REF: Dynamically Typed Value Object
  3589. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3590. **
  3591. ** SQLite uses the sqlite3_value object to represent all values
  3592. ** that can be stored in a database table. SQLite uses dynamic typing
  3593. ** for the values it stores. ^Values stored in sqlite3_value objects
  3594. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3595. **
  3596. ** An sqlite3_value object may be either "protected" or "unprotected".
  3597. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3598. ** will accept either a protected or an unprotected sqlite3_value.
  3599. ** Every interface that accepts sqlite3_value arguments specifies
  3600. ** whether or not it requires a protected sqlite3_value.
  3601. **
  3602. ** The terms "protected" and "unprotected" refer to whether or not
  3603. ** a mutex is held. An internal mutex is held for a protected
  3604. ** sqlite3_value object but no mutex is held for an unprotected
  3605. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3606. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3607. ** or if SQLite is run in one of reduced mutex modes
  3608. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3609. ** then there is no distinction between protected and unprotected
  3610. ** sqlite3_value objects and they can be used interchangeably. However,
  3611. ** for maximum code portability it is recommended that applications
  3612. ** still make the distinction between protected and unprotected
  3613. ** sqlite3_value objects even when not strictly required.
  3614. **
  3615. ** ^The sqlite3_value objects that are passed as parameters into the
  3616. ** implementation of [application-defined SQL functions] are protected.
  3617. ** ^The sqlite3_value object returned by
  3618. ** [sqlite3_column_value()] is unprotected.
  3619. ** Unprotected sqlite3_value objects may only be used with
  3620. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3621. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3622. ** interfaces require protected sqlite3_value objects.
  3623. */
  3624. typedef struct Mem sqlite3_value;
  3625. /*
  3626. ** CAPI3REF: SQL Function Context Object
  3627. **
  3628. ** The context in which an SQL function executes is stored in an
  3629. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3630. ** is always first parameter to [application-defined SQL functions].
  3631. ** The application-defined SQL function implementation will pass this
  3632. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3633. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3634. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3635. ** and/or [sqlite3_set_auxdata()].
  3636. */
  3637. typedef struct sqlite3_context sqlite3_context;
  3638. /*
  3639. ** CAPI3REF: Binding Values To Prepared Statements
  3640. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3641. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3642. **
  3643. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3644. ** literals may be replaced by a [parameter] that matches one of following
  3645. ** templates:
  3646. **
  3647. ** <ul>
  3648. ** <li> ?
  3649. ** <li> ?NNN
  3650. ** <li> :VVV
  3651. ** <li> @VVV
  3652. ** <li> $VVV
  3653. ** </ul>
  3654. **
  3655. ** In the templates above, NNN represents an integer literal,
  3656. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3657. ** parameters (also called "host parameter names" or "SQL parameters")
  3658. ** can be set using the sqlite3_bind_*() routines defined here.
  3659. **
  3660. ** ^The first argument to the sqlite3_bind_*() routines is always
  3661. ** a pointer to the [sqlite3_stmt] object returned from
  3662. ** [sqlite3_prepare_v2()] or its variants.
  3663. **
  3664. ** ^The second argument is the index of the SQL parameter to be set.
  3665. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3666. ** SQL parameter is used more than once, second and subsequent
  3667. ** occurrences have the same index as the first occurrence.
  3668. ** ^The index for named parameters can be looked up using the
  3669. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3670. ** for "?NNN" parameters is the value of NNN.
  3671. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3672. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3673. **
  3674. ** ^The third argument is the value to bind to the parameter.
  3675. **
  3676. ** ^(In those routines that have a fourth argument, its value is the
  3677. ** number of bytes in the parameter. To be clear: the value is the
  3678. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3679. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3680. ** is negative, then the length of the string is
  3681. ** the number of bytes up to the first zero terminator.
  3682. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3683. ** the behavior is undefined.
  3684. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3685. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3686. ** where the NUL terminator would occur assuming the string were NUL
  3687. ** terminated. If any NUL characters occur at byte offsets less than
  3688. ** the value of the fourth parameter then the resulting string value will
  3689. ** contain embedded NULs. The result of expressions involving strings
  3690. ** with embedded NULs is undefined.
  3691. **
  3692. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3693. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3694. ** string after SQLite has finished with it. ^The destructor is called
  3695. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3696. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3697. ** ^If the fifth argument is
  3698. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3699. ** information is in static, unmanaged space and does not need to be freed.
  3700. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3701. ** SQLite makes its own private copy of the data immediately, before
  3702. ** the sqlite3_bind_*() routine returns.
  3703. **
  3704. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3705. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3706. ** (just an integer to hold its size) while it is being processed.
  3707. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3708. ** content is later written using
  3709. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3710. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3711. **
  3712. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3713. ** for the [prepared statement] or with a prepared statement for which
  3714. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3715. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3716. ** routine is passed a [prepared statement] that has been finalized, the
  3717. ** result is undefined and probably harmful.
  3718. **
  3719. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3720. ** ^Unbound parameters are interpreted as NULL.
  3721. **
  3722. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3723. ** [error code] if anything goes wrong.
  3724. ** ^[SQLITE_RANGE] is returned if the parameter
  3725. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3726. **
  3727. ** See also: [sqlite3_bind_parameter_count()],
  3728. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3729. */
  3730. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3731. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3732. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3733. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3734. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3735. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3736. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3737. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3738. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3739. /*
  3740. ** CAPI3REF: Number Of SQL Parameters
  3741. **
  3742. ** ^This routine can be used to find the number of [SQL parameters]
  3743. ** in a [prepared statement]. SQL parameters are tokens of the
  3744. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3745. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3746. ** to the parameters at a later time.
  3747. **
  3748. ** ^(This routine actually returns the index of the largest (rightmost)
  3749. ** parameter. For all forms except ?NNN, this will correspond to the
  3750. ** number of unique parameters. If parameters of the ?NNN form are used,
  3751. ** there may be gaps in the list.)^
  3752. **
  3753. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3754. ** [sqlite3_bind_parameter_name()], and
  3755. ** [sqlite3_bind_parameter_index()].
  3756. */
  3757. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3758. /*
  3759. ** CAPI3REF: Name Of A Host Parameter
  3760. **
  3761. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3762. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3763. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3764. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3765. ** respectively.
  3766. ** In other words, the initial ":" or "$" or "@" or "?"
  3767. ** is included as part of the name.)^
  3768. ** ^Parameters of the form "?" without a following integer have no name
  3769. ** and are referred to as "nameless" or "anonymous parameters".
  3770. **
  3771. ** ^The first host parameter has an index of 1, not 0.
  3772. **
  3773. ** ^If the value N is out of range or if the N-th parameter is
  3774. ** nameless, then NULL is returned. ^The returned string is
  3775. ** always in UTF-8 encoding even if the named parameter was
  3776. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3777. ** [sqlite3_prepare16_v2()].
  3778. **
  3779. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3780. ** [sqlite3_bind_parameter_count()], and
  3781. ** [sqlite3_bind_parameter_index()].
  3782. */
  3783. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3784. /*
  3785. ** CAPI3REF: Index Of A Parameter With A Given Name
  3786. **
  3787. ** ^Return the index of an SQL parameter given its name. ^The
  3788. ** index value returned is suitable for use as the second
  3789. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3790. ** is returned if no matching parameter is found. ^The parameter
  3791. ** name must be given in UTF-8 even if the original statement
  3792. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3793. **
  3794. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3795. ** [sqlite3_bind_parameter_count()], and
  3796. ** [sqlite3_bind_parameter_index()].
  3797. */
  3798. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3799. /*
  3800. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3801. **
  3802. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3803. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3804. ** ^Use this routine to reset all host parameters to NULL.
  3805. */
  3806. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3807. /*
  3808. ** CAPI3REF: Number Of Columns In A Result Set
  3809. **
  3810. ** ^Return the number of columns in the result set returned by the
  3811. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3812. ** statement that does not return data (for example an [UPDATE]).
  3813. **
  3814. ** See also: [sqlite3_data_count()]
  3815. */
  3816. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3817. /*
  3818. ** CAPI3REF: Column Names In A Result Set
  3819. **
  3820. ** ^These routines return the name assigned to a particular column
  3821. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3822. ** interface returns a pointer to a zero-terminated UTF-8 string
  3823. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3824. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3825. ** that implements the [SELECT] statement. ^The second parameter is the
  3826. ** column number. ^The leftmost column is number 0.
  3827. **
  3828. ** ^The returned string pointer is valid until either the [prepared statement]
  3829. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3830. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3831. ** or until the next call to
  3832. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3833. **
  3834. ** ^If sqlite3_malloc() fails during the processing of either routine
  3835. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3836. ** NULL pointer is returned.
  3837. **
  3838. ** ^The name of a result column is the value of the "AS" clause for
  3839. ** that column, if there is an AS clause. If there is no AS clause
  3840. ** then the name of the column is unspecified and may change from
  3841. ** one release of SQLite to the next.
  3842. */
  3843. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3844. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3845. /*
  3846. ** CAPI3REF: Source Of Data In A Query Result
  3847. **
  3848. ** ^These routines provide a means to determine the database, table, and
  3849. ** table column that is the origin of a particular result column in
  3850. ** [SELECT] statement.
  3851. ** ^The name of the database or table or column can be returned as
  3852. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3853. ** the database name, the _table_ routines return the table name, and
  3854. ** the origin_ routines return the column name.
  3855. ** ^The returned string is valid until the [prepared statement] is destroyed
  3856. ** using [sqlite3_finalize()] or until the statement is automatically
  3857. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3858. ** or until the same information is requested
  3859. ** again in a different encoding.
  3860. **
  3861. ** ^The names returned are the original un-aliased names of the
  3862. ** database, table, and column.
  3863. **
  3864. ** ^The first argument to these interfaces is a [prepared statement].
  3865. ** ^These functions return information about the Nth result column returned by
  3866. ** the statement, where N is the second function argument.
  3867. ** ^The left-most column is column 0 for these routines.
  3868. **
  3869. ** ^If the Nth column returned by the statement is an expression or
  3870. ** subquery and is not a column value, then all of these functions return
  3871. ** NULL. ^These routine might also return NULL if a memory allocation error
  3872. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3873. ** or column that query result column was extracted from.
  3874. **
  3875. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3876. ** UTF-16 encoded strings and the other functions return UTF-8.
  3877. **
  3878. ** ^These APIs are only available if the library was compiled with the
  3879. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3880. **
  3881. ** If two or more threads call one or more of these routines against the same
  3882. ** prepared statement and column at the same time then the results are
  3883. ** undefined.
  3884. **
  3885. ** If two or more threads call one or more
  3886. ** [sqlite3_column_database_name | column metadata interfaces]
  3887. ** for the same [prepared statement] and result column
  3888. ** at the same time then the results are undefined.
  3889. */
  3890. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3891. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3892. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3893. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3894. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3895. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3896. /*
  3897. ** CAPI3REF: Declared Datatype Of A Query Result
  3898. **
  3899. ** ^(The first parameter is a [prepared statement].
  3900. ** If this statement is a [SELECT] statement and the Nth column of the
  3901. ** returned result set of that [SELECT] is a table column (not an
  3902. ** expression or subquery) then the declared type of the table
  3903. ** column is returned.)^ ^If the Nth column of the result set is an
  3904. ** expression or subquery, then a NULL pointer is returned.
  3905. ** ^The returned string is always UTF-8 encoded.
  3906. **
  3907. ** ^(For example, given the database schema:
  3908. **
  3909. ** CREATE TABLE t1(c1 VARIANT);
  3910. **
  3911. ** and the following statement to be compiled:
  3912. **
  3913. ** SELECT c1 + 1, c1 FROM t1;
  3914. **
  3915. ** this routine would return the string "VARIANT" for the second result
  3916. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3917. **
  3918. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3919. ** is declared to contain a particular type does not mean that the
  3920. ** data stored in that column is of the declared type. SQLite is
  3921. ** strongly typed, but the typing is dynamic not static. ^Type
  3922. ** is associated with individual values, not with the containers
  3923. ** used to hold those values.
  3924. */
  3925. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3926. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3927. /*
  3928. ** CAPI3REF: Evaluate An SQL Statement
  3929. **
  3930. ** After a [prepared statement] has been prepared using either
  3931. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3932. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3933. ** must be called one or more times to evaluate the statement.
  3934. **
  3935. ** The details of the behavior of the sqlite3_step() interface depend
  3936. ** on whether the statement was prepared using the newer "v2" interface
  3937. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3938. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3939. ** new "v2" interface is recommended for new applications but the legacy
  3940. ** interface will continue to be supported.
  3941. **
  3942. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3943. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3944. ** ^With the "v2" interface, any of the other [result codes] or
  3945. ** [extended result codes] might be returned as well.
  3946. **
  3947. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3948. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3949. ** or occurs outside of an explicit transaction, then you can retry the
  3950. ** statement. If the statement is not a [COMMIT] and occurs within an
  3951. ** explicit transaction then you should rollback the transaction before
  3952. ** continuing.
  3953. **
  3954. ** ^[SQLITE_DONE] means that the statement has finished executing
  3955. ** successfully. sqlite3_step() should not be called again on this virtual
  3956. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3957. ** machine back to its initial state.
  3958. **
  3959. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3960. ** is returned each time a new row of data is ready for processing by the
  3961. ** caller. The values may be accessed using the [column access functions].
  3962. ** sqlite3_step() is called again to retrieve the next row of data.
  3963. **
  3964. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3965. ** violation) has occurred. sqlite3_step() should not be called again on
  3966. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3967. ** ^With the legacy interface, a more specific error code (for example,
  3968. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3969. ** can be obtained by calling [sqlite3_reset()] on the
  3970. ** [prepared statement]. ^In the "v2" interface,
  3971. ** the more specific error code is returned directly by sqlite3_step().
  3972. **
  3973. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3974. ** Perhaps it was called on a [prepared statement] that has
  3975. ** already been [sqlite3_finalize | finalized] or on one that had
  3976. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3977. ** be the case that the same database connection is being used by two or
  3978. ** more threads at the same moment in time.
  3979. **
  3980. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3981. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3982. ** other than [SQLITE_ROW] before any subsequent invocation of
  3983. ** sqlite3_step(). Failure to reset the prepared statement using
  3984. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3985. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3986. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3987. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3988. ** break because any application that ever receives an SQLITE_MISUSE error
  3989. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3990. ** can be used to restore the legacy behavior.
  3991. **
  3992. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3993. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3994. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3995. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3996. ** specific [error codes] that better describes the error.
  3997. ** We admit that this is a goofy design. The problem has been fixed
  3998. ** with the "v2" interface. If you prepare all of your SQL statements
  3999. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4000. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4001. ** then the more specific [error codes] are returned directly
  4002. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4003. */
  4004. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  4005. /*
  4006. ** CAPI3REF: Number of columns in a result set
  4007. **
  4008. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4009. ** current row of the result set of [prepared statement] P.
  4010. ** ^If prepared statement P does not have results ready to return
  4011. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4012. ** interfaces) then sqlite3_data_count(P) returns 0.
  4013. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4014. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4015. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4016. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4017. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4018. ** where it always returns zero since each step of that multi-step
  4019. ** pragma returns 0 columns of data.
  4020. **
  4021. ** See also: [sqlite3_column_count()]
  4022. */
  4023. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  4024. /*
  4025. ** CAPI3REF: Fundamental Datatypes
  4026. ** KEYWORDS: SQLITE_TEXT
  4027. **
  4028. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4029. **
  4030. ** <ul>
  4031. ** <li> 64-bit signed integer
  4032. ** <li> 64-bit IEEE floating point number
  4033. ** <li> string
  4034. ** <li> BLOB
  4035. ** <li> NULL
  4036. ** </ul>)^
  4037. **
  4038. ** These constants are codes for each of those types.
  4039. **
  4040. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4041. ** for a completely different meaning. Software that links against both
  4042. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4043. ** SQLITE_TEXT.
  4044. */
  4045. #define SQLITE_INTEGER 1
  4046. #define SQLITE_FLOAT 2
  4047. #define SQLITE_BLOB 4
  4048. #define SQLITE_NULL 5
  4049. #ifdef SQLITE_TEXT
  4050. # undef SQLITE_TEXT
  4051. #else
  4052. # define SQLITE_TEXT 3
  4053. #endif
  4054. #define SQLITE3_TEXT 3
  4055. /*
  4056. ** CAPI3REF: Result Values From A Query
  4057. ** KEYWORDS: {column access functions}
  4058. **
  4059. ** These routines form the "result set" interface.
  4060. **
  4061. ** ^These routines return information about a single column of the current
  4062. ** result row of a query. ^In every case the first argument is a pointer
  4063. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4064. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4065. ** and the second argument is the index of the column for which information
  4066. ** should be returned. ^The leftmost column of the result set has the index 0.
  4067. ** ^The number of columns in the result can be determined using
  4068. ** [sqlite3_column_count()].
  4069. **
  4070. ** If the SQL statement does not currently point to a valid row, or if the
  4071. ** column index is out of range, the result is undefined.
  4072. ** These routines may only be called when the most recent call to
  4073. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4074. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4075. ** If any of these routines are called after [sqlite3_reset()] or
  4076. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4077. ** something other than [SQLITE_ROW], the results are undefined.
  4078. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4079. ** are called from a different thread while any of these routines
  4080. ** are pending, then the results are undefined.
  4081. **
  4082. ** ^The sqlite3_column_type() routine returns the
  4083. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4084. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4085. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4086. ** returned by sqlite3_column_type() is only meaningful if no type
  4087. ** conversions have occurred as described below. After a type conversion,
  4088. ** the value returned by sqlite3_column_type() is undefined. Future
  4089. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4090. ** following a type conversion.
  4091. **
  4092. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4093. ** routine returns the number of bytes in that BLOB or string.
  4094. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4095. ** the string to UTF-8 and then returns the number of bytes.
  4096. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4097. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4098. ** the number of bytes in that string.
  4099. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4100. **
  4101. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4102. ** routine returns the number of bytes in that BLOB or string.
  4103. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4104. ** the string to UTF-16 and then returns the number of bytes.
  4105. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4106. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4107. ** the number of bytes in that string.
  4108. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4109. **
  4110. ** ^The values returned by [sqlite3_column_bytes()] and
  4111. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4112. ** of the string. ^For clarity: the values returned by
  4113. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4114. ** bytes in the string, not the number of characters.
  4115. **
  4116. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4117. ** even empty strings, are always zero-terminated. ^The return
  4118. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4119. **
  4120. ** ^The object returned by [sqlite3_column_value()] is an
  4121. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  4122. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  4123. ** If the [unprotected sqlite3_value] object returned by
  4124. ** [sqlite3_column_value()] is used in any other way, including calls
  4125. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4126. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  4127. **
  4128. ** These routines attempt to convert the value where appropriate. ^For
  4129. ** example, if the internal representation is FLOAT and a text result
  4130. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4131. ** conversion automatically. ^(The following table details the conversions
  4132. ** that are applied:
  4133. **
  4134. ** <blockquote>
  4135. ** <table border="1">
  4136. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4137. **
  4138. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4139. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4140. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  4141. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  4142. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4143. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4144. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4145. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  4146. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4147. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  4148. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  4149. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  4150. ** <tr><td> TEXT <td> BLOB <td> No change
  4151. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  4152. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  4153. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4154. ** </table>
  4155. ** </blockquote>)^
  4156. **
  4157. ** The table above makes reference to standard C library functions atoi()
  4158. ** and atof(). SQLite does not really use these functions. It has its
  4159. ** own equivalent internal routines. The atoi() and atof() names are
  4160. ** used in the table for brevity and because they are familiar to most
  4161. ** C programmers.
  4162. **
  4163. ** Note that when type conversions occur, pointers returned by prior
  4164. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4165. ** sqlite3_column_text16() may be invalidated.
  4166. ** Type conversions and pointer invalidations might occur
  4167. ** in the following cases:
  4168. **
  4169. ** <ul>
  4170. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4171. ** sqlite3_column_text16() is called. A zero-terminator might
  4172. ** need to be added to the string.</li>
  4173. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4174. ** sqlite3_column_text16() is called. The content must be converted
  4175. ** to UTF-16.</li>
  4176. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4177. ** sqlite3_column_text() is called. The content must be converted
  4178. ** to UTF-8.</li>
  4179. ** </ul>
  4180. **
  4181. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4182. ** not invalidate a prior pointer, though of course the content of the buffer
  4183. ** that the prior pointer references will have been modified. Other kinds
  4184. ** of conversion are done in place when it is possible, but sometimes they
  4185. ** are not possible and in those cases prior pointers are invalidated.
  4186. **
  4187. ** The safest and easiest to remember policy is to invoke these routines
  4188. ** in one of the following ways:
  4189. **
  4190. ** <ul>
  4191. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4192. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4193. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4194. ** </ul>
  4195. **
  4196. ** In other words, you should call sqlite3_column_text(),
  4197. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4198. ** into the desired format, then invoke sqlite3_column_bytes() or
  4199. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4200. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4201. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4202. ** with calls to sqlite3_column_bytes().
  4203. **
  4204. ** ^The pointers returned are valid until a type conversion occurs as
  4205. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4206. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4207. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  4208. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4209. ** [sqlite3_free()].
  4210. **
  4211. ** ^(If a memory allocation error occurs during the evaluation of any
  4212. ** of these routines, a default value is returned. The default value
  4213. ** is either the integer 0, the floating point number 0.0, or a NULL
  4214. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4215. ** [SQLITE_NOMEM].)^
  4216. */
  4217. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4218. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4219. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4220. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4221. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4222. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4223. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4224. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4225. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4226. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4227. /*
  4228. ** CAPI3REF: Destroy A Prepared Statement Object
  4229. **
  4230. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4231. ** ^If the most recent evaluation of the statement encountered no errors
  4232. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4233. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4234. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4235. ** [extended error code].
  4236. **
  4237. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4238. ** the life cycle of [prepared statement] S:
  4239. ** before statement S is ever evaluated, after
  4240. ** one or more calls to [sqlite3_reset()], or after any call
  4241. ** to [sqlite3_step()] regardless of whether or not the statement has
  4242. ** completed execution.
  4243. **
  4244. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4245. **
  4246. ** The application must finalize every [prepared statement] in order to avoid
  4247. ** resource leaks. It is a grievous error for the application to try to use
  4248. ** a prepared statement after it has been finalized. Any use of a prepared
  4249. ** statement after it has been finalized can result in undefined and
  4250. ** undesirable behavior such as segfaults and heap corruption.
  4251. */
  4252. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4253. /*
  4254. ** CAPI3REF: Reset A Prepared Statement Object
  4255. **
  4256. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4257. ** object back to its initial state, ready to be re-executed.
  4258. ** ^Any SQL statement variables that had values bound to them using
  4259. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4260. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4261. **
  4262. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4263. ** back to the beginning of its program.
  4264. **
  4265. ** ^If the most recent call to [sqlite3_step(S)] for the
  4266. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4267. ** or if [sqlite3_step(S)] has never before been called on S,
  4268. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4269. **
  4270. ** ^If the most recent call to [sqlite3_step(S)] for the
  4271. ** [prepared statement] S indicated an error, then
  4272. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4273. **
  4274. ** ^The [sqlite3_reset(S)] interface does not change the values
  4275. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4276. */
  4277. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4278. /*
  4279. ** CAPI3REF: Create Or Redefine SQL Functions
  4280. ** KEYWORDS: {function creation routines}
  4281. ** KEYWORDS: {application-defined SQL function}
  4282. ** KEYWORDS: {application-defined SQL functions}
  4283. **
  4284. ** ^These functions (collectively known as "function creation routines")
  4285. ** are used to add SQL functions or aggregates or to redefine the behavior
  4286. ** of existing SQL functions or aggregates. The only differences between
  4287. ** these routines are the text encoding expected for
  4288. ** the second parameter (the name of the function being created)
  4289. ** and the presence or absence of a destructor callback for
  4290. ** the application data pointer.
  4291. **
  4292. ** ^The first parameter is the [database connection] to which the SQL
  4293. ** function is to be added. ^If an application uses more than one database
  4294. ** connection then application-defined SQL functions must be added
  4295. ** to each database connection separately.
  4296. **
  4297. ** ^The second parameter is the name of the SQL function to be created or
  4298. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4299. ** representation, exclusive of the zero-terminator. ^Note that the name
  4300. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4301. ** ^Any attempt to create a function with a longer name
  4302. ** will result in [SQLITE_MISUSE] being returned.
  4303. **
  4304. ** ^The third parameter (nArg)
  4305. ** is the number of arguments that the SQL function or
  4306. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4307. ** aggregate may take any number of arguments between 0 and the limit
  4308. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4309. ** parameter is less than -1 or greater than 127 then the behavior is
  4310. ** undefined.
  4311. **
  4312. ** ^The fourth parameter, eTextRep, specifies what
  4313. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4314. ** its parameters. Every SQL function implementation must be able to work
  4315. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  4316. ** more efficient with one encoding than another. ^An application may
  4317. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  4318. ** times with the same function but with different values of eTextRep.
  4319. ** ^When multiple implementations of the same function are available, SQLite
  4320. ** will pick the one that involves the least amount of data conversion.
  4321. ** If there is only a single implementation which does not care what text
  4322. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  4323. **
  4324. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4325. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4326. **
  4327. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4328. ** pointers to C-language functions that implement the SQL function or
  4329. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4330. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4331. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4332. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4333. ** SQL function or aggregate, pass NULL pointers for all three function
  4334. ** callbacks.
  4335. **
  4336. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4337. ** then it is destructor for the application data pointer.
  4338. ** The destructor is invoked when the function is deleted, either by being
  4339. ** overloaded or when the database connection closes.)^
  4340. ** ^The destructor is also invoked if the call to
  4341. ** sqlite3_create_function_v2() fails.
  4342. ** ^When the destructor callback of the tenth parameter is invoked, it
  4343. ** is passed a single argument which is a copy of the application data
  4344. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4345. **
  4346. ** ^It is permitted to register multiple implementations of the same
  4347. ** functions with the same name but with either differing numbers of
  4348. ** arguments or differing preferred text encodings. ^SQLite will use
  4349. ** the implementation that most closely matches the way in which the
  4350. ** SQL function is used. ^A function implementation with a non-negative
  4351. ** nArg parameter is a better match than a function implementation with
  4352. ** a negative nArg. ^A function where the preferred text encoding
  4353. ** matches the database encoding is a better
  4354. ** match than a function where the encoding is different.
  4355. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4356. ** is a closer match than a function where the encoding difference is
  4357. ** between UTF8 and UTF16.
  4358. **
  4359. ** ^Built-in functions may be overloaded by new application-defined functions.
  4360. **
  4361. ** ^An application-defined function is permitted to call other
  4362. ** SQLite interfaces. However, such calls must not
  4363. ** close the database connection nor finalize or reset the prepared
  4364. ** statement in which the function is running.
  4365. */
  4366. SQLITE_API int sqlite3_create_function(
  4367. sqlite3 *db,
  4368. const char *zFunctionName,
  4369. int nArg,
  4370. int eTextRep,
  4371. void *pApp,
  4372. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4373. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4374. void (*xFinal)(sqlite3_context*)
  4375. );
  4376. SQLITE_API int sqlite3_create_function16(
  4377. sqlite3 *db,
  4378. const void *zFunctionName,
  4379. int nArg,
  4380. int eTextRep,
  4381. void *pApp,
  4382. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4383. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4384. void (*xFinal)(sqlite3_context*)
  4385. );
  4386. SQLITE_API int sqlite3_create_function_v2(
  4387. sqlite3 *db,
  4388. const char *zFunctionName,
  4389. int nArg,
  4390. int eTextRep,
  4391. void *pApp,
  4392. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4393. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4394. void (*xFinal)(sqlite3_context*),
  4395. void(*xDestroy)(void*)
  4396. );
  4397. /*
  4398. ** CAPI3REF: Text Encodings
  4399. **
  4400. ** These constant define integer codes that represent the various
  4401. ** text encodings supported by SQLite.
  4402. */
  4403. #define SQLITE_UTF8 1
  4404. #define SQLITE_UTF16LE 2
  4405. #define SQLITE_UTF16BE 3
  4406. #define SQLITE_UTF16 4 /* Use native byte order */
  4407. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  4408. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4409. /*
  4410. ** CAPI3REF: Deprecated Functions
  4411. ** DEPRECATED
  4412. **
  4413. ** These functions are [deprecated]. In order to maintain
  4414. ** backwards compatibility with older code, these functions continue
  4415. ** to be supported. However, new applications should avoid
  4416. ** the use of these functions. To help encourage people to avoid
  4417. ** using these functions, we are not going to tell you what they do.
  4418. */
  4419. #ifndef SQLITE_OMIT_DEPRECATED
  4420. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4421. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4422. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4423. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4424. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4425. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
  4426. #endif
  4427. /*
  4428. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4429. **
  4430. ** The C-language implementation of SQL functions and aggregates uses
  4431. ** this set of interface routines to access the parameter values on
  4432. ** the function or aggregate.
  4433. **
  4434. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4435. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4436. ** define callbacks that implement the SQL functions and aggregates.
  4437. ** The 3rd parameter to these callbacks is an array of pointers to
  4438. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4439. ** each parameter to the SQL function. These routines are used to
  4440. ** extract values from the [sqlite3_value] objects.
  4441. **
  4442. ** These routines work only with [protected sqlite3_value] objects.
  4443. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4444. ** object results in undefined behavior.
  4445. **
  4446. ** ^These routines work just like the corresponding [column access functions]
  4447. ** except that these routines take a single [protected sqlite3_value] object
  4448. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4449. **
  4450. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4451. ** in the native byte-order of the host machine. ^The
  4452. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4453. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4454. **
  4455. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4456. ** numeric affinity to the value. This means that an attempt is
  4457. ** made to convert the value to an integer or floating point. If
  4458. ** such a conversion is possible without loss of information (in other
  4459. ** words, if the value is a string that looks like a number)
  4460. ** then the conversion is performed. Otherwise no conversion occurs.
  4461. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4462. **
  4463. ** Please pay particular attention to the fact that the pointer returned
  4464. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4465. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4466. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4467. ** or [sqlite3_value_text16()].
  4468. **
  4469. ** These routines must be called from the same thread as
  4470. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4471. */
  4472. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4473. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4474. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4475. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4476. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4477. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4478. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4479. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4480. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4481. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4482. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4483. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4484. /*
  4485. ** CAPI3REF: Obtain Aggregate Function Context
  4486. **
  4487. ** Implementations of aggregate SQL functions use this
  4488. ** routine to allocate memory for storing their state.
  4489. **
  4490. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4491. ** for a particular aggregate function, SQLite
  4492. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4493. ** to the new memory. ^On second and subsequent calls to
  4494. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4495. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4496. ** called once for each invocation of the xStep callback and then one
  4497. ** last time when the xFinal callback is invoked. ^(When no rows match
  4498. ** an aggregate query, the xStep() callback of the aggregate function
  4499. ** implementation is never called and xFinal() is called exactly once.
  4500. ** In those cases, sqlite3_aggregate_context() might be called for the
  4501. ** first time from within xFinal().)^
  4502. **
  4503. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
  4504. ** less than or equal to zero or if a memory allocate error occurs.
  4505. **
  4506. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4507. ** determined by the N parameter on first successful call. Changing the
  4508. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4509. ** the same aggregate function instance will not resize the memory
  4510. ** allocation.)^
  4511. **
  4512. ** ^SQLite automatically frees the memory allocated by
  4513. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4514. **
  4515. ** The first parameter must be a copy of the
  4516. ** [sqlite3_context | SQL function context] that is the first parameter
  4517. ** to the xStep or xFinal callback routine that implements the aggregate
  4518. ** function.
  4519. **
  4520. ** This routine must be called from the same thread in which
  4521. ** the aggregate SQL function is running.
  4522. */
  4523. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4524. /*
  4525. ** CAPI3REF: User Data For Functions
  4526. **
  4527. ** ^The sqlite3_user_data() interface returns a copy of
  4528. ** the pointer that was the pUserData parameter (the 5th parameter)
  4529. ** of the [sqlite3_create_function()]
  4530. ** and [sqlite3_create_function16()] routines that originally
  4531. ** registered the application defined function.
  4532. **
  4533. ** This routine must be called from the same thread in which
  4534. ** the application-defined function is running.
  4535. */
  4536. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4537. /*
  4538. ** CAPI3REF: Database Connection For Functions
  4539. **
  4540. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4541. ** the pointer to the [database connection] (the 1st parameter)
  4542. ** of the [sqlite3_create_function()]
  4543. ** and [sqlite3_create_function16()] routines that originally
  4544. ** registered the application defined function.
  4545. */
  4546. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4547. /*
  4548. ** CAPI3REF: Function Auxiliary Data
  4549. **
  4550. ** The following two functions may be used by scalar SQL functions to
  4551. ** associate metadata with argument values. If the same value is passed to
  4552. ** multiple invocations of the same SQL function during query execution, under
  4553. ** some circumstances the associated metadata may be preserved. This may
  4554. ** be used, for example, to add a regular-expression matching scalar
  4555. ** function. The compiled version of the regular expression is stored as
  4556. ** metadata associated with the SQL value passed as the regular expression
  4557. ** pattern. The compiled regular expression can be reused on multiple
  4558. ** invocations of the same function so that the original pattern string
  4559. ** does not need to be recompiled on each invocation.
  4560. **
  4561. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4562. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4563. ** value to the application-defined function. ^If no metadata has been ever
  4564. ** been set for the Nth argument of the function, or if the corresponding
  4565. ** function parameter has changed since the meta-data was set,
  4566. ** then sqlite3_get_auxdata() returns a NULL pointer.
  4567. **
  4568. ** ^The sqlite3_set_auxdata() interface saves the metadata
  4569. ** pointed to by its 3rd parameter as the metadata for the N-th
  4570. ** argument of the application-defined function. Subsequent
  4571. ** calls to sqlite3_get_auxdata() might return this data, if it has
  4572. ** not been destroyed.
  4573. ** ^If it is not NULL, SQLite will invoke the destructor
  4574. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  4575. ** the metadata when the corresponding function parameter changes
  4576. ** or when the SQL statement completes, whichever comes first.
  4577. **
  4578. ** SQLite is free to call the destructor and drop metadata on any
  4579. ** parameter of any function at any time. ^The only guarantee is that
  4580. ** the destructor will be called before the metadata is dropped.
  4581. **
  4582. ** ^(In practice, metadata is preserved between function calls for
  4583. ** expressions that are constant at compile time. This includes literal
  4584. ** values and [parameters].)^
  4585. **
  4586. ** These routines must be called from the same thread in which
  4587. ** the SQL function is running.
  4588. */
  4589. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4590. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4591. /*
  4592. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4593. **
  4594. ** These are special values for the destructor that is passed in as the
  4595. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4596. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4597. ** and will never change. It does not need to be destroyed. ^The
  4598. ** SQLITE_TRANSIENT value means that the content will likely change in
  4599. ** the near future and that SQLite should make its own private copy of
  4600. ** the content before returning.
  4601. **
  4602. ** The typedef is necessary to work around problems in certain
  4603. ** C++ compilers. See ticket #2191.
  4604. */
  4605. typedef void (*sqlite3_destructor_type)(void*);
  4606. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4607. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4608. /*
  4609. ** CAPI3REF: Setting The Result Of An SQL Function
  4610. **
  4611. ** These routines are used by the xFunc or xFinal callbacks that
  4612. ** implement SQL functions and aggregates. See
  4613. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4614. ** for additional information.
  4615. **
  4616. ** These functions work very much like the [parameter binding] family of
  4617. ** functions used to bind values to host parameters in prepared statements.
  4618. ** Refer to the [SQL parameter] documentation for additional information.
  4619. **
  4620. ** ^The sqlite3_result_blob() interface sets the result from
  4621. ** an application-defined function to be the BLOB whose content is pointed
  4622. ** to by the second parameter and which is N bytes long where N is the
  4623. ** third parameter.
  4624. **
  4625. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4626. ** the application-defined function to be a BLOB containing all zero
  4627. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4628. **
  4629. ** ^The sqlite3_result_double() interface sets the result from
  4630. ** an application-defined function to be a floating point value specified
  4631. ** by its 2nd argument.
  4632. **
  4633. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4634. ** cause the implemented SQL function to throw an exception.
  4635. ** ^SQLite uses the string pointed to by the
  4636. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4637. ** as the text of an error message. ^SQLite interprets the error
  4638. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4639. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4640. ** byte order. ^If the third parameter to sqlite3_result_error()
  4641. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4642. ** message all text up through the first zero character.
  4643. ** ^If the third parameter to sqlite3_result_error() or
  4644. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4645. ** bytes (not characters) from the 2nd parameter as the error message.
  4646. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4647. ** routines make a private copy of the error message text before
  4648. ** they return. Hence, the calling function can deallocate or
  4649. ** modify the text after they return without harm.
  4650. ** ^The sqlite3_result_error_code() function changes the error code
  4651. ** returned by SQLite as a result of an error in a function. ^By default,
  4652. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4653. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4654. **
  4655. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4656. ** error indicating that a string or BLOB is too long to represent.
  4657. **
  4658. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4659. ** error indicating that a memory allocation failed.
  4660. **
  4661. ** ^The sqlite3_result_int() interface sets the return value
  4662. ** of the application-defined function to be the 32-bit signed integer
  4663. ** value given in the 2nd argument.
  4664. ** ^The sqlite3_result_int64() interface sets the return value
  4665. ** of the application-defined function to be the 64-bit signed integer
  4666. ** value given in the 2nd argument.
  4667. **
  4668. ** ^The sqlite3_result_null() interface sets the return value
  4669. ** of the application-defined function to be NULL.
  4670. **
  4671. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4672. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4673. ** set the return value of the application-defined function to be
  4674. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4675. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4676. ** ^SQLite takes the text result from the application from
  4677. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4678. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4679. ** is negative, then SQLite takes result text from the 2nd parameter
  4680. ** through the first zero character.
  4681. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4682. ** is non-negative, then as many bytes (not characters) of the text
  4683. ** pointed to by the 2nd parameter are taken as the application-defined
  4684. ** function result. If the 3rd parameter is non-negative, then it
  4685. ** must be the byte offset into the string where the NUL terminator would
  4686. ** appear if the string where NUL terminated. If any NUL characters occur
  4687. ** in the string at a byte offset that is less than the value of the 3rd
  4688. ** parameter, then the resulting string will contain embedded NULs and the
  4689. ** result of expressions operating on strings with embedded NULs is undefined.
  4690. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4691. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4692. ** function as the destructor on the text or BLOB result when it has
  4693. ** finished using that result.
  4694. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4695. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4696. ** assumes that the text or BLOB result is in constant space and does not
  4697. ** copy the content of the parameter nor call a destructor on the content
  4698. ** when it has finished using that result.
  4699. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4700. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4701. ** then SQLite makes a copy of the result into space obtained from
  4702. ** from [sqlite3_malloc()] before it returns.
  4703. **
  4704. ** ^The sqlite3_result_value() interface sets the result of
  4705. ** the application-defined function to be a copy the
  4706. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4707. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4708. ** so that the [sqlite3_value] specified in the parameter may change or
  4709. ** be deallocated after sqlite3_result_value() returns without harm.
  4710. ** ^A [protected sqlite3_value] object may always be used where an
  4711. ** [unprotected sqlite3_value] object is required, so either
  4712. ** kind of [sqlite3_value] object can be used with this interface.
  4713. **
  4714. ** If these routines are called from within the different thread
  4715. ** than the one containing the application-defined function that received
  4716. ** the [sqlite3_context] pointer, the results are undefined.
  4717. */
  4718. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4719. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4720. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4721. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4722. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4723. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4724. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4725. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4726. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4727. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4728. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4729. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4730. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4731. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4732. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4733. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4734. /*
  4735. ** CAPI3REF: Define New Collating Sequences
  4736. **
  4737. ** ^These functions add, remove, or modify a [collation] associated
  4738. ** with the [database connection] specified as the first argument.
  4739. **
  4740. ** ^The name of the collation is a UTF-8 string
  4741. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4742. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4743. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4744. ** considered to be the same name.
  4745. **
  4746. ** ^(The third argument (eTextRep) must be one of the constants:
  4747. ** <ul>
  4748. ** <li> [SQLITE_UTF8],
  4749. ** <li> [SQLITE_UTF16LE],
  4750. ** <li> [SQLITE_UTF16BE],
  4751. ** <li> [SQLITE_UTF16], or
  4752. ** <li> [SQLITE_UTF16_ALIGNED].
  4753. ** </ul>)^
  4754. ** ^The eTextRep argument determines the encoding of strings passed
  4755. ** to the collating function callback, xCallback.
  4756. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4757. ** force strings to be UTF16 with native byte order.
  4758. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4759. ** on an even byte address.
  4760. **
  4761. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4762. ** through as the first argument to the collating function callback.
  4763. **
  4764. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4765. ** ^Multiple collating functions can be registered using the same name but
  4766. ** with different eTextRep parameters and SQLite will use whichever
  4767. ** function requires the least amount of data transformation.
  4768. ** ^If the xCallback argument is NULL then the collating function is
  4769. ** deleted. ^When all collating functions having the same name are deleted,
  4770. ** that collation is no longer usable.
  4771. **
  4772. ** ^The collating function callback is invoked with a copy of the pArg
  4773. ** application data pointer and with two strings in the encoding specified
  4774. ** by the eTextRep argument. The collating function must return an
  4775. ** integer that is negative, zero, or positive
  4776. ** if the first string is less than, equal to, or greater than the second,
  4777. ** respectively. A collating function must always return the same answer
  4778. ** given the same inputs. If two or more collating functions are registered
  4779. ** to the same collation name (using different eTextRep values) then all
  4780. ** must give an equivalent answer when invoked with equivalent strings.
  4781. ** The collating function must obey the following properties for all
  4782. ** strings A, B, and C:
  4783. **
  4784. ** <ol>
  4785. ** <li> If A==B then B==A.
  4786. ** <li> If A==B and B==C then A==C.
  4787. ** <li> If A&lt;B THEN B&gt;A.
  4788. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4789. ** </ol>
  4790. **
  4791. ** If a collating function fails any of the above constraints and that
  4792. ** collating function is registered and used, then the behavior of SQLite
  4793. ** is undefined.
  4794. **
  4795. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4796. ** with the addition that the xDestroy callback is invoked on pArg when
  4797. ** the collating function is deleted.
  4798. ** ^Collating functions are deleted when they are overridden by later
  4799. ** calls to the collation creation functions or when the
  4800. ** [database connection] is closed using [sqlite3_close()].
  4801. **
  4802. ** ^The xDestroy callback is <u>not</u> called if the
  4803. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4804. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4805. ** check the return code and dispose of the application data pointer
  4806. ** themselves rather than expecting SQLite to deal with it for them.
  4807. ** This is different from every other SQLite interface. The inconsistency
  4808. ** is unfortunate but cannot be changed without breaking backwards
  4809. ** compatibility.
  4810. **
  4811. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4812. */
  4813. SQLITE_API int sqlite3_create_collation(
  4814. sqlite3*,
  4815. const char *zName,
  4816. int eTextRep,
  4817. void *pArg,
  4818. int(*xCompare)(void*,int,const void*,int,const void*)
  4819. );
  4820. SQLITE_API int sqlite3_create_collation_v2(
  4821. sqlite3*,
  4822. const char *zName,
  4823. int eTextRep,
  4824. void *pArg,
  4825. int(*xCompare)(void*,int,const void*,int,const void*),
  4826. void(*xDestroy)(void*)
  4827. );
  4828. SQLITE_API int sqlite3_create_collation16(
  4829. sqlite3*,
  4830. const void *zName,
  4831. int eTextRep,
  4832. void *pArg,
  4833. int(*xCompare)(void*,int,const void*,int,const void*)
  4834. );
  4835. /*
  4836. ** CAPI3REF: Collation Needed Callbacks
  4837. **
  4838. ** ^To avoid having to register all collation sequences before a database
  4839. ** can be used, a single callback function may be registered with the
  4840. ** [database connection] to be invoked whenever an undefined collation
  4841. ** sequence is required.
  4842. **
  4843. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4844. ** then it is passed the names of undefined collation sequences as strings
  4845. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4846. ** the names are passed as UTF-16 in machine native byte order.
  4847. ** ^A call to either function replaces the existing collation-needed callback.
  4848. **
  4849. ** ^(When the callback is invoked, the first argument passed is a copy
  4850. ** of the second argument to sqlite3_collation_needed() or
  4851. ** sqlite3_collation_needed16(). The second argument is the database
  4852. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4853. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4854. ** sequence function required. The fourth parameter is the name of the
  4855. ** required collation sequence.)^
  4856. **
  4857. ** The callback function should register the desired collation using
  4858. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4859. ** [sqlite3_create_collation_v2()].
  4860. */
  4861. SQLITE_API int sqlite3_collation_needed(
  4862. sqlite3*,
  4863. void*,
  4864. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4865. );
  4866. SQLITE_API int sqlite3_collation_needed16(
  4867. sqlite3*,
  4868. void*,
  4869. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4870. );
  4871. #ifdef SQLITE_HAS_CODEC
  4872. /*
  4873. ** Specify the key for an encrypted database. This routine should be
  4874. ** called right after sqlite3_open().
  4875. **
  4876. ** The code to implement this API is not available in the public release
  4877. ** of SQLite.
  4878. */
  4879. SQLITE_API int sqlite3_key(
  4880. sqlite3 *db, /* Database to be rekeyed */
  4881. const void *pKey, int nKey /* The key */
  4882. );
  4883. /*
  4884. ** Change the key on an open database. If the current database is not
  4885. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4886. ** database is decrypted.
  4887. **
  4888. ** The code to implement this API is not available in the public release
  4889. ** of SQLite.
  4890. */
  4891. SQLITE_API int sqlite3_rekey(
  4892. sqlite3 *db, /* Database to be rekeyed */
  4893. const void *pKey, int nKey /* The new key */
  4894. );
  4895. /*
  4896. ** Specify the activation key for a SEE database. Unless
  4897. ** activated, none of the SEE routines will work.
  4898. */
  4899. SQLITE_API void sqlite3_activate_see(
  4900. const char *zPassPhrase /* Activation phrase */
  4901. );
  4902. #endif
  4903. #ifdef SQLITE_ENABLE_CEROD
  4904. /*
  4905. ** Specify the activation key for a CEROD database. Unless
  4906. ** activated, none of the CEROD routines will work.
  4907. */
  4908. SQLITE_API void sqlite3_activate_cerod(
  4909. const char *zPassPhrase /* Activation phrase */
  4910. );
  4911. #endif
  4912. /*
  4913. ** CAPI3REF: Suspend Execution For A Short Time
  4914. **
  4915. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4916. ** for at least a number of milliseconds specified in its parameter.
  4917. **
  4918. ** If the operating system does not support sleep requests with
  4919. ** millisecond time resolution, then the time will be rounded up to
  4920. ** the nearest second. The number of milliseconds of sleep actually
  4921. ** requested from the operating system is returned.
  4922. **
  4923. ** ^SQLite implements this interface by calling the xSleep()
  4924. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4925. ** of the default VFS is not implemented correctly, or not implemented at
  4926. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4927. ** in the previous paragraphs.
  4928. */
  4929. SQLITE_API int sqlite3_sleep(int);
  4930. /*
  4931. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4932. **
  4933. ** ^(If this global variable is made to point to a string which is
  4934. ** the name of a folder (a.k.a. directory), then all temporary files
  4935. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4936. ** will be placed in that directory.)^ ^If this variable
  4937. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4938. ** temporary file directory.
  4939. **
  4940. ** It is not safe to read or modify this variable in more than one
  4941. ** thread at a time. It is not safe to read or modify this variable
  4942. ** if a [database connection] is being used at the same time in a separate
  4943. ** thread.
  4944. ** It is intended that this variable be set once
  4945. ** as part of process initialization and before any SQLite interface
  4946. ** routines have been called and that this variable remain unchanged
  4947. ** thereafter.
  4948. **
  4949. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4950. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4951. ** the [temp_store_directory pragma] always assumes that any string
  4952. ** that this variable points to is held in memory obtained from
  4953. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4954. ** using [sqlite3_free].
  4955. ** Hence, if this variable is modified directly, either it should be
  4956. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4957. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4958. **
  4959. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4960. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4961. ** features that require the use of temporary files may fail. Here is an
  4962. ** example of how to do this using C++ with the Windows Runtime:
  4963. **
  4964. ** <blockquote><pre>
  4965. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4966. ** &nbsp; TemporaryFolder->Path->Data();
  4967. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4968. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4969. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4970. ** &nbsp; NULL, NULL);
  4971. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4972. ** </pre></blockquote>
  4973. */
  4974. SQLITE_API char *sqlite3_temp_directory;
  4975. /*
  4976. ** CAPI3REF: Name Of The Folder Holding Database Files
  4977. **
  4978. ** ^(If this global variable is made to point to a string which is
  4979. ** the name of a folder (a.k.a. directory), then all database files
  4980. ** specified with a relative pathname and created or accessed by
  4981. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4982. ** to be relative to that directory.)^ ^If this variable is a NULL
  4983. ** pointer, then SQLite assumes that all database files specified
  4984. ** with a relative pathname are relative to the current directory
  4985. ** for the process. Only the windows VFS makes use of this global
  4986. ** variable; it is ignored by the unix VFS.
  4987. **
  4988. ** Changing the value of this variable while a database connection is
  4989. ** open can result in a corrupt database.
  4990. **
  4991. ** It is not safe to read or modify this variable in more than one
  4992. ** thread at a time. It is not safe to read or modify this variable
  4993. ** if a [database connection] is being used at the same time in a separate
  4994. ** thread.
  4995. ** It is intended that this variable be set once
  4996. ** as part of process initialization and before any SQLite interface
  4997. ** routines have been called and that this variable remain unchanged
  4998. ** thereafter.
  4999. **
  5000. ** ^The [data_store_directory pragma] may modify this variable and cause
  5001. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5002. ** the [data_store_directory pragma] always assumes that any string
  5003. ** that this variable points to is held in memory obtained from
  5004. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5005. ** using [sqlite3_free].
  5006. ** Hence, if this variable is modified directly, either it should be
  5007. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5008. ** or else the use of the [data_store_directory pragma] should be avoided.
  5009. */
  5010. SQLITE_API char *sqlite3_data_directory;
  5011. /*
  5012. ** CAPI3REF: Test For Auto-Commit Mode
  5013. ** KEYWORDS: {autocommit mode}
  5014. **
  5015. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5016. ** zero if the given database connection is or is not in autocommit mode,
  5017. ** respectively. ^Autocommit mode is on by default.
  5018. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5019. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5020. **
  5021. ** If certain kinds of errors occur on a statement within a multi-statement
  5022. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5023. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5024. ** transaction might be rolled back automatically. The only way to
  5025. ** find out whether SQLite automatically rolled back the transaction after
  5026. ** an error is to use this function.
  5027. **
  5028. ** If another thread changes the autocommit status of the database
  5029. ** connection while this routine is running, then the return value
  5030. ** is undefined.
  5031. */
  5032. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  5033. /*
  5034. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5035. **
  5036. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5037. ** to which a [prepared statement] belongs. ^The [database connection]
  5038. ** returned by sqlite3_db_handle is the same [database connection]
  5039. ** that was the first argument
  5040. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5041. ** create the statement in the first place.
  5042. */
  5043. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  5044. /*
  5045. ** CAPI3REF: Return The Filename For A Database Connection
  5046. **
  5047. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5048. ** associated with database N of connection D. ^The main database file
  5049. ** has the name "main". If there is no attached database N on the database
  5050. ** connection D, or if database N is a temporary or in-memory database, then
  5051. ** a NULL pointer is returned.
  5052. **
  5053. ** ^The filename returned by this function is the output of the
  5054. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5055. ** will be an absolute pathname, even if the filename used
  5056. ** to open the database originally was a URI or relative pathname.
  5057. */
  5058. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5059. /*
  5060. ** CAPI3REF: Determine if a database is read-only
  5061. **
  5062. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5063. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5064. ** the name of a database on connection D.
  5065. */
  5066. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5067. /*
  5068. ** CAPI3REF: Find the next prepared statement
  5069. **
  5070. ** ^This interface returns a pointer to the next [prepared statement] after
  5071. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5072. ** then this interface returns a pointer to the first prepared statement
  5073. ** associated with the database connection pDb. ^If no prepared statement
  5074. ** satisfies the conditions of this routine, it returns NULL.
  5075. **
  5076. ** The [database connection] pointer D in a call to
  5077. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5078. ** connection and in particular must not be a NULL pointer.
  5079. */
  5080. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5081. /*
  5082. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5083. **
  5084. ** ^The sqlite3_commit_hook() interface registers a callback
  5085. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5086. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5087. ** for the same database connection is overridden.
  5088. ** ^The sqlite3_rollback_hook() interface registers a callback
  5089. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5090. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5091. ** for the same database connection is overridden.
  5092. ** ^The pArg argument is passed through to the callback.
  5093. ** ^If the callback on a commit hook function returns non-zero,
  5094. ** then the commit is converted into a rollback.
  5095. **
  5096. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5097. ** return the P argument from the previous call of the same function
  5098. ** on the same [database connection] D, or NULL for
  5099. ** the first call for each function on D.
  5100. **
  5101. ** The commit and rollback hook callbacks are not reentrant.
  5102. ** The callback implementation must not do anything that will modify
  5103. ** the database connection that invoked the callback. Any actions
  5104. ** to modify the database connection must be deferred until after the
  5105. ** completion of the [sqlite3_step()] call that triggered the commit
  5106. ** or rollback hook in the first place.
  5107. ** Note that running any other SQL statements, including SELECT statements,
  5108. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5109. ** the database connections for the meaning of "modify" in this paragraph.
  5110. **
  5111. ** ^Registering a NULL function disables the callback.
  5112. **
  5113. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5114. ** operation is allowed to continue normally. ^If the commit hook
  5115. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5116. ** ^The rollback hook is invoked on a rollback that results from a commit
  5117. ** hook returning non-zero, just as it would be with any other rollback.
  5118. **
  5119. ** ^For the purposes of this API, a transaction is said to have been
  5120. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5121. ** an error or constraint causes an implicit rollback to occur.
  5122. ** ^The rollback callback is not invoked if a transaction is
  5123. ** automatically rolled back because the database connection is closed.
  5124. **
  5125. ** See also the [sqlite3_update_hook()] interface.
  5126. */
  5127. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5128. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5129. /*
  5130. ** CAPI3REF: Data Change Notification Callbacks
  5131. **
  5132. ** ^The sqlite3_update_hook() interface registers a callback function
  5133. ** with the [database connection] identified by the first argument
  5134. ** to be invoked whenever a row is updated, inserted or deleted.
  5135. ** ^Any callback set by a previous call to this function
  5136. ** for the same database connection is overridden.
  5137. **
  5138. ** ^The second argument is a pointer to the function to invoke when a
  5139. ** row is updated, inserted or deleted.
  5140. ** ^The first argument to the callback is a copy of the third argument
  5141. ** to sqlite3_update_hook().
  5142. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5143. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5144. ** to be invoked.
  5145. ** ^The third and fourth arguments to the callback contain pointers to the
  5146. ** database and table name containing the affected row.
  5147. ** ^The final callback parameter is the [rowid] of the row.
  5148. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5149. **
  5150. ** ^(The update hook is not invoked when internal system tables are
  5151. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5152. **
  5153. ** ^In the current implementation, the update hook
  5154. ** is not invoked when duplication rows are deleted because of an
  5155. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5156. ** invoked when rows are deleted using the [truncate optimization].
  5157. ** The exceptions defined in this paragraph might change in a future
  5158. ** release of SQLite.
  5159. **
  5160. ** The update hook implementation must not do anything that will modify
  5161. ** the database connection that invoked the update hook. Any actions
  5162. ** to modify the database connection must be deferred until after the
  5163. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5164. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5165. ** database connections for the meaning of "modify" in this paragraph.
  5166. **
  5167. ** ^The sqlite3_update_hook(D,C,P) function
  5168. ** returns the P argument from the previous call
  5169. ** on the same [database connection] D, or NULL for
  5170. ** the first call on D.
  5171. **
  5172. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5173. ** interfaces.
  5174. */
  5175. SQLITE_API void *sqlite3_update_hook(
  5176. sqlite3*,
  5177. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5178. void*
  5179. );
  5180. /*
  5181. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5182. **
  5183. ** ^(This routine enables or disables the sharing of the database cache
  5184. ** and schema data structures between [database connection | connections]
  5185. ** to the same database. Sharing is enabled if the argument is true
  5186. ** and disabled if the argument is false.)^
  5187. **
  5188. ** ^Cache sharing is enabled and disabled for an entire process.
  5189. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5190. ** sharing was enabled or disabled for each thread separately.
  5191. **
  5192. ** ^(The cache sharing mode set by this interface effects all subsequent
  5193. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5194. ** Existing database connections continue use the sharing mode
  5195. ** that was in effect at the time they were opened.)^
  5196. **
  5197. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5198. ** successfully. An [error code] is returned otherwise.)^
  5199. **
  5200. ** ^Shared cache is disabled by default. But this might change in
  5201. ** future releases of SQLite. Applications that care about shared
  5202. ** cache setting should set it explicitly.
  5203. **
  5204. ** This interface is threadsafe on processors where writing a
  5205. ** 32-bit integer is atomic.
  5206. **
  5207. ** See Also: [SQLite Shared-Cache Mode]
  5208. */
  5209. SQLITE_API int sqlite3_enable_shared_cache(int);
  5210. /*
  5211. ** CAPI3REF: Attempt To Free Heap Memory
  5212. **
  5213. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5214. ** of heap memory by deallocating non-essential memory allocations
  5215. ** held by the database library. Memory used to cache database
  5216. ** pages to improve performance is an example of non-essential memory.
  5217. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5218. ** which might be more or less than the amount requested.
  5219. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5220. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5221. **
  5222. ** See also: [sqlite3_db_release_memory()]
  5223. */
  5224. SQLITE_API int sqlite3_release_memory(int);
  5225. /*
  5226. ** CAPI3REF: Free Memory Used By A Database Connection
  5227. **
  5228. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5229. ** memory as possible from database connection D. Unlike the
  5230. ** [sqlite3_release_memory()] interface, this interface is effect even
  5231. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5232. ** omitted.
  5233. **
  5234. ** See also: [sqlite3_release_memory()]
  5235. */
  5236. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5237. /*
  5238. ** CAPI3REF: Impose A Limit On Heap Size
  5239. **
  5240. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5241. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5242. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5243. ** limit by reducing the number of pages held in the page cache
  5244. ** as heap memory usages approaches the limit.
  5245. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5246. ** below the limit, it will exceed the limit rather than generate
  5247. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5248. ** is advisory only.
  5249. **
  5250. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5251. ** the soft heap limit prior to the call, or negative in the case of an
  5252. ** error. ^If the argument N is negative
  5253. ** then no change is made to the soft heap limit. Hence, the current
  5254. ** size of the soft heap limit can be determined by invoking
  5255. ** sqlite3_soft_heap_limit64() with a negative argument.
  5256. **
  5257. ** ^If the argument N is zero then the soft heap limit is disabled.
  5258. **
  5259. ** ^(The soft heap limit is not enforced in the current implementation
  5260. ** if one or more of following conditions are true:
  5261. **
  5262. ** <ul>
  5263. ** <li> The soft heap limit is set to zero.
  5264. ** <li> Memory accounting is disabled using a combination of the
  5265. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5266. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5267. ** <li> An alternative page cache implementation is specified using
  5268. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5269. ** <li> The page cache allocates from its own memory pool supplied
  5270. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5271. ** from the heap.
  5272. ** </ul>)^
  5273. **
  5274. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5275. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5276. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5277. ** the soft heap limit is enforced on every memory allocation. Without
  5278. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5279. ** when memory is allocated by the page cache. Testing suggests that because
  5280. ** the page cache is the predominate memory user in SQLite, most
  5281. ** applications will achieve adequate soft heap limit enforcement without
  5282. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5283. **
  5284. ** The circumstances under which SQLite will enforce the soft heap limit may
  5285. ** changes in future releases of SQLite.
  5286. */
  5287. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5288. /*
  5289. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5290. ** DEPRECATED
  5291. **
  5292. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5293. ** interface. This routine is provided for historical compatibility
  5294. ** only. All new applications should use the
  5295. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5296. */
  5297. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5298. /*
  5299. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5300. **
  5301. ** ^This routine returns metadata about a specific column of a specific
  5302. ** database table accessible using the [database connection] handle
  5303. ** passed as the first function argument.
  5304. **
  5305. ** ^The column is identified by the second, third and fourth parameters to
  5306. ** this function. ^The second parameter is either the name of the database
  5307. ** (i.e. "main", "temp", or an attached database) containing the specified
  5308. ** table or NULL. ^If it is NULL, then all attached databases are searched
  5309. ** for the table using the same algorithm used by the database engine to
  5310. ** resolve unqualified table references.
  5311. **
  5312. ** ^The third and fourth parameters to this function are the table and column
  5313. ** name of the desired column, respectively. Neither of these parameters
  5314. ** may be NULL.
  5315. **
  5316. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5317. ** and subsequent parameters to this function. ^Any of these arguments may be
  5318. ** NULL, in which case the corresponding element of metadata is omitted.
  5319. **
  5320. ** ^(<blockquote>
  5321. ** <table border="1">
  5322. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5323. **
  5324. ** <tr><td> 5th <td> const char* <td> Data type
  5325. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5326. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5327. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5328. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5329. ** </table>
  5330. ** </blockquote>)^
  5331. **
  5332. ** ^The memory pointed to by the character pointers returned for the
  5333. ** declaration type and collation sequence is valid only until the next
  5334. ** call to any SQLite API function.
  5335. **
  5336. ** ^If the specified table is actually a view, an [error code] is returned.
  5337. **
  5338. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  5339. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5340. ** parameters are set for the explicitly declared column. ^(If there is no
  5341. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5342. ** parameters are set as follows:
  5343. **
  5344. ** <pre>
  5345. ** data type: "INTEGER"
  5346. ** collation sequence: "BINARY"
  5347. ** not null: 0
  5348. ** primary key: 1
  5349. ** auto increment: 0
  5350. ** </pre>)^
  5351. **
  5352. ** ^(This function may load one or more schemas from database files. If an
  5353. ** error occurs during this process, or if the requested table or column
  5354. ** cannot be found, an [error code] is returned and an error message left
  5355. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  5356. **
  5357. ** ^This API is only available if the library was compiled with the
  5358. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5359. */
  5360. SQLITE_API int sqlite3_table_column_metadata(
  5361. sqlite3 *db, /* Connection handle */
  5362. const char *zDbName, /* Database name or NULL */
  5363. const char *zTableName, /* Table name */
  5364. const char *zColumnName, /* Column name */
  5365. char const **pzDataType, /* OUTPUT: Declared data type */
  5366. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5367. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5368. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5369. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5370. );
  5371. /*
  5372. ** CAPI3REF: Load An Extension
  5373. **
  5374. ** ^This interface loads an SQLite extension library from the named file.
  5375. **
  5376. ** ^The sqlite3_load_extension() interface attempts to load an
  5377. ** SQLite extension library contained in the file zFile.
  5378. **
  5379. ** ^The entry point is zProc.
  5380. ** ^zProc may be 0, in which case the name of the entry point
  5381. ** defaults to "sqlite3_extension_init".
  5382. ** ^The sqlite3_load_extension() interface returns
  5383. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5384. ** ^If an error occurs and pzErrMsg is not 0, then the
  5385. ** [sqlite3_load_extension()] interface shall attempt to
  5386. ** fill *pzErrMsg with error message text stored in memory
  5387. ** obtained from [sqlite3_malloc()]. The calling function
  5388. ** should free this memory by calling [sqlite3_free()].
  5389. **
  5390. ** ^Extension loading must be enabled using
  5391. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5392. ** otherwise an error will be returned.
  5393. **
  5394. ** See also the [load_extension() SQL function].
  5395. */
  5396. SQLITE_API int sqlite3_load_extension(
  5397. sqlite3 *db, /* Load the extension into this database connection */
  5398. const char *zFile, /* Name of the shared library containing extension */
  5399. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5400. char **pzErrMsg /* Put error message here if not 0 */
  5401. );
  5402. /*
  5403. ** CAPI3REF: Enable Or Disable Extension Loading
  5404. **
  5405. ** ^So as not to open security holes in older applications that are
  5406. ** unprepared to deal with extension loading, and as a means of disabling
  5407. ** extension loading while evaluating user-entered SQL, the following API
  5408. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5409. **
  5410. ** ^Extension loading is off by default. See ticket #1863.
  5411. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5412. ** to turn extension loading on and call it with onoff==0 to turn
  5413. ** it back off again.
  5414. */
  5415. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5416. /*
  5417. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5418. **
  5419. ** ^This interface causes the xEntryPoint() function to be invoked for
  5420. ** each new [database connection] that is created. The idea here is that
  5421. ** xEntryPoint() is the entry point for a statically linked SQLite extension
  5422. ** that is to be automatically loaded into all new database connections.
  5423. **
  5424. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5425. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5426. ** arguments and expects and integer result as if the signature of the
  5427. ** entry point where as follows:
  5428. **
  5429. ** <blockquote><pre>
  5430. ** &nbsp; int xEntryPoint(
  5431. ** &nbsp; sqlite3 *db,
  5432. ** &nbsp; const char **pzErrMsg,
  5433. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5434. ** &nbsp; );
  5435. ** </pre></blockquote>)^
  5436. **
  5437. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5438. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5439. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5440. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5441. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5442. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5443. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5444. **
  5445. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5446. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5447. ** will be called more than once for each database connection that is opened.
  5448. **
  5449. ** See also: [sqlite3_reset_auto_extension()].
  5450. */
  5451. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5452. /*
  5453. ** CAPI3REF: Reset Automatic Extension Loading
  5454. **
  5455. ** ^This interface disables all automatic extensions previously
  5456. ** registered using [sqlite3_auto_extension()].
  5457. */
  5458. SQLITE_API void sqlite3_reset_auto_extension(void);
  5459. /*
  5460. ** The interface to the virtual-table mechanism is currently considered
  5461. ** to be experimental. The interface might change in incompatible ways.
  5462. ** If this is a problem for you, do not use the interface at this time.
  5463. **
  5464. ** When the virtual-table mechanism stabilizes, we will declare the
  5465. ** interface fixed, support it indefinitely, and remove this comment.
  5466. */
  5467. /*
  5468. ** Structures used by the virtual table interface
  5469. */
  5470. typedef struct sqlite3_vtab sqlite3_vtab;
  5471. typedef struct sqlite3_index_info sqlite3_index_info;
  5472. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5473. typedef struct sqlite3_module sqlite3_module;
  5474. /*
  5475. ** CAPI3REF: Virtual Table Object
  5476. ** KEYWORDS: sqlite3_module {virtual table module}
  5477. **
  5478. ** This structure, sometimes called a "virtual table module",
  5479. ** defines the implementation of a [virtual tables].
  5480. ** This structure consists mostly of methods for the module.
  5481. **
  5482. ** ^A virtual table module is created by filling in a persistent
  5483. ** instance of this structure and passing a pointer to that instance
  5484. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5485. ** ^The registration remains valid until it is replaced by a different
  5486. ** module or until the [database connection] closes. The content
  5487. ** of this structure must not change while it is registered with
  5488. ** any database connection.
  5489. */
  5490. struct sqlite3_module {
  5491. int iVersion;
  5492. int (*xCreate)(sqlite3*, void *pAux,
  5493. int argc, const char *const*argv,
  5494. sqlite3_vtab **ppVTab, char**);
  5495. int (*xConnect)(sqlite3*, void *pAux,
  5496. int argc, const char *const*argv,
  5497. sqlite3_vtab **ppVTab, char**);
  5498. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5499. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5500. int (*xDestroy)(sqlite3_vtab *pVTab);
  5501. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5502. int (*xClose)(sqlite3_vtab_cursor*);
  5503. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5504. int argc, sqlite3_value **argv);
  5505. int (*xNext)(sqlite3_vtab_cursor*);
  5506. int (*xEof)(sqlite3_vtab_cursor*);
  5507. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5508. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5509. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5510. int (*xBegin)(sqlite3_vtab *pVTab);
  5511. int (*xSync)(sqlite3_vtab *pVTab);
  5512. int (*xCommit)(sqlite3_vtab *pVTab);
  5513. int (*xRollback)(sqlite3_vtab *pVTab);
  5514. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5515. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5516. void **ppArg);
  5517. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5518. /* The methods above are in version 1 of the sqlite_module object. Those
  5519. ** below are for version 2 and greater. */
  5520. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5521. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5522. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5523. };
  5524. /*
  5525. ** CAPI3REF: Virtual Table Indexing Information
  5526. ** KEYWORDS: sqlite3_index_info
  5527. **
  5528. ** The sqlite3_index_info structure and its substructures is used as part
  5529. ** of the [virtual table] interface to
  5530. ** pass information into and receive the reply from the [xBestIndex]
  5531. ** method of a [virtual table module]. The fields under **Inputs** are the
  5532. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5533. ** results into the **Outputs** fields.
  5534. **
  5535. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5536. **
  5537. ** <blockquote>column OP expr</blockquote>
  5538. **
  5539. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5540. ** stored in aConstraint[].op using one of the
  5541. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5542. ** ^(The index of the column is stored in
  5543. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5544. ** expr on the right-hand side can be evaluated (and thus the constraint
  5545. ** is usable) and false if it cannot.)^
  5546. **
  5547. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5548. ** and makes other simplifications to the WHERE clause in an attempt to
  5549. ** get as many WHERE clause terms into the form shown above as possible.
  5550. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5551. ** relevant to the particular virtual table being queried.
  5552. **
  5553. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5554. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5555. **
  5556. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5557. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5558. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5559. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5560. ** is true, then the constraint is assumed to be fully handled by the
  5561. ** virtual table and is not checked again by SQLite.)^
  5562. **
  5563. ** ^The idxNum and idxPtr values are recorded and passed into the
  5564. ** [xFilter] method.
  5565. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5566. ** needToFreeIdxPtr is true.
  5567. **
  5568. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5569. ** the correct order to satisfy the ORDER BY clause so that no separate
  5570. ** sorting step is required.
  5571. **
  5572. ** ^The estimatedCost value is an estimate of the cost of doing the
  5573. ** particular lookup. A full scan of a table with N entries should have
  5574. ** a cost of N. A binary search of a table of N entries should have a
  5575. ** cost of approximately log(N).
  5576. */
  5577. struct sqlite3_index_info {
  5578. /* Inputs */
  5579. int nConstraint; /* Number of entries in aConstraint */
  5580. struct sqlite3_index_constraint {
  5581. int iColumn; /* Column on left-hand side of constraint */
  5582. unsigned char op; /* Constraint operator */
  5583. unsigned char usable; /* True if this constraint is usable */
  5584. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5585. } *aConstraint; /* Table of WHERE clause constraints */
  5586. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5587. struct sqlite3_index_orderby {
  5588. int iColumn; /* Column number */
  5589. unsigned char desc; /* True for DESC. False for ASC. */
  5590. } *aOrderBy; /* The ORDER BY clause */
  5591. /* Outputs */
  5592. struct sqlite3_index_constraint_usage {
  5593. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5594. unsigned char omit; /* Do not code a test for this constraint */
  5595. } *aConstraintUsage;
  5596. int idxNum; /* Number used to identify the index */
  5597. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5598. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5599. int orderByConsumed; /* True if output is already ordered */
  5600. double estimatedCost; /* Estimated cost of using this index */
  5601. };
  5602. /*
  5603. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5604. **
  5605. ** These macros defined the allowed values for the
  5606. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5607. ** an operator that is part of a constraint term in the wHERE clause of
  5608. ** a query that uses a [virtual table].
  5609. */
  5610. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5611. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5612. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5613. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5614. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5615. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5616. /*
  5617. ** CAPI3REF: Register A Virtual Table Implementation
  5618. **
  5619. ** ^These routines are used to register a new [virtual table module] name.
  5620. ** ^Module names must be registered before
  5621. ** creating a new [virtual table] using the module and before using a
  5622. ** preexisting [virtual table] for the module.
  5623. **
  5624. ** ^The module name is registered on the [database connection] specified
  5625. ** by the first parameter. ^The name of the module is given by the
  5626. ** second parameter. ^The third parameter is a pointer to
  5627. ** the implementation of the [virtual table module]. ^The fourth
  5628. ** parameter is an arbitrary client data pointer that is passed through
  5629. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5630. ** when a new virtual table is be being created or reinitialized.
  5631. **
  5632. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5633. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5634. ** invoke the destructor function (if it is not NULL) when SQLite
  5635. ** no longer needs the pClientData pointer. ^The destructor will also
  5636. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5637. ** ^The sqlite3_create_module()
  5638. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5639. ** destructor.
  5640. */
  5641. SQLITE_API int sqlite3_create_module(
  5642. sqlite3 *db, /* SQLite connection to register module with */
  5643. const char *zName, /* Name of the module */
  5644. const sqlite3_module *p, /* Methods for the module */
  5645. void *pClientData /* Client data for xCreate/xConnect */
  5646. );
  5647. SQLITE_API int sqlite3_create_module_v2(
  5648. sqlite3 *db, /* SQLite connection to register module with */
  5649. const char *zName, /* Name of the module */
  5650. const sqlite3_module *p, /* Methods for the module */
  5651. void *pClientData, /* Client data for xCreate/xConnect */
  5652. void(*xDestroy)(void*) /* Module destructor function */
  5653. );
  5654. /*
  5655. ** CAPI3REF: Virtual Table Instance Object
  5656. ** KEYWORDS: sqlite3_vtab
  5657. **
  5658. ** Every [virtual table module] implementation uses a subclass
  5659. ** of this object to describe a particular instance
  5660. ** of the [virtual table]. Each subclass will
  5661. ** be tailored to the specific needs of the module implementation.
  5662. ** The purpose of this superclass is to define certain fields that are
  5663. ** common to all module implementations.
  5664. **
  5665. ** ^Virtual tables methods can set an error message by assigning a
  5666. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5667. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5668. ** prior to assigning a new string to zErrMsg. ^After the error message
  5669. ** is delivered up to the client application, the string will be automatically
  5670. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5671. */
  5672. struct sqlite3_vtab {
  5673. const sqlite3_module *pModule; /* The module for this virtual table */
  5674. int nRef; /* NO LONGER USED */
  5675. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5676. /* Virtual table implementations will typically add additional fields */
  5677. };
  5678. /*
  5679. ** CAPI3REF: Virtual Table Cursor Object
  5680. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5681. **
  5682. ** Every [virtual table module] implementation uses a subclass of the
  5683. ** following structure to describe cursors that point into the
  5684. ** [virtual table] and are used
  5685. ** to loop through the virtual table. Cursors are created using the
  5686. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5687. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5688. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5689. ** of the module. Each module implementation will define
  5690. ** the content of a cursor structure to suit its own needs.
  5691. **
  5692. ** This superclass exists in order to define fields of the cursor that
  5693. ** are common to all implementations.
  5694. */
  5695. struct sqlite3_vtab_cursor {
  5696. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5697. /* Virtual table implementations will typically add additional fields */
  5698. };
  5699. /*
  5700. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5701. **
  5702. ** ^The [xCreate] and [xConnect] methods of a
  5703. ** [virtual table module] call this interface
  5704. ** to declare the format (the names and datatypes of the columns) of
  5705. ** the virtual tables they implement.
  5706. */
  5707. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5708. /*
  5709. ** CAPI3REF: Overload A Function For A Virtual Table
  5710. **
  5711. ** ^(Virtual tables can provide alternative implementations of functions
  5712. ** using the [xFindFunction] method of the [virtual table module].
  5713. ** But global versions of those functions
  5714. ** must exist in order to be overloaded.)^
  5715. **
  5716. ** ^(This API makes sure a global version of a function with a particular
  5717. ** name and number of parameters exists. If no such function exists
  5718. ** before this API is called, a new function is created.)^ ^The implementation
  5719. ** of the new function always causes an exception to be thrown. So
  5720. ** the new function is not good for anything by itself. Its only
  5721. ** purpose is to be a placeholder function that can be overloaded
  5722. ** by a [virtual table].
  5723. */
  5724. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5725. /*
  5726. ** The interface to the virtual-table mechanism defined above (back up
  5727. ** to a comment remarkably similar to this one) is currently considered
  5728. ** to be experimental. The interface might change in incompatible ways.
  5729. ** If this is a problem for you, do not use the interface at this time.
  5730. **
  5731. ** When the virtual-table mechanism stabilizes, we will declare the
  5732. ** interface fixed, support it indefinitely, and remove this comment.
  5733. */
  5734. /*
  5735. ** CAPI3REF: A Handle To An Open BLOB
  5736. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5737. **
  5738. ** An instance of this object represents an open BLOB on which
  5739. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5740. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5741. ** and destroyed by [sqlite3_blob_close()].
  5742. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5743. ** can be used to read or write small subsections of the BLOB.
  5744. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5745. */
  5746. typedef struct sqlite3_blob sqlite3_blob;
  5747. /*
  5748. ** CAPI3REF: Open A BLOB For Incremental I/O
  5749. **
  5750. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5751. ** in row iRow, column zColumn, table zTable in database zDb;
  5752. ** in other words, the same BLOB that would be selected by:
  5753. **
  5754. ** <pre>
  5755. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5756. ** </pre>)^
  5757. **
  5758. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5759. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5760. ** ^It is not possible to open a column that is part of an index or primary
  5761. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5762. ** not possible to open a column that is part of a [child key] for writing.
  5763. **
  5764. ** ^Note that the database name is not the filename that contains
  5765. ** the database but rather the symbolic name of the database that
  5766. ** appears after the AS keyword when the database is connected using [ATTACH].
  5767. ** ^For the main database file, the database name is "main".
  5768. ** ^For TEMP tables, the database name is "temp".
  5769. **
  5770. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5771. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5772. ** to be a null pointer.)^
  5773. ** ^This function sets the [database connection] error code and message
  5774. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5775. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5776. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5777. ** regardless of the success or failure of this routine.
  5778. **
  5779. ** ^(If the row that a BLOB handle points to is modified by an
  5780. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5781. ** then the BLOB handle is marked as "expired".
  5782. ** This is true if any column of the row is changed, even a column
  5783. ** other than the one the BLOB handle is open on.)^
  5784. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5785. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5786. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5787. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5788. ** commit if the transaction continues to completion.)^
  5789. **
  5790. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5791. ** the opened blob. ^The size of a blob may not be changed by this
  5792. ** interface. Use the [UPDATE] SQL command to change the size of a
  5793. ** blob.
  5794. **
  5795. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5796. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5797. ** to create an empty, zero-filled blob in which to read or write using
  5798. ** this interface.
  5799. **
  5800. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5801. ** be released by a call to [sqlite3_blob_close()].
  5802. */
  5803. SQLITE_API int sqlite3_blob_open(
  5804. sqlite3*,
  5805. const char *zDb,
  5806. const char *zTable,
  5807. const char *zColumn,
  5808. sqlite3_int64 iRow,
  5809. int flags,
  5810. sqlite3_blob **ppBlob
  5811. );
  5812. /*
  5813. ** CAPI3REF: Move a BLOB Handle to a New Row
  5814. **
  5815. ** ^This function is used to move an existing blob handle so that it points
  5816. ** to a different row of the same database table. ^The new row is identified
  5817. ** by the rowid value passed as the second argument. Only the row can be
  5818. ** changed. ^The database, table and column on which the blob handle is open
  5819. ** remain the same. Moving an existing blob handle to a new row can be
  5820. ** faster than closing the existing handle and opening a new one.
  5821. **
  5822. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5823. ** it must exist and there must be either a blob or text value stored in
  5824. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5825. ** it does not contain a blob or text value, or if another error occurs, an
  5826. ** SQLite error code is returned and the blob handle is considered aborted.
  5827. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5828. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5829. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5830. ** always returns zero.
  5831. **
  5832. ** ^This function sets the database handle error code and message.
  5833. */
  5834. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5835. /*
  5836. ** CAPI3REF: Close A BLOB Handle
  5837. **
  5838. ** ^Closes an open [BLOB handle].
  5839. **
  5840. ** ^Closing a BLOB shall cause the current transaction to commit
  5841. ** if there are no other BLOBs, no pending prepared statements, and the
  5842. ** database connection is in [autocommit mode].
  5843. ** ^If any writes were made to the BLOB, they might be held in cache
  5844. ** until the close operation if they will fit.
  5845. **
  5846. ** ^(Closing the BLOB often forces the changes
  5847. ** out to disk and so if any I/O errors occur, they will likely occur
  5848. ** at the time when the BLOB is closed. Any errors that occur during
  5849. ** closing are reported as a non-zero return value.)^
  5850. **
  5851. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5852. ** an error code, the BLOB is still closed.)^
  5853. **
  5854. ** ^Calling this routine with a null pointer (such as would be returned
  5855. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5856. */
  5857. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5858. /*
  5859. ** CAPI3REF: Return The Size Of An Open BLOB
  5860. **
  5861. ** ^Returns the size in bytes of the BLOB accessible via the
  5862. ** successfully opened [BLOB handle] in its only argument. ^The
  5863. ** incremental blob I/O routines can only read or overwriting existing
  5864. ** blob content; they cannot change the size of a blob.
  5865. **
  5866. ** This routine only works on a [BLOB handle] which has been created
  5867. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5868. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5869. ** to this routine results in undefined and probably undesirable behavior.
  5870. */
  5871. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5872. /*
  5873. ** CAPI3REF: Read Data From A BLOB Incrementally
  5874. **
  5875. ** ^(This function is used to read data from an open [BLOB handle] into a
  5876. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5877. ** from the open BLOB, starting at offset iOffset.)^
  5878. **
  5879. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5880. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5881. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5882. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5883. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5884. **
  5885. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5886. ** error code of [SQLITE_ABORT].
  5887. **
  5888. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5889. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5890. **
  5891. ** This routine only works on a [BLOB handle] which has been created
  5892. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5893. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5894. ** to this routine results in undefined and probably undesirable behavior.
  5895. **
  5896. ** See also: [sqlite3_blob_write()].
  5897. */
  5898. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5899. /*
  5900. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5901. **
  5902. ** ^This function is used to write data into an open [BLOB handle] from a
  5903. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5904. ** into the open BLOB, starting at offset iOffset.
  5905. **
  5906. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5907. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5908. ** this function returns [SQLITE_READONLY].
  5909. **
  5910. ** ^This function may only modify the contents of the BLOB; it is
  5911. ** not possible to increase the size of a BLOB using this API.
  5912. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5913. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5914. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5915. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5916. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5917. **
  5918. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5919. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5920. ** before the [BLOB handle] expired are not rolled back by the
  5921. ** expiration of the handle, though of course those changes might
  5922. ** have been overwritten by the statement that expired the BLOB handle
  5923. ** or by other independent statements.
  5924. **
  5925. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5926. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5927. **
  5928. ** This routine only works on a [BLOB handle] which has been created
  5929. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5930. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5931. ** to this routine results in undefined and probably undesirable behavior.
  5932. **
  5933. ** See also: [sqlite3_blob_read()].
  5934. */
  5935. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5936. /*
  5937. ** CAPI3REF: Virtual File System Objects
  5938. **
  5939. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5940. ** that SQLite uses to interact
  5941. ** with the underlying operating system. Most SQLite builds come with a
  5942. ** single default VFS that is appropriate for the host computer.
  5943. ** New VFSes can be registered and existing VFSes can be unregistered.
  5944. ** The following interfaces are provided.
  5945. **
  5946. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5947. ** ^Names are case sensitive.
  5948. ** ^Names are zero-terminated UTF-8 strings.
  5949. ** ^If there is no match, a NULL pointer is returned.
  5950. ** ^If zVfsName is NULL then the default VFS is returned.
  5951. **
  5952. ** ^New VFSes are registered with sqlite3_vfs_register().
  5953. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5954. ** ^The same VFS can be registered multiple times without injury.
  5955. ** ^To make an existing VFS into the default VFS, register it again
  5956. ** with the makeDflt flag set. If two different VFSes with the
  5957. ** same name are registered, the behavior is undefined. If a
  5958. ** VFS is registered with a name that is NULL or an empty string,
  5959. ** then the behavior is undefined.
  5960. **
  5961. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5962. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5963. ** the default. The choice for the new VFS is arbitrary.)^
  5964. */
  5965. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5966. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5967. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5968. /*
  5969. ** CAPI3REF: Mutexes
  5970. **
  5971. ** The SQLite core uses these routines for thread
  5972. ** synchronization. Though they are intended for internal
  5973. ** use by SQLite, code that links against SQLite is
  5974. ** permitted to use any of these routines.
  5975. **
  5976. ** The SQLite source code contains multiple implementations
  5977. ** of these mutex routines. An appropriate implementation
  5978. ** is selected automatically at compile-time. ^(The following
  5979. ** implementations are available in the SQLite core:
  5980. **
  5981. ** <ul>
  5982. ** <li> SQLITE_MUTEX_PTHREADS
  5983. ** <li> SQLITE_MUTEX_W32
  5984. ** <li> SQLITE_MUTEX_NOOP
  5985. ** </ul>)^
  5986. **
  5987. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5988. ** that does no real locking and is appropriate for use in
  5989. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5990. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5991. ** and Windows.
  5992. **
  5993. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5994. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5995. ** implementation is included with the library. In this case the
  5996. ** application must supply a custom mutex implementation using the
  5997. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5998. ** before calling sqlite3_initialize() or any other public sqlite3_
  5999. ** function that calls sqlite3_initialize().)^
  6000. **
  6001. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6002. ** mutex and returns a pointer to it. ^If it returns NULL
  6003. ** that means that a mutex could not be allocated. ^SQLite
  6004. ** will unwind its stack and return an error. ^(The argument
  6005. ** to sqlite3_mutex_alloc() is one of these integer constants:
  6006. **
  6007. ** <ul>
  6008. ** <li> SQLITE_MUTEX_FAST
  6009. ** <li> SQLITE_MUTEX_RECURSIVE
  6010. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6011. ** <li> SQLITE_MUTEX_STATIC_MEM
  6012. ** <li> SQLITE_MUTEX_STATIC_MEM2
  6013. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6014. ** <li> SQLITE_MUTEX_STATIC_LRU
  6015. ** <li> SQLITE_MUTEX_STATIC_LRU2
  6016. ** </ul>)^
  6017. **
  6018. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6019. ** cause sqlite3_mutex_alloc() to create
  6020. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6021. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6022. ** The mutex implementation does not need to make a distinction
  6023. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6024. ** not want to. ^SQLite will only request a recursive mutex in
  6025. ** cases where it really needs one. ^If a faster non-recursive mutex
  6026. ** implementation is available on the host platform, the mutex subsystem
  6027. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6028. **
  6029. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6030. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6031. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  6032. ** used by the current version of SQLite. Future versions of SQLite
  6033. ** may add additional static mutexes. Static mutexes are for internal
  6034. ** use by SQLite only. Applications that use SQLite mutexes should
  6035. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6036. ** SQLITE_MUTEX_RECURSIVE.
  6037. **
  6038. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6039. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6040. ** returns a different mutex on every call. ^But for the static
  6041. ** mutex types, the same mutex is returned on every call that has
  6042. ** the same type number.
  6043. **
  6044. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6045. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  6046. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  6047. ** use when they are deallocated. Attempting to deallocate a static
  6048. ** mutex results in undefined behavior. ^SQLite never deallocates
  6049. ** a static mutex.
  6050. **
  6051. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6052. ** to enter a mutex. ^If another thread is already within the mutex,
  6053. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6054. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6055. ** upon successful entry. ^(Mutexes created using
  6056. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6057. ** In such cases the,
  6058. ** mutex must be exited an equal number of times before another thread
  6059. ** can enter.)^ ^(If the same thread tries to enter any other
  6060. ** kind of mutex more than once, the behavior is undefined.
  6061. ** SQLite will never exhibit
  6062. ** such behavior in its own use of mutexes.)^
  6063. **
  6064. ** ^(Some systems (for example, Windows 95) do not support the operation
  6065. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6066. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6067. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  6068. **
  6069. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6070. ** previously entered by the same thread. ^(The behavior
  6071. ** is undefined if the mutex is not currently entered by the
  6072. ** calling thread or is not currently allocated. SQLite will
  6073. ** never do either.)^
  6074. **
  6075. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6076. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6077. ** behave as no-ops.
  6078. **
  6079. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6080. */
  6081. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  6082. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  6083. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  6084. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  6085. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  6086. /*
  6087. ** CAPI3REF: Mutex Methods Object
  6088. **
  6089. ** An instance of this structure defines the low-level routines
  6090. ** used to allocate and use mutexes.
  6091. **
  6092. ** Usually, the default mutex implementations provided by SQLite are
  6093. ** sufficient, however the user has the option of substituting a custom
  6094. ** implementation for specialized deployments or systems for which SQLite
  6095. ** does not provide a suitable implementation. In this case, the user
  6096. ** creates and populates an instance of this structure to pass
  6097. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6098. ** Additionally, an instance of this structure can be used as an
  6099. ** output variable when querying the system for the current mutex
  6100. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6101. **
  6102. ** ^The xMutexInit method defined by this structure is invoked as
  6103. ** part of system initialization by the sqlite3_initialize() function.
  6104. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6105. ** effective call to [sqlite3_initialize()].
  6106. **
  6107. ** ^The xMutexEnd method defined by this structure is invoked as
  6108. ** part of system shutdown by the sqlite3_shutdown() function. The
  6109. ** implementation of this method is expected to release all outstanding
  6110. ** resources obtained by the mutex methods implementation, especially
  6111. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6112. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6113. **
  6114. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6115. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6116. ** xMutexNotheld) implement the following interfaces (respectively):
  6117. **
  6118. ** <ul>
  6119. ** <li> [sqlite3_mutex_alloc()] </li>
  6120. ** <li> [sqlite3_mutex_free()] </li>
  6121. ** <li> [sqlite3_mutex_enter()] </li>
  6122. ** <li> [sqlite3_mutex_try()] </li>
  6123. ** <li> [sqlite3_mutex_leave()] </li>
  6124. ** <li> [sqlite3_mutex_held()] </li>
  6125. ** <li> [sqlite3_mutex_notheld()] </li>
  6126. ** </ul>)^
  6127. **
  6128. ** The only difference is that the public sqlite3_XXX functions enumerated
  6129. ** above silently ignore any invocations that pass a NULL pointer instead
  6130. ** of a valid mutex handle. The implementations of the methods defined
  6131. ** by this structure are not required to handle this case, the results
  6132. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6133. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6134. ** it is passed a NULL pointer).
  6135. **
  6136. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  6137. ** invoke xMutexInit() multiple times within the same process and without
  6138. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6139. ** xMutexInit() must be no-ops.
  6140. **
  6141. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6142. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  6143. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6144. ** memory allocation for a fast or recursive mutex.
  6145. **
  6146. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6147. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6148. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6149. ** prior to returning.
  6150. */
  6151. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6152. struct sqlite3_mutex_methods {
  6153. int (*xMutexInit)(void);
  6154. int (*xMutexEnd)(void);
  6155. sqlite3_mutex *(*xMutexAlloc)(int);
  6156. void (*xMutexFree)(sqlite3_mutex *);
  6157. void (*xMutexEnter)(sqlite3_mutex *);
  6158. int (*xMutexTry)(sqlite3_mutex *);
  6159. void (*xMutexLeave)(sqlite3_mutex *);
  6160. int (*xMutexHeld)(sqlite3_mutex *);
  6161. int (*xMutexNotheld)(sqlite3_mutex *);
  6162. };
  6163. /*
  6164. ** CAPI3REF: Mutex Verification Routines
  6165. **
  6166. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6167. ** are intended for use inside assert() statements. ^The SQLite core
  6168. ** never uses these routines except inside an assert() and applications
  6169. ** are advised to follow the lead of the core. ^The SQLite core only
  6170. ** provides implementations for these routines when it is compiled
  6171. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  6172. ** are only required to provide these routines if SQLITE_DEBUG is
  6173. ** defined and if NDEBUG is not defined.
  6174. **
  6175. ** ^These routines should return true if the mutex in their argument
  6176. ** is held or not held, respectively, by the calling thread.
  6177. **
  6178. ** ^The implementation is not required to provide versions of these
  6179. ** routines that actually work. If the implementation does not provide working
  6180. ** versions of these routines, it should at least provide stubs that always
  6181. ** return true so that one does not get spurious assertion failures.
  6182. **
  6183. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  6184. ** the routine should return 1. This seems counter-intuitive since
  6185. ** clearly the mutex cannot be held if it does not exist. But
  6186. ** the reason the mutex does not exist is because the build is not
  6187. ** using mutexes. And we do not want the assert() containing the
  6188. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6189. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  6190. ** interface should also return 1 when given a NULL pointer.
  6191. */
  6192. #ifndef NDEBUG
  6193. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6194. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6195. #endif
  6196. /*
  6197. ** CAPI3REF: Mutex Types
  6198. **
  6199. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6200. ** which is one of these integer constants.
  6201. **
  6202. ** The set of static mutexes may change from one SQLite release to the
  6203. ** next. Applications that override the built-in mutex logic must be
  6204. ** prepared to accommodate additional static mutexes.
  6205. */
  6206. #define SQLITE_MUTEX_FAST 0
  6207. #define SQLITE_MUTEX_RECURSIVE 1
  6208. #define SQLITE_MUTEX_STATIC_MASTER 2
  6209. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6210. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6211. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6212. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6213. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6214. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6215. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6216. /*
  6217. ** CAPI3REF: Retrieve the mutex for a database connection
  6218. **
  6219. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6220. ** serializes access to the [database connection] given in the argument
  6221. ** when the [threading mode] is Serialized.
  6222. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6223. ** routine returns a NULL pointer.
  6224. */
  6225. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6226. /*
  6227. ** CAPI3REF: Low-Level Control Of Database Files
  6228. **
  6229. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6230. ** xFileControl method for the [sqlite3_io_methods] object associated
  6231. ** with a particular database identified by the second argument. ^The
  6232. ** name of the database is "main" for the main database or "temp" for the
  6233. ** TEMP database, or the name that appears after the AS keyword for
  6234. ** databases that are added using the [ATTACH] SQL command.
  6235. ** ^A NULL pointer can be used in place of "main" to refer to the
  6236. ** main database file.
  6237. ** ^The third and fourth parameters to this routine
  6238. ** are passed directly through to the second and third parameters of
  6239. ** the xFileControl method. ^The return value of the xFileControl
  6240. ** method becomes the return value of this routine.
  6241. **
  6242. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6243. ** a pointer to the underlying [sqlite3_file] object to be written into
  6244. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6245. ** case is a short-circuit path which does not actually invoke the
  6246. ** underlying sqlite3_io_methods.xFileControl method.
  6247. **
  6248. ** ^If the second parameter (zDbName) does not match the name of any
  6249. ** open database file, then SQLITE_ERROR is returned. ^This error
  6250. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6251. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6252. ** also return SQLITE_ERROR. There is no way to distinguish between
  6253. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6254. ** xFileControl method.
  6255. **
  6256. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6257. */
  6258. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6259. /*
  6260. ** CAPI3REF: Testing Interface
  6261. **
  6262. ** ^The sqlite3_test_control() interface is used to read out internal
  6263. ** state of SQLite and to inject faults into SQLite for testing
  6264. ** purposes. ^The first parameter is an operation code that determines
  6265. ** the number, meaning, and operation of all subsequent parameters.
  6266. **
  6267. ** This interface is not for use by applications. It exists solely
  6268. ** for verifying the correct operation of the SQLite library. Depending
  6269. ** on how the SQLite library is compiled, this interface might not exist.
  6270. **
  6271. ** The details of the operation codes, their meanings, the parameters
  6272. ** they take, and what they do are all subject to change without notice.
  6273. ** Unlike most of the SQLite API, this function is not guaranteed to
  6274. ** operate consistently from one release to the next.
  6275. */
  6276. SQLITE_API int sqlite3_test_control(int op, ...);
  6277. /*
  6278. ** CAPI3REF: Testing Interface Operation Codes
  6279. **
  6280. ** These constants are the valid operation code parameters used
  6281. ** as the first argument to [sqlite3_test_control()].
  6282. **
  6283. ** These parameters and their meanings are subject to change
  6284. ** without notice. These values are for testing purposes only.
  6285. ** Applications should not use any of these parameters or the
  6286. ** [sqlite3_test_control()] interface.
  6287. */
  6288. #define SQLITE_TESTCTRL_FIRST 5
  6289. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6290. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6291. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6292. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6293. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6294. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6295. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6296. #define SQLITE_TESTCTRL_ASSERT 12
  6297. #define SQLITE_TESTCTRL_ALWAYS 13
  6298. #define SQLITE_TESTCTRL_RESERVE 14
  6299. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6300. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6301. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6302. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6303. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  6304. #define SQLITE_TESTCTRL_LAST 19
  6305. /*
  6306. ** CAPI3REF: SQLite Runtime Status
  6307. **
  6308. ** ^This interface is used to retrieve runtime status information
  6309. ** about the performance of SQLite, and optionally to reset various
  6310. ** highwater marks. ^The first argument is an integer code for
  6311. ** the specific parameter to measure. ^(Recognized integer codes
  6312. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6313. ** ^The current value of the parameter is returned into *pCurrent.
  6314. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6315. ** resetFlag is true, then the highest record value is reset after
  6316. ** *pHighwater is written. ^(Some parameters do not record the highest
  6317. ** value. For those parameters
  6318. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6319. ** ^(Other parameters record only the highwater mark and not the current
  6320. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6321. **
  6322. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  6323. ** non-zero [error code] on failure.
  6324. **
  6325. ** This routine is threadsafe but is not atomic. This routine can be
  6326. ** called while other threads are running the same or different SQLite
  6327. ** interfaces. However the values returned in *pCurrent and
  6328. ** *pHighwater reflect the status of SQLite at different points in time
  6329. ** and it is possible that another thread might change the parameter
  6330. ** in between the times when *pCurrent and *pHighwater are written.
  6331. **
  6332. ** See also: [sqlite3_db_status()]
  6333. */
  6334. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6335. /*
  6336. ** CAPI3REF: Status Parameters
  6337. ** KEYWORDS: {status parameters}
  6338. **
  6339. ** These integer constants designate various run-time status parameters
  6340. ** that can be returned by [sqlite3_status()].
  6341. **
  6342. ** <dl>
  6343. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6344. ** <dd>This parameter is the current amount of memory checked out
  6345. ** using [sqlite3_malloc()], either directly or indirectly. The
  6346. ** figure includes calls made to [sqlite3_malloc()] by the application
  6347. ** and internal memory usage by the SQLite library. Scratch memory
  6348. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6349. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6350. ** this parameter. The amount returned is the sum of the allocation
  6351. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6352. **
  6353. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6354. ** <dd>This parameter records the largest memory allocation request
  6355. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6356. ** internal equivalents). Only the value returned in the
  6357. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6358. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6359. **
  6360. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6361. ** <dd>This parameter records the number of separate memory allocations
  6362. ** currently checked out.</dd>)^
  6363. **
  6364. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6365. ** <dd>This parameter returns the number of pages used out of the
  6366. ** [pagecache memory allocator] that was configured using
  6367. ** [SQLITE_CONFIG_PAGECACHE]. The
  6368. ** value returned is in pages, not in bytes.</dd>)^
  6369. **
  6370. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6371. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6372. ** <dd>This parameter returns the number of bytes of page cache
  6373. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6374. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6375. ** returned value includes allocations that overflowed because they
  6376. ** where too large (they were larger than the "sz" parameter to
  6377. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6378. ** no space was left in the page cache.</dd>)^
  6379. **
  6380. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6381. ** <dd>This parameter records the largest memory allocation request
  6382. ** handed to [pagecache memory allocator]. Only the value returned in the
  6383. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6384. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6385. **
  6386. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6387. ** <dd>This parameter returns the number of allocations used out of the
  6388. ** [scratch memory allocator] configured using
  6389. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6390. ** in bytes. Since a single thread may only have one scratch allocation
  6391. ** outstanding at time, this parameter also reports the number of threads
  6392. ** using scratch memory at the same time.</dd>)^
  6393. **
  6394. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6395. ** <dd>This parameter returns the number of bytes of scratch memory
  6396. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6397. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6398. ** returned include overflows because the requested allocation was too
  6399. ** larger (that is, because the requested allocation was larger than the
  6400. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6401. ** slots were available.
  6402. ** </dd>)^
  6403. **
  6404. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6405. ** <dd>This parameter records the largest memory allocation request
  6406. ** handed to [scratch memory allocator]. Only the value returned in the
  6407. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6408. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6409. **
  6410. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6411. ** <dd>This parameter records the deepest parser stack. It is only
  6412. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6413. ** </dl>
  6414. **
  6415. ** New status parameters may be added from time to time.
  6416. */
  6417. #define SQLITE_STATUS_MEMORY_USED 0
  6418. #define SQLITE_STATUS_PAGECACHE_USED 1
  6419. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6420. #define SQLITE_STATUS_SCRATCH_USED 3
  6421. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6422. #define SQLITE_STATUS_MALLOC_SIZE 5
  6423. #define SQLITE_STATUS_PARSER_STACK 6
  6424. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6425. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6426. #define SQLITE_STATUS_MALLOC_COUNT 9
  6427. /*
  6428. ** CAPI3REF: Database Connection Status
  6429. **
  6430. ** ^This interface is used to retrieve runtime status information
  6431. ** about a single [database connection]. ^The first argument is the
  6432. ** database connection object to be interrogated. ^The second argument
  6433. ** is an integer constant, taken from the set of
  6434. ** [SQLITE_DBSTATUS options], that
  6435. ** determines the parameter to interrogate. The set of
  6436. ** [SQLITE_DBSTATUS options] is likely
  6437. ** to grow in future releases of SQLite.
  6438. **
  6439. ** ^The current value of the requested parameter is written into *pCur
  6440. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6441. ** the resetFlg is true, then the highest instantaneous value is
  6442. ** reset back down to the current value.
  6443. **
  6444. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6445. ** non-zero [error code] on failure.
  6446. **
  6447. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6448. */
  6449. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6450. /*
  6451. ** CAPI3REF: Status Parameters for database connections
  6452. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6453. **
  6454. ** These constants are the available integer "verbs" that can be passed as
  6455. ** the second argument to the [sqlite3_db_status()] interface.
  6456. **
  6457. ** New verbs may be added in future releases of SQLite. Existing verbs
  6458. ** might be discontinued. Applications should check the return code from
  6459. ** [sqlite3_db_status()] to make sure that the call worked.
  6460. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6461. ** if a discontinued or unsupported verb is invoked.
  6462. **
  6463. ** <dl>
  6464. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6465. ** <dd>This parameter returns the number of lookaside memory slots currently
  6466. ** checked out.</dd>)^
  6467. **
  6468. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6469. ** <dd>This parameter returns the number malloc attempts that were
  6470. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6471. ** the current value is always zero.)^
  6472. **
  6473. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6474. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6475. ** <dd>This parameter returns the number malloc attempts that might have
  6476. ** been satisfied using lookaside memory but failed due to the amount of
  6477. ** memory requested being larger than the lookaside slot size.
  6478. ** Only the high-water value is meaningful;
  6479. ** the current value is always zero.)^
  6480. **
  6481. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6482. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6483. ** <dd>This parameter returns the number malloc attempts that might have
  6484. ** been satisfied using lookaside memory but failed due to all lookaside
  6485. ** memory already being in use.
  6486. ** Only the high-water value is meaningful;
  6487. ** the current value is always zero.)^
  6488. **
  6489. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6490. ** <dd>This parameter returns the approximate number of of bytes of heap
  6491. ** memory used by all pager caches associated with the database connection.)^
  6492. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6493. **
  6494. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6495. ** <dd>This parameter returns the approximate number of of bytes of heap
  6496. ** memory used to store the schema for all databases associated
  6497. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6498. ** ^The full amount of memory used by the schemas is reported, even if the
  6499. ** schema memory is shared with other database connections due to
  6500. ** [shared cache mode] being enabled.
  6501. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6502. **
  6503. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6504. ** <dd>This parameter returns the approximate number of of bytes of heap
  6505. ** and lookaside memory used by all prepared statements associated with
  6506. ** the database connection.)^
  6507. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6508. ** </dd>
  6509. **
  6510. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6511. ** <dd>This parameter returns the number of pager cache hits that have
  6512. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6513. ** is always 0.
  6514. ** </dd>
  6515. **
  6516. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6517. ** <dd>This parameter returns the number of pager cache misses that have
  6518. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6519. ** is always 0.
  6520. ** </dd>
  6521. **
  6522. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6523. ** <dd>This parameter returns the number of dirty cache entries that have
  6524. ** been written to disk. Specifically, the number of pages written to the
  6525. ** wal file in wal mode databases, or the number of pages written to the
  6526. ** database file in rollback mode databases. Any pages written as part of
  6527. ** transaction rollback or database recovery operations are not included.
  6528. ** If an IO or other error occurs while writing a page to disk, the effect
  6529. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6530. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6531. ** </dd>
  6532. ** </dl>
  6533. */
  6534. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6535. #define SQLITE_DBSTATUS_CACHE_USED 1
  6536. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6537. #define SQLITE_DBSTATUS_STMT_USED 3
  6538. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6539. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6540. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6541. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6542. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6543. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6544. #define SQLITE_DBSTATUS_MAX 9 /* Largest defined DBSTATUS */
  6545. /*
  6546. ** CAPI3REF: Prepared Statement Status
  6547. **
  6548. ** ^(Each prepared statement maintains various
  6549. ** [SQLITE_STMTSTATUS counters] that measure the number
  6550. ** of times it has performed specific operations.)^ These counters can
  6551. ** be used to monitor the performance characteristics of the prepared
  6552. ** statements. For example, if the number of table steps greatly exceeds
  6553. ** the number of table searches or result rows, that would tend to indicate
  6554. ** that the prepared statement is using a full table scan rather than
  6555. ** an index.
  6556. **
  6557. ** ^(This interface is used to retrieve and reset counter values from
  6558. ** a [prepared statement]. The first argument is the prepared statement
  6559. ** object to be interrogated. The second argument
  6560. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6561. ** to be interrogated.)^
  6562. ** ^The current value of the requested counter is returned.
  6563. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6564. ** interface call returns.
  6565. **
  6566. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6567. */
  6568. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6569. /*
  6570. ** CAPI3REF: Status Parameters for prepared statements
  6571. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6572. **
  6573. ** These preprocessor macros define integer codes that name counter
  6574. ** values associated with the [sqlite3_stmt_status()] interface.
  6575. ** The meanings of the various counters are as follows:
  6576. **
  6577. ** <dl>
  6578. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6579. ** <dd>^This is the number of times that SQLite has stepped forward in
  6580. ** a table as part of a full table scan. Large numbers for this counter
  6581. ** may indicate opportunities for performance improvement through
  6582. ** careful use of indices.</dd>
  6583. **
  6584. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6585. ** <dd>^This is the number of sort operations that have occurred.
  6586. ** A non-zero value in this counter may indicate an opportunity to
  6587. ** improvement performance through careful use of indices.</dd>
  6588. **
  6589. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6590. ** <dd>^This is the number of rows inserted into transient indices that
  6591. ** were created automatically in order to help joins run faster.
  6592. ** A non-zero value in this counter may indicate an opportunity to
  6593. ** improvement performance by adding permanent indices that do not
  6594. ** need to be reinitialized each time the statement is run.</dd>
  6595. ** </dl>
  6596. */
  6597. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6598. #define SQLITE_STMTSTATUS_SORT 2
  6599. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6600. /*
  6601. ** CAPI3REF: Custom Page Cache Object
  6602. **
  6603. ** The sqlite3_pcache type is opaque. It is implemented by
  6604. ** the pluggable module. The SQLite core has no knowledge of
  6605. ** its size or internal structure and never deals with the
  6606. ** sqlite3_pcache object except by holding and passing pointers
  6607. ** to the object.
  6608. **
  6609. ** See [sqlite3_pcache_methods2] for additional information.
  6610. */
  6611. typedef struct sqlite3_pcache sqlite3_pcache;
  6612. /*
  6613. ** CAPI3REF: Custom Page Cache Object
  6614. **
  6615. ** The sqlite3_pcache_page object represents a single page in the
  6616. ** page cache. The page cache will allocate instances of this
  6617. ** object. Various methods of the page cache use pointers to instances
  6618. ** of this object as parameters or as their return value.
  6619. **
  6620. ** See [sqlite3_pcache_methods2] for additional information.
  6621. */
  6622. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6623. struct sqlite3_pcache_page {
  6624. void *pBuf; /* The content of the page */
  6625. void *pExtra; /* Extra information associated with the page */
  6626. };
  6627. /*
  6628. ** CAPI3REF: Application Defined Page Cache.
  6629. ** KEYWORDS: {page cache}
  6630. **
  6631. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6632. ** register an alternative page cache implementation by passing in an
  6633. ** instance of the sqlite3_pcache_methods2 structure.)^
  6634. ** In many applications, most of the heap memory allocated by
  6635. ** SQLite is used for the page cache.
  6636. ** By implementing a
  6637. ** custom page cache using this API, an application can better control
  6638. ** the amount of memory consumed by SQLite, the way in which
  6639. ** that memory is allocated and released, and the policies used to
  6640. ** determine exactly which parts of a database file are cached and for
  6641. ** how long.
  6642. **
  6643. ** The alternative page cache mechanism is an
  6644. ** extreme measure that is only needed by the most demanding applications.
  6645. ** The built-in page cache is recommended for most uses.
  6646. **
  6647. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6648. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6649. ** the application may discard the parameter after the call to
  6650. ** [sqlite3_config()] returns.)^
  6651. **
  6652. ** [[the xInit() page cache method]]
  6653. ** ^(The xInit() method is called once for each effective
  6654. ** call to [sqlite3_initialize()])^
  6655. ** (usually only once during the lifetime of the process). ^(The xInit()
  6656. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6657. ** The intent of the xInit() method is to set up global data structures
  6658. ** required by the custom page cache implementation.
  6659. ** ^(If the xInit() method is NULL, then the
  6660. ** built-in default page cache is used instead of the application defined
  6661. ** page cache.)^
  6662. **
  6663. ** [[the xShutdown() page cache method]]
  6664. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6665. ** It can be used to clean up
  6666. ** any outstanding resources before process shutdown, if required.
  6667. ** ^The xShutdown() method may be NULL.
  6668. **
  6669. ** ^SQLite automatically serializes calls to the xInit method,
  6670. ** so the xInit method need not be threadsafe. ^The
  6671. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6672. ** not need to be threadsafe either. All other methods must be threadsafe
  6673. ** in multithreaded applications.
  6674. **
  6675. ** ^SQLite will never invoke xInit() more than once without an intervening
  6676. ** call to xShutdown().
  6677. **
  6678. ** [[the xCreate() page cache methods]]
  6679. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6680. ** SQLite will typically create one cache instance for each open database file,
  6681. ** though this is not guaranteed. ^The
  6682. ** first parameter, szPage, is the size in bytes of the pages that must
  6683. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6684. ** second parameter szExtra is a number of bytes of extra storage
  6685. ** associated with each page cache entry. ^The szExtra parameter will
  6686. ** a number less than 250. SQLite will use the
  6687. ** extra szExtra bytes on each page to store metadata about the underlying
  6688. ** database page on disk. The value passed into szExtra depends
  6689. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6690. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6691. ** created will be used to cache database pages of a file stored on disk, or
  6692. ** false if it is used for an in-memory database. The cache implementation
  6693. ** does not have to do anything special based with the value of bPurgeable;
  6694. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6695. ** never invoke xUnpin() except to deliberately delete a page.
  6696. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6697. ** false will always have the "discard" flag set to true.
  6698. ** ^Hence, a cache created with bPurgeable false will
  6699. ** never contain any unpinned pages.
  6700. **
  6701. ** [[the xCachesize() page cache method]]
  6702. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6703. ** suggested maximum cache-size (number of pages stored by) the cache
  6704. ** instance passed as the first argument. This is the value configured using
  6705. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6706. ** parameter, the implementation is not required to do anything with this
  6707. ** value; it is advisory only.
  6708. **
  6709. ** [[the xPagecount() page cache methods]]
  6710. ** The xPagecount() method must return the number of pages currently
  6711. ** stored in the cache, both pinned and unpinned.
  6712. **
  6713. ** [[the xFetch() page cache methods]]
  6714. ** The xFetch() method locates a page in the cache and returns a pointer to
  6715. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6716. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6717. ** pointer to a buffer of szPage bytes used to store the content of a
  6718. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6719. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6720. ** for each entry in the page cache.
  6721. **
  6722. ** The page to be fetched is determined by the key. ^The minimum key value
  6723. ** is 1. After it has been retrieved using xFetch, the page is considered
  6724. ** to be "pinned".
  6725. **
  6726. ** If the requested page is already in the page cache, then the page cache
  6727. ** implementation must return a pointer to the page buffer with its content
  6728. ** intact. If the requested page is not already in the cache, then the
  6729. ** cache implementation should use the value of the createFlag
  6730. ** parameter to help it determined what action to take:
  6731. **
  6732. ** <table border=1 width=85% align=center>
  6733. ** <tr><th> createFlag <th> Behaviour when page is not already in cache
  6734. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6735. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6736. ** Otherwise return NULL.
  6737. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6738. ** NULL if allocating a new page is effectively impossible.
  6739. ** </table>
  6740. **
  6741. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6742. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6743. ** failed.)^ In between the to xFetch() calls, SQLite may
  6744. ** attempt to unpin one or more cache pages by spilling the content of
  6745. ** pinned pages to disk and synching the operating system disk cache.
  6746. **
  6747. ** [[the xUnpin() page cache method]]
  6748. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6749. ** as its second argument. If the third parameter, discard, is non-zero,
  6750. ** then the page must be evicted from the cache.
  6751. ** ^If the discard parameter is
  6752. ** zero, then the page may be discarded or retained at the discretion of
  6753. ** page cache implementation. ^The page cache implementation
  6754. ** may choose to evict unpinned pages at any time.
  6755. **
  6756. ** The cache must not perform any reference counting. A single
  6757. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6758. ** to xFetch().
  6759. **
  6760. ** [[the xRekey() page cache methods]]
  6761. ** The xRekey() method is used to change the key value associated with the
  6762. ** page passed as the second argument. If the cache
  6763. ** previously contains an entry associated with newKey, it must be
  6764. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6765. ** to be pinned.
  6766. **
  6767. ** When SQLite calls the xTruncate() method, the cache must discard all
  6768. ** existing cache entries with page numbers (keys) greater than or equal
  6769. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6770. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6771. ** they can be safely discarded.
  6772. **
  6773. ** [[the xDestroy() page cache method]]
  6774. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6775. ** All resources associated with the specified cache should be freed. ^After
  6776. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6777. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6778. ** functions.
  6779. **
  6780. ** [[the xShrink() page cache method]]
  6781. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6782. ** free up as much of heap memory as possible. The page cache implementation
  6783. ** is not obligated to free any memory, but well-behaved implementations should
  6784. ** do their best.
  6785. */
  6786. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6787. struct sqlite3_pcache_methods2 {
  6788. int iVersion;
  6789. void *pArg;
  6790. int (*xInit)(void*);
  6791. void (*xShutdown)(void*);
  6792. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6793. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6794. int (*xPagecount)(sqlite3_pcache*);
  6795. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6796. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6797. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6798. unsigned oldKey, unsigned newKey);
  6799. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6800. void (*xDestroy)(sqlite3_pcache*);
  6801. void (*xShrink)(sqlite3_pcache*);
  6802. };
  6803. /*
  6804. ** This is the obsolete pcache_methods object that has now been replaced
  6805. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6806. ** retained in the header file for backwards compatibility only.
  6807. */
  6808. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6809. struct sqlite3_pcache_methods {
  6810. void *pArg;
  6811. int (*xInit)(void*);
  6812. void (*xShutdown)(void*);
  6813. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6814. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6815. int (*xPagecount)(sqlite3_pcache*);
  6816. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6817. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6818. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6819. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6820. void (*xDestroy)(sqlite3_pcache*);
  6821. };
  6822. /*
  6823. ** CAPI3REF: Online Backup Object
  6824. **
  6825. ** The sqlite3_backup object records state information about an ongoing
  6826. ** online backup operation. ^The sqlite3_backup object is created by
  6827. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6828. ** [sqlite3_backup_finish()].
  6829. **
  6830. ** See Also: [Using the SQLite Online Backup API]
  6831. */
  6832. typedef struct sqlite3_backup sqlite3_backup;
  6833. /*
  6834. ** CAPI3REF: Online Backup API.
  6835. **
  6836. ** The backup API copies the content of one database into another.
  6837. ** It is useful either for creating backups of databases or
  6838. ** for copying in-memory databases to or from persistent files.
  6839. **
  6840. ** See Also: [Using the SQLite Online Backup API]
  6841. **
  6842. ** ^SQLite holds a write transaction open on the destination database file
  6843. ** for the duration of the backup operation.
  6844. ** ^The source database is read-locked only while it is being read;
  6845. ** it is not locked continuously for the entire backup operation.
  6846. ** ^Thus, the backup may be performed on a live source database without
  6847. ** preventing other database connections from
  6848. ** reading or writing to the source database while the backup is underway.
  6849. **
  6850. ** ^(To perform a backup operation:
  6851. ** <ol>
  6852. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6853. ** backup,
  6854. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6855. ** the data between the two databases, and finally
  6856. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6857. ** associated with the backup operation.
  6858. ** </ol>)^
  6859. ** There should be exactly one call to sqlite3_backup_finish() for each
  6860. ** successful call to sqlite3_backup_init().
  6861. **
  6862. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6863. **
  6864. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6865. ** [database connection] associated with the destination database
  6866. ** and the database name, respectively.
  6867. ** ^The database name is "main" for the main database, "temp" for the
  6868. ** temporary database, or the name specified after the AS keyword in
  6869. ** an [ATTACH] statement for an attached database.
  6870. ** ^The S and M arguments passed to
  6871. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6872. ** and database name of the source database, respectively.
  6873. ** ^The source and destination [database connections] (parameters S and D)
  6874. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6875. ** an error.
  6876. **
  6877. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6878. ** returned and an error code and error message are stored in the
  6879. ** destination [database connection] D.
  6880. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6881. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6882. ** [sqlite3_errmsg16()] functions.
  6883. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6884. ** [sqlite3_backup] object.
  6885. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6886. ** sqlite3_backup_finish() functions to perform the specified backup
  6887. ** operation.
  6888. **
  6889. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6890. **
  6891. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6892. ** the source and destination databases specified by [sqlite3_backup] object B.
  6893. ** ^If N is negative, all remaining source pages are copied.
  6894. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6895. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6896. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6897. ** from source to destination, then it returns [SQLITE_DONE].
  6898. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6899. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6900. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6901. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6902. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6903. **
  6904. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6905. ** <ol>
  6906. ** <li> the destination database was opened read-only, or
  6907. ** <li> the destination database is using write-ahead-log journaling
  6908. ** and the destination and source page sizes differ, or
  6909. ** <li> the destination database is an in-memory database and the
  6910. ** destination and source page sizes differ.
  6911. ** </ol>)^
  6912. **
  6913. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6914. ** the [sqlite3_busy_handler | busy-handler function]
  6915. ** is invoked (if one is specified). ^If the
  6916. ** busy-handler returns non-zero before the lock is available, then
  6917. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6918. ** sqlite3_backup_step() can be retried later. ^If the source
  6919. ** [database connection]
  6920. ** is being used to write to the source database when sqlite3_backup_step()
  6921. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6922. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6923. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6924. ** [SQLITE_READONLY] is returned, then
  6925. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6926. ** errors are considered fatal.)^ The application must accept
  6927. ** that the backup operation has failed and pass the backup operation handle
  6928. ** to the sqlite3_backup_finish() to release associated resources.
  6929. **
  6930. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6931. ** on the destination file. ^The exclusive lock is not released until either
  6932. ** sqlite3_backup_finish() is called or the backup operation is complete
  6933. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6934. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6935. ** lasts for the duration of the sqlite3_backup_step() call.
  6936. ** ^Because the source database is not locked between calls to
  6937. ** sqlite3_backup_step(), the source database may be modified mid-way
  6938. ** through the backup process. ^If the source database is modified by an
  6939. ** external process or via a database connection other than the one being
  6940. ** used by the backup operation, then the backup will be automatically
  6941. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6942. ** database is modified by the using the same database connection as is used
  6943. ** by the backup operation, then the backup database is automatically
  6944. ** updated at the same time.
  6945. **
  6946. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6947. **
  6948. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6949. ** application wishes to abandon the backup operation, the application
  6950. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6951. ** ^The sqlite3_backup_finish() interfaces releases all
  6952. ** resources associated with the [sqlite3_backup] object.
  6953. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6954. ** active write-transaction on the destination database is rolled back.
  6955. ** The [sqlite3_backup] object is invalid
  6956. ** and may not be used following a call to sqlite3_backup_finish().
  6957. **
  6958. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6959. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6960. ** sqlite3_backup_step() completed.
  6961. ** ^If an out-of-memory condition or IO error occurred during any prior
  6962. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6963. ** sqlite3_backup_finish() returns the corresponding [error code].
  6964. **
  6965. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6966. ** is not a permanent error and does not affect the return value of
  6967. ** sqlite3_backup_finish().
  6968. **
  6969. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6970. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6971. **
  6972. ** ^Each call to sqlite3_backup_step() sets two values inside
  6973. ** the [sqlite3_backup] object: the number of pages still to be backed
  6974. ** up and the total number of pages in the source database file.
  6975. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6976. ** retrieve these two values, respectively.
  6977. **
  6978. ** ^The values returned by these functions are only updated by
  6979. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6980. ** operation, then the values are not updated to account for any extra
  6981. ** pages that need to be updated or the size of the source database file
  6982. ** changing.
  6983. **
  6984. ** <b>Concurrent Usage of Database Handles</b>
  6985. **
  6986. ** ^The source [database connection] may be used by the application for other
  6987. ** purposes while a backup operation is underway or being initialized.
  6988. ** ^If SQLite is compiled and configured to support threadsafe database
  6989. ** connections, then the source database connection may be used concurrently
  6990. ** from within other threads.
  6991. **
  6992. ** However, the application must guarantee that the destination
  6993. ** [database connection] is not passed to any other API (by any thread) after
  6994. ** sqlite3_backup_init() is called and before the corresponding call to
  6995. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6996. ** if the application incorrectly accesses the destination [database connection]
  6997. ** and so no error code is reported, but the operations may malfunction
  6998. ** nevertheless. Use of the destination database connection while a
  6999. ** backup is in progress might also also cause a mutex deadlock.
  7000. **
  7001. ** If running in [shared cache mode], the application must
  7002. ** guarantee that the shared cache used by the destination database
  7003. ** is not accessed while the backup is running. In practice this means
  7004. ** that the application must guarantee that the disk file being
  7005. ** backed up to is not accessed by any connection within the process,
  7006. ** not just the specific connection that was passed to sqlite3_backup_init().
  7007. **
  7008. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7009. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7010. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7011. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7012. ** same time as another thread is invoking sqlite3_backup_step() it is
  7013. ** possible that they return invalid values.
  7014. */
  7015. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  7016. sqlite3 *pDest, /* Destination database handle */
  7017. const char *zDestName, /* Destination database name */
  7018. sqlite3 *pSource, /* Source database handle */
  7019. const char *zSourceName /* Source database name */
  7020. );
  7021. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7022. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  7023. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  7024. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  7025. /*
  7026. ** CAPI3REF: Unlock Notification
  7027. **
  7028. ** ^When running in shared-cache mode, a database operation may fail with
  7029. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7030. ** individual tables within the shared-cache cannot be obtained. See
  7031. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7032. ** ^This API may be used to register a callback that SQLite will invoke
  7033. ** when the connection currently holding the required lock relinquishes it.
  7034. ** ^This API is only available if the library was compiled with the
  7035. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7036. **
  7037. ** See Also: [Using the SQLite Unlock Notification Feature].
  7038. **
  7039. ** ^Shared-cache locks are released when a database connection concludes
  7040. ** its current transaction, either by committing it or rolling it back.
  7041. **
  7042. ** ^When a connection (known as the blocked connection) fails to obtain a
  7043. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7044. ** identity of the database connection (the blocking connection) that
  7045. ** has locked the required resource is stored internally. ^After an
  7046. ** application receives an SQLITE_LOCKED error, it may call the
  7047. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7048. ** the first argument to register for a callback that will be invoked
  7049. ** when the blocking connections current transaction is concluded. ^The
  7050. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7051. ** call that concludes the blocking connections transaction.
  7052. **
  7053. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7054. ** there is a chance that the blocking connection will have already
  7055. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7056. ** If this happens, then the specified callback is invoked immediately,
  7057. ** from within the call to sqlite3_unlock_notify().)^
  7058. **
  7059. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7060. ** shared-cache table, and more than one other connection currently holds
  7061. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7062. ** the other connections to use as the blocking connection.
  7063. **
  7064. ** ^(There may be at most one unlock-notify callback registered by a
  7065. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7066. ** blocked connection already has a registered unlock-notify callback,
  7067. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7068. ** called with a NULL pointer as its second argument, then any existing
  7069. ** unlock-notify callback is canceled. ^The blocked connections
  7070. ** unlock-notify callback may also be canceled by closing the blocked
  7071. ** connection using [sqlite3_close()].
  7072. **
  7073. ** The unlock-notify callback is not reentrant. If an application invokes
  7074. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7075. ** crash or deadlock may be the result.
  7076. **
  7077. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7078. ** returns SQLITE_OK.
  7079. **
  7080. ** <b>Callback Invocation Details</b>
  7081. **
  7082. ** When an unlock-notify callback is registered, the application provides a
  7083. ** single void* pointer that is passed to the callback when it is invoked.
  7084. ** However, the signature of the callback function allows SQLite to pass
  7085. ** it an array of void* context pointers. The first argument passed to
  7086. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7087. ** and the second is the number of entries in the array.
  7088. **
  7089. ** When a blocking connections transaction is concluded, there may be
  7090. ** more than one blocked connection that has registered for an unlock-notify
  7091. ** callback. ^If two or more such blocked connections have specified the
  7092. ** same callback function, then instead of invoking the callback function
  7093. ** multiple times, it is invoked once with the set of void* context pointers
  7094. ** specified by the blocked connections bundled together into an array.
  7095. ** This gives the application an opportunity to prioritize any actions
  7096. ** related to the set of unblocked database connections.
  7097. **
  7098. ** <b>Deadlock Detection</b>
  7099. **
  7100. ** Assuming that after registering for an unlock-notify callback a
  7101. ** database waits for the callback to be issued before taking any further
  7102. ** action (a reasonable assumption), then using this API may cause the
  7103. ** application to deadlock. For example, if connection X is waiting for
  7104. ** connection Y's transaction to be concluded, and similarly connection
  7105. ** Y is waiting on connection X's transaction, then neither connection
  7106. ** will proceed and the system may remain deadlocked indefinitely.
  7107. **
  7108. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7109. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7110. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7111. ** unlock-notify callback is registered. The system is said to be in
  7112. ** a deadlocked state if connection A has registered for an unlock-notify
  7113. ** callback on the conclusion of connection B's transaction, and connection
  7114. ** B has itself registered for an unlock-notify callback when connection
  7115. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7116. ** the system is also considered to be deadlocked if connection B has
  7117. ** registered for an unlock-notify callback on the conclusion of connection
  7118. ** C's transaction, where connection C is waiting on connection A. ^Any
  7119. ** number of levels of indirection are allowed.
  7120. **
  7121. ** <b>The "DROP TABLE" Exception</b>
  7122. **
  7123. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7124. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7125. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7126. ** SQLite checks if there are any currently executing SELECT statements
  7127. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7128. ** returned. In this case there is no "blocking connection", so invoking
  7129. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7130. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7131. ** or "DROP INDEX" query, an infinite loop might be the result.
  7132. **
  7133. ** One way around this problem is to check the extended error code returned
  7134. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7135. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7136. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7137. ** SQLITE_LOCKED.)^
  7138. */
  7139. SQLITE_API int sqlite3_unlock_notify(
  7140. sqlite3 *pBlocked, /* Waiting connection */
  7141. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7142. void *pNotifyArg /* Argument to pass to xNotify */
  7143. );
  7144. /*
  7145. ** CAPI3REF: String Comparison
  7146. **
  7147. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7148. ** and extensions to compare the contents of two buffers containing UTF-8
  7149. ** strings in a case-independent fashion, using the same definition of "case
  7150. ** independence" that SQLite uses internally when comparing identifiers.
  7151. */
  7152. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7153. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7154. /*
  7155. ** CAPI3REF: Error Logging Interface
  7156. **
  7157. ** ^The [sqlite3_log()] interface writes a message into the error log
  7158. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7159. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7160. ** used with [sqlite3_snprintf()] to generate the final output string.
  7161. **
  7162. ** The sqlite3_log() interface is intended for use by extensions such as
  7163. ** virtual tables, collating functions, and SQL functions. While there is
  7164. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7165. ** is considered bad form.
  7166. **
  7167. ** The zFormat string must not be NULL.
  7168. **
  7169. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7170. ** will not use dynamically allocated memory. The log message is stored in
  7171. ** a fixed-length buffer on the stack. If the log message is longer than
  7172. ** a few hundred characters, it will be truncated to the length of the
  7173. ** buffer.
  7174. */
  7175. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7176. /*
  7177. ** CAPI3REF: Write-Ahead Log Commit Hook
  7178. **
  7179. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7180. ** will be invoked each time a database connection commits data to a
  7181. ** [write-ahead log] (i.e. whenever a transaction is committed in
  7182. ** [journal_mode | journal_mode=WAL mode]).
  7183. **
  7184. ** ^The callback is invoked by SQLite after the commit has taken place and
  7185. ** the associated write-lock on the database released, so the implementation
  7186. ** may read, write or [checkpoint] the database as required.
  7187. **
  7188. ** ^The first parameter passed to the callback function when it is invoked
  7189. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7190. ** registering the callback. ^The second is a copy of the database handle.
  7191. ** ^The third parameter is the name of the database that was written to -
  7192. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7193. ** is the number of pages currently in the write-ahead log file,
  7194. ** including those that were just committed.
  7195. **
  7196. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7197. ** code is returned, that error will propagate back up through the
  7198. ** SQLite code base to cause the statement that provoked the callback
  7199. ** to report an error, though the commit will have still occurred. If the
  7200. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7201. ** that does not correspond to any valid SQLite error code, the results
  7202. ** are undefined.
  7203. **
  7204. ** A single database handle may have at most a single write-ahead log callback
  7205. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7206. ** previously registered write-ahead log callback. ^Note that the
  7207. ** [sqlite3_wal_autocheckpoint()] interface and the
  7208. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7209. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7210. */
  7211. SQLITE_API void *sqlite3_wal_hook(
  7212. sqlite3*,
  7213. int(*)(void *,sqlite3*,const char*,int),
  7214. void*
  7215. );
  7216. /*
  7217. ** CAPI3REF: Configure an auto-checkpoint
  7218. **
  7219. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7220. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7221. ** to automatically [checkpoint]
  7222. ** after committing a transaction if there are N or
  7223. ** more frames in the [write-ahead log] file. ^Passing zero or
  7224. ** a negative value as the nFrame parameter disables automatic
  7225. ** checkpoints entirely.
  7226. **
  7227. ** ^The callback registered by this function replaces any existing callback
  7228. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7229. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7230. ** configured by this function.
  7231. **
  7232. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7233. ** from SQL.
  7234. **
  7235. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7236. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7237. ** pages. The use of this interface
  7238. ** is only necessary if the default setting is found to be suboptimal
  7239. ** for a particular application.
  7240. */
  7241. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7242. /*
  7243. ** CAPI3REF: Checkpoint a database
  7244. **
  7245. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  7246. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  7247. ** empty string, then a checkpoint is run on all databases of
  7248. ** connection D. ^If the database connection D is not in
  7249. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  7250. **
  7251. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  7252. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  7253. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  7254. ** run whenever the WAL reaches a certain size threshold.
  7255. **
  7256. ** See also: [sqlite3_wal_checkpoint_v2()]
  7257. */
  7258. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7259. /*
  7260. ** CAPI3REF: Checkpoint a database
  7261. **
  7262. ** Run a checkpoint operation on WAL database zDb attached to database
  7263. ** handle db. The specific operation is determined by the value of the
  7264. ** eMode parameter:
  7265. **
  7266. ** <dl>
  7267. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7268. ** Checkpoint as many frames as possible without waiting for any database
  7269. ** readers or writers to finish. Sync the db file if all frames in the log
  7270. ** are checkpointed. This mode is the same as calling
  7271. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  7272. **
  7273. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7274. ** This mode blocks (calls the busy-handler callback) until there is no
  7275. ** database writer and all readers are reading from the most recent database
  7276. ** snapshot. It then checkpoints all frames in the log file and syncs the
  7277. ** database file. This call blocks database writers while it is running,
  7278. ** but not database readers.
  7279. **
  7280. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7281. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  7282. ** checkpointing the log file it blocks (calls the busy-handler callback)
  7283. ** until all readers are reading from the database file only. This ensures
  7284. ** that the next client to write to the database file restarts the log file
  7285. ** from the beginning. This call blocks database writers while it is running,
  7286. ** but not database readers.
  7287. ** </dl>
  7288. **
  7289. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7290. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  7291. ** the total number of checkpointed frames (including any that were already
  7292. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  7293. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  7294. ** If no values are available because of an error, they are both set to -1
  7295. ** before returning to communicate this to the caller.
  7296. **
  7297. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  7298. ** any other process is running a checkpoint operation at the same time, the
  7299. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  7300. ** busy-handler configured, it will not be invoked in this case.
  7301. **
  7302. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  7303. ** "writer" lock on the database file. If the writer lock cannot be obtained
  7304. ** immediately, and a busy-handler is configured, it is invoked and the writer
  7305. ** lock retried until either the busy-handler returns 0 or the lock is
  7306. ** successfully obtained. The busy-handler is also invoked while waiting for
  7307. ** database readers as described above. If the busy-handler returns 0 before
  7308. ** the writer lock is obtained or while waiting for database readers, the
  7309. ** checkpoint operation proceeds from that point in the same way as
  7310. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7311. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7312. **
  7313. ** If parameter zDb is NULL or points to a zero length string, then the
  7314. ** specified operation is attempted on all WAL databases. In this case the
  7315. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7316. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7317. ** attached WAL databases, the operation is still attempted on any remaining
  7318. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7319. ** error occurs while processing an attached database, processing is abandoned
  7320. ** and the error code returned to the caller immediately. If no error
  7321. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7322. ** databases, SQLITE_OK is returned.
  7323. **
  7324. ** If database zDb is the name of an attached database that is not in WAL
  7325. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7326. ** zDb is not NULL (or a zero length string) and is not the name of any
  7327. ** attached database, SQLITE_ERROR is returned to the caller.
  7328. */
  7329. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7330. sqlite3 *db, /* Database handle */
  7331. const char *zDb, /* Name of attached database (or NULL) */
  7332. int eMode, /* SQLITE_CHECKPOINT_* value */
  7333. int *pnLog, /* OUT: Size of WAL log in frames */
  7334. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7335. );
  7336. /*
  7337. ** CAPI3REF: Checkpoint operation parameters
  7338. **
  7339. ** These constants can be used as the 3rd parameter to
  7340. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7341. ** documentation for additional information about the meaning and use of
  7342. ** each of these values.
  7343. */
  7344. #define SQLITE_CHECKPOINT_PASSIVE 0
  7345. #define SQLITE_CHECKPOINT_FULL 1
  7346. #define SQLITE_CHECKPOINT_RESTART 2
  7347. /*
  7348. ** CAPI3REF: Virtual Table Interface Configuration
  7349. **
  7350. ** This function may be called by either the [xConnect] or [xCreate] method
  7351. ** of a [virtual table] implementation to configure
  7352. ** various facets of the virtual table interface.
  7353. **
  7354. ** If this interface is invoked outside the context of an xConnect or
  7355. ** xCreate virtual table method then the behavior is undefined.
  7356. **
  7357. ** At present, there is only one option that may be configured using
  7358. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7359. ** may be added in the future.
  7360. */
  7361. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7362. /*
  7363. ** CAPI3REF: Virtual Table Configuration Options
  7364. **
  7365. ** These macros define the various options to the
  7366. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7367. ** can use to customize and optimize their behavior.
  7368. **
  7369. ** <dl>
  7370. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7371. ** <dd>Calls of the form
  7372. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7373. ** where X is an integer. If X is zero, then the [virtual table] whose
  7374. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7375. ** support constraints. In this configuration (which is the default) if
  7376. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7377. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7378. ** specified as part of the users SQL statement, regardless of the actual
  7379. ** ON CONFLICT mode specified.
  7380. **
  7381. ** If X is non-zero, then the virtual table implementation guarantees
  7382. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7383. ** any modifications to internal or persistent data structures have been made.
  7384. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7385. ** is able to roll back a statement or database transaction, and abandon
  7386. ** or continue processing the current SQL statement as appropriate.
  7387. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7388. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7389. ** had been ABORT.
  7390. **
  7391. ** Virtual table implementations that are required to handle OR REPLACE
  7392. ** must do so within the [xUpdate] method. If a call to the
  7393. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7394. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7395. ** silently replace the appropriate rows within the xUpdate callback and
  7396. ** return SQLITE_OK. Or, if this is not possible, it may return
  7397. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7398. ** constraint handling.
  7399. ** </dl>
  7400. */
  7401. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7402. /*
  7403. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7404. **
  7405. ** This function may only be called from within a call to the [xUpdate] method
  7406. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7407. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7408. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7409. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7410. ** [virtual table].
  7411. */
  7412. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7413. /*
  7414. ** CAPI3REF: Conflict resolution modes
  7415. **
  7416. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7417. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7418. ** is for the SQL statement being evaluated.
  7419. **
  7420. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7421. ** return value from the [sqlite3_set_authorizer()] callback and that
  7422. ** [SQLITE_ABORT] is also a [result code].
  7423. */
  7424. #define SQLITE_ROLLBACK 1
  7425. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7426. #define SQLITE_FAIL 3
  7427. /* #define SQLITE_ABORT 4 // Also an error code */
  7428. #define SQLITE_REPLACE 5
  7429. /*
  7430. ** Undo the hack that converts floating point types to integer for
  7431. ** builds on processors without floating point support.
  7432. */
  7433. #ifdef SQLITE_OMIT_FLOATING_POINT
  7434. # undef double
  7435. #endif
  7436. #if 0
  7437. } /* End of the 'extern "C"' block */
  7438. #endif
  7439. #endif
  7440. /*
  7441. ** 2010 August 30
  7442. **
  7443. ** The author disclaims copyright to this source code. In place of
  7444. ** a legal notice, here is a blessing:
  7445. **
  7446. ** May you do good and not evil.
  7447. ** May you find forgiveness for yourself and forgive others.
  7448. ** May you share freely, never taking more than you give.
  7449. **
  7450. *************************************************************************
  7451. */
  7452. #ifndef _SQLITE3RTREE_H_
  7453. #define _SQLITE3RTREE_H_
  7454. #if 0
  7455. extern "C" {
  7456. #endif
  7457. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7458. /*
  7459. ** Register a geometry callback named zGeom that can be used as part of an
  7460. ** R-Tree geometry query as follows:
  7461. **
  7462. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7463. */
  7464. SQLITE_API int sqlite3_rtree_geometry_callback(
  7465. sqlite3 *db,
  7466. const char *zGeom,
  7467. #ifdef SQLITE_RTREE_INT_ONLY
  7468. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7469. #else
  7470. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7471. #endif
  7472. void *pContext
  7473. );
  7474. /*
  7475. ** A pointer to a structure of the following type is passed as the first
  7476. ** argument to callbacks registered using rtree_geometry_callback().
  7477. */
  7478. struct sqlite3_rtree_geometry {
  7479. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7480. int nParam; /* Size of array aParam[] */
  7481. double *aParam; /* Parameters passed to SQL geom function */
  7482. void *pUser; /* Callback implementation user data */
  7483. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7484. };
  7485. #if 0
  7486. } /* end of the 'extern "C"' block */
  7487. #endif
  7488. #endif /* ifndef _SQLITE3RTREE_H_ */
  7489. /************** End of sqlite3.h *********************************************/
  7490. /************** Continuing where we left off in sqliteInt.h ******************/
  7491. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7492. /************** Begin file hash.h ********************************************/
  7493. /*
  7494. ** 2001 September 22
  7495. **
  7496. ** The author disclaims copyright to this source code. In place of
  7497. ** a legal notice, here is a blessing:
  7498. **
  7499. ** May you do good and not evil.
  7500. ** May you find forgiveness for yourself and forgive others.
  7501. ** May you share freely, never taking more than you give.
  7502. **
  7503. *************************************************************************
  7504. ** This is the header file for the generic hash-table implemenation
  7505. ** used in SQLite.
  7506. */
  7507. #ifndef _SQLITE_HASH_H_
  7508. #define _SQLITE_HASH_H_
  7509. /* Forward declarations of structures. */
  7510. typedef struct Hash Hash;
  7511. typedef struct HashElem HashElem;
  7512. /* A complete hash table is an instance of the following structure.
  7513. ** The internals of this structure are intended to be opaque -- client
  7514. ** code should not attempt to access or modify the fields of this structure
  7515. ** directly. Change this structure only by using the routines below.
  7516. ** However, some of the "procedures" and "functions" for modifying and
  7517. ** accessing this structure are really macros, so we can't really make
  7518. ** this structure opaque.
  7519. **
  7520. ** All elements of the hash table are on a single doubly-linked list.
  7521. ** Hash.first points to the head of this list.
  7522. **
  7523. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7524. ** the global doubly-linked list. The contents of the bucket are the
  7525. ** element pointed to plus the next _ht.count-1 elements in the list.
  7526. **
  7527. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7528. ** by a linear search of the global list. For small tables, the
  7529. ** Hash.ht table is never allocated because if there are few elements
  7530. ** in the table, it is faster to do a linear search than to manage
  7531. ** the hash table.
  7532. */
  7533. struct Hash {
  7534. unsigned int htsize; /* Number of buckets in the hash table */
  7535. unsigned int count; /* Number of entries in this table */
  7536. HashElem *first; /* The first element of the array */
  7537. struct _ht { /* the hash table */
  7538. int count; /* Number of entries with this hash */
  7539. HashElem *chain; /* Pointer to first entry with this hash */
  7540. } *ht;
  7541. };
  7542. /* Each element in the hash table is an instance of the following
  7543. ** structure. All elements are stored on a single doubly-linked list.
  7544. **
  7545. ** Again, this structure is intended to be opaque, but it can't really
  7546. ** be opaque because it is used by macros.
  7547. */
  7548. struct HashElem {
  7549. HashElem *next, *prev; /* Next and previous elements in the table */
  7550. void *data; /* Data associated with this element */
  7551. const char *pKey; int nKey; /* Key associated with this element */
  7552. };
  7553. /*
  7554. ** Access routines. To delete, insert a NULL pointer.
  7555. */
  7556. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7557. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7558. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7559. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7560. /*
  7561. ** Macros for looping over all elements of a hash table. The idiom is
  7562. ** like this:
  7563. **
  7564. ** Hash h;
  7565. ** HashElem *p;
  7566. ** ...
  7567. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7568. ** SomeStructure *pData = sqliteHashData(p);
  7569. ** // do something with pData
  7570. ** }
  7571. */
  7572. #define sqliteHashFirst(H) ((H)->first)
  7573. #define sqliteHashNext(E) ((E)->next)
  7574. #define sqliteHashData(E) ((E)->data)
  7575. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7576. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7577. /*
  7578. ** Number of entries in a hash table
  7579. */
  7580. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7581. #endif /* _SQLITE_HASH_H_ */
  7582. /************** End of hash.h ************************************************/
  7583. /************** Continuing where we left off in sqliteInt.h ******************/
  7584. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7585. /************** Begin file parse.h *******************************************/
  7586. #define TK_SEMI 1
  7587. #define TK_EXPLAIN 2
  7588. #define TK_QUERY 3
  7589. #define TK_PLAN 4
  7590. #define TK_BEGIN 5
  7591. #define TK_TRANSACTION 6
  7592. #define TK_DEFERRED 7
  7593. #define TK_IMMEDIATE 8
  7594. #define TK_EXCLUSIVE 9
  7595. #define TK_COMMIT 10
  7596. #define TK_END 11
  7597. #define TK_ROLLBACK 12
  7598. #define TK_SAVEPOINT 13
  7599. #define TK_RELEASE 14
  7600. #define TK_TO 15
  7601. #define TK_TABLE 16
  7602. #define TK_CREATE 17
  7603. #define TK_IF 18
  7604. #define TK_NOT 19
  7605. #define TK_EXISTS 20
  7606. #define TK_TEMP 21
  7607. #define TK_LP 22
  7608. #define TK_RP 23
  7609. #define TK_AS 24
  7610. #define TK_COMMA 25
  7611. #define TK_ID 26
  7612. #define TK_INDEXED 27
  7613. #define TK_ABORT 28
  7614. #define TK_ACTION 29
  7615. #define TK_AFTER 30
  7616. #define TK_ANALYZE 31
  7617. #define TK_ASC 32
  7618. #define TK_ATTACH 33
  7619. #define TK_BEFORE 34
  7620. #define TK_BY 35
  7621. #define TK_CASCADE 36
  7622. #define TK_CAST 37
  7623. #define TK_COLUMNKW 38
  7624. #define TK_CONFLICT 39
  7625. #define TK_DATABASE 40
  7626. #define TK_DESC 41
  7627. #define TK_DETACH 42
  7628. #define TK_EACH 43
  7629. #define TK_FAIL 44
  7630. #define TK_FOR 45
  7631. #define TK_IGNORE 46
  7632. #define TK_INITIALLY 47
  7633. #define TK_INSTEAD 48
  7634. #define TK_LIKE_KW 49
  7635. #define TK_MATCH 50
  7636. #define TK_NO 51
  7637. #define TK_KEY 52
  7638. #define TK_OF 53
  7639. #define TK_OFFSET 54
  7640. #define TK_PRAGMA 55
  7641. #define TK_RAISE 56
  7642. #define TK_REPLACE 57
  7643. #define TK_RESTRICT 58
  7644. #define TK_ROW 59
  7645. #define TK_TRIGGER 60
  7646. #define TK_VACUUM 61
  7647. #define TK_VIEW 62
  7648. #define TK_VIRTUAL 63
  7649. #define TK_REINDEX 64
  7650. #define TK_RENAME 65
  7651. #define TK_CTIME_KW 66
  7652. #define TK_ANY 67
  7653. #define TK_OR 68
  7654. #define TK_AND 69
  7655. #define TK_IS 70
  7656. #define TK_BETWEEN 71
  7657. #define TK_IN 72
  7658. #define TK_ISNULL 73
  7659. #define TK_NOTNULL 74
  7660. #define TK_NE 75
  7661. #define TK_EQ 76
  7662. #define TK_GT 77
  7663. #define TK_LE 78
  7664. #define TK_LT 79
  7665. #define TK_GE 80
  7666. #define TK_ESCAPE 81
  7667. #define TK_BITAND 82
  7668. #define TK_BITOR 83
  7669. #define TK_LSHIFT 84
  7670. #define TK_RSHIFT 85
  7671. #define TK_PLUS 86
  7672. #define TK_MINUS 87
  7673. #define TK_STAR 88
  7674. #define TK_SLASH 89
  7675. #define TK_REM 90
  7676. #define TK_CONCAT 91
  7677. #define TK_COLLATE 92
  7678. #define TK_BITNOT 93
  7679. #define TK_STRING 94
  7680. #define TK_JOIN_KW 95
  7681. #define TK_CONSTRAINT 96
  7682. #define TK_DEFAULT 97
  7683. #define TK_NULL 98
  7684. #define TK_PRIMARY 99
  7685. #define TK_UNIQUE 100
  7686. #define TK_CHECK 101
  7687. #define TK_REFERENCES 102
  7688. #define TK_AUTOINCR 103
  7689. #define TK_ON 104
  7690. #define TK_INSERT 105
  7691. #define TK_DELETE 106
  7692. #define TK_UPDATE 107
  7693. #define TK_SET 108
  7694. #define TK_DEFERRABLE 109
  7695. #define TK_FOREIGN 110
  7696. #define TK_DROP 111
  7697. #define TK_UNION 112
  7698. #define TK_ALL 113
  7699. #define TK_EXCEPT 114
  7700. #define TK_INTERSECT 115
  7701. #define TK_SELECT 116
  7702. #define TK_DISTINCT 117
  7703. #define TK_DOT 118
  7704. #define TK_FROM 119
  7705. #define TK_JOIN 120
  7706. #define TK_USING 121
  7707. #define TK_ORDER 122
  7708. #define TK_GROUP 123
  7709. #define TK_HAVING 124
  7710. #define TK_LIMIT 125
  7711. #define TK_WHERE 126
  7712. #define TK_INTO 127
  7713. #define TK_VALUES 128
  7714. #define TK_INTEGER 129
  7715. #define TK_FLOAT 130
  7716. #define TK_BLOB 131
  7717. #define TK_REGISTER 132
  7718. #define TK_VARIABLE 133
  7719. #define TK_CASE 134
  7720. #define TK_WHEN 135
  7721. #define TK_THEN 136
  7722. #define TK_ELSE 137
  7723. #define TK_INDEX 138
  7724. #define TK_ALTER 139
  7725. #define TK_ADD 140
  7726. #define TK_TO_TEXT 141
  7727. #define TK_TO_BLOB 142
  7728. #define TK_TO_NUMERIC 143
  7729. #define TK_TO_INT 144
  7730. #define TK_TO_REAL 145
  7731. #define TK_ISNOT 146
  7732. #define TK_END_OF_FILE 147
  7733. #define TK_ILLEGAL 148
  7734. #define TK_SPACE 149
  7735. #define TK_UNCLOSED_STRING 150
  7736. #define TK_FUNCTION 151
  7737. #define TK_COLUMN 152
  7738. #define TK_AGG_FUNCTION 153
  7739. #define TK_AGG_COLUMN 154
  7740. #define TK_CONST_FUNC 155
  7741. #define TK_UMINUS 156
  7742. #define TK_UPLUS 157
  7743. /************** End of parse.h ***********************************************/
  7744. /************** Continuing where we left off in sqliteInt.h ******************/
  7745. #include <stdio.h>
  7746. #include <stdlib.h>
  7747. #include <string.h>
  7748. #include <assert.h>
  7749. #include <stddef.h>
  7750. /*
  7751. ** If compiling for a processor that lacks floating point support,
  7752. ** substitute integer for floating-point
  7753. */
  7754. #ifdef SQLITE_OMIT_FLOATING_POINT
  7755. # define double sqlite_int64
  7756. # define float sqlite_int64
  7757. # define LONGDOUBLE_TYPE sqlite_int64
  7758. # ifndef SQLITE_BIG_DBL
  7759. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7760. # endif
  7761. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7762. # define SQLITE_OMIT_TRACE 1
  7763. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7764. # undef SQLITE_HAVE_ISNAN
  7765. #endif
  7766. #ifndef SQLITE_BIG_DBL
  7767. # define SQLITE_BIG_DBL (1e99)
  7768. #endif
  7769. /*
  7770. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7771. ** afterward. Having this macro allows us to cause the C compiler
  7772. ** to omit code used by TEMP tables without messy #ifndef statements.
  7773. */
  7774. #ifdef SQLITE_OMIT_TEMPDB
  7775. #define OMIT_TEMPDB 1
  7776. #else
  7777. #define OMIT_TEMPDB 0
  7778. #endif
  7779. /*
  7780. ** The "file format" number is an integer that is incremented whenever
  7781. ** the VDBE-level file format changes. The following macros define the
  7782. ** the default file format for new databases and the maximum file format
  7783. ** that the library can read.
  7784. */
  7785. #define SQLITE_MAX_FILE_FORMAT 4
  7786. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7787. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7788. #endif
  7789. /*
  7790. ** Determine whether triggers are recursive by default. This can be
  7791. ** changed at run-time using a pragma.
  7792. */
  7793. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7794. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7795. #endif
  7796. /*
  7797. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7798. ** on the command-line
  7799. */
  7800. #ifndef SQLITE_TEMP_STORE
  7801. # define SQLITE_TEMP_STORE 1
  7802. #endif
  7803. /*
  7804. ** GCC does not define the offsetof() macro so we'll have to do it
  7805. ** ourselves.
  7806. */
  7807. #ifndef offsetof
  7808. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7809. #endif
  7810. /*
  7811. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7812. ** not, there are still machines out there that use EBCDIC.)
  7813. */
  7814. #if 'A' == '\301'
  7815. # define SQLITE_EBCDIC 1
  7816. #else
  7817. # define SQLITE_ASCII 1
  7818. #endif
  7819. /*
  7820. ** Integers of known sizes. These typedefs might change for architectures
  7821. ** where the sizes very. Preprocessor macros are available so that the
  7822. ** types can be conveniently redefined at compile-type. Like this:
  7823. **
  7824. ** cc '-DUINTPTR_TYPE=long long int' ...
  7825. */
  7826. #ifndef UINT32_TYPE
  7827. # ifdef HAVE_UINT32_T
  7828. # define UINT32_TYPE uint32_t
  7829. # else
  7830. # define UINT32_TYPE unsigned int
  7831. # endif
  7832. #endif
  7833. #ifndef UINT16_TYPE
  7834. # ifdef HAVE_UINT16_T
  7835. # define UINT16_TYPE uint16_t
  7836. # else
  7837. # define UINT16_TYPE unsigned short int
  7838. # endif
  7839. #endif
  7840. #ifndef INT16_TYPE
  7841. # ifdef HAVE_INT16_T
  7842. # define INT16_TYPE int16_t
  7843. # else
  7844. # define INT16_TYPE short int
  7845. # endif
  7846. #endif
  7847. #ifndef UINT8_TYPE
  7848. # ifdef HAVE_UINT8_T
  7849. # define UINT8_TYPE uint8_t
  7850. # else
  7851. # define UINT8_TYPE unsigned char
  7852. # endif
  7853. #endif
  7854. #ifndef INT8_TYPE
  7855. # ifdef HAVE_INT8_T
  7856. # define INT8_TYPE int8_t
  7857. # else
  7858. # define INT8_TYPE signed char
  7859. # endif
  7860. #endif
  7861. #ifndef LONGDOUBLE_TYPE
  7862. # define LONGDOUBLE_TYPE long double
  7863. #endif
  7864. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7865. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7866. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7867. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7868. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7869. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7870. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7871. /*
  7872. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7873. ** that can be stored in a u32 without loss of data. The value
  7874. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  7875. ** have to specify the value in the less intuitive manner shown:
  7876. */
  7877. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  7878. /*
  7879. ** The datatype used to store estimates of the number of rows in a
  7880. ** table or index. This is an unsigned integer type. For 99.9% of
  7881. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  7882. ** can be used at compile-time if desired.
  7883. */
  7884. #ifdef SQLITE_64BIT_STATS
  7885. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  7886. #else
  7887. typedef u32 tRowcnt; /* 32-bit is the default */
  7888. #endif
  7889. /*
  7890. ** Macros to determine whether the machine is big or little endian,
  7891. ** evaluated at runtime.
  7892. */
  7893. #ifdef SQLITE_AMALGAMATION
  7894. SQLITE_PRIVATE const int sqlite3one = 1;
  7895. #else
  7896. SQLITE_PRIVATE const int sqlite3one;
  7897. #endif
  7898. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  7899. || defined(__x86_64) || defined(__x86_64__)
  7900. # define SQLITE_BIGENDIAN 0
  7901. # define SQLITE_LITTLEENDIAN 1
  7902. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  7903. #else
  7904. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  7905. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  7906. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  7907. #endif
  7908. /*
  7909. ** Constants for the largest and smallest possible 64-bit signed integers.
  7910. ** These macros are designed to work correctly on both 32-bit and 64-bit
  7911. ** compilers.
  7912. */
  7913. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  7914. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  7915. /*
  7916. ** Round up a number to the next larger multiple of 8. This is used
  7917. ** to force 8-byte alignment on 64-bit architectures.
  7918. */
  7919. #define ROUND8(x) (((x)+7)&~7)
  7920. /*
  7921. ** Round down to the nearest multiple of 8
  7922. */
  7923. #define ROUNDDOWN8(x) ((x)&~7)
  7924. /*
  7925. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  7926. ** macro is used only within assert() to verify that the code gets
  7927. ** all alignment restrictions correct.
  7928. **
  7929. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  7930. ** underlying malloc() implemention might return us 4-byte aligned
  7931. ** pointers. In that case, only verify 4-byte alignment.
  7932. */
  7933. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  7934. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  7935. #else
  7936. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  7937. #endif
  7938. /*
  7939. ** An instance of the following structure is used to store the busy-handler
  7940. ** callback for a given sqlite handle.
  7941. **
  7942. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  7943. ** callback for the database handle. Each pager opened via the sqlite
  7944. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  7945. ** callback is currently invoked only from within pager.c.
  7946. */
  7947. typedef struct BusyHandler BusyHandler;
  7948. struct BusyHandler {
  7949. int (*xFunc)(void *,int); /* The busy callback */
  7950. void *pArg; /* First arg to busy callback */
  7951. int nBusy; /* Incremented with each busy call */
  7952. };
  7953. /*
  7954. ** Name of the master database table. The master database table
  7955. ** is a special table that holds the names and attributes of all
  7956. ** user tables and indices.
  7957. */
  7958. #define MASTER_NAME "sqlite_master"
  7959. #define TEMP_MASTER_NAME "sqlite_temp_master"
  7960. /*
  7961. ** The root-page of the master database table.
  7962. */
  7963. #define MASTER_ROOT 1
  7964. /*
  7965. ** The name of the schema table.
  7966. */
  7967. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  7968. /*
  7969. ** A convenience macro that returns the number of elements in
  7970. ** an array.
  7971. */
  7972. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  7973. /*
  7974. ** The following value as a destructor means to use sqlite3DbFree().
  7975. ** The sqlite3DbFree() routine requires two parameters instead of the
  7976. ** one parameter that destructors normally want. So we have to introduce
  7977. ** this magic value that the code knows to handle differently. Any
  7978. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  7979. ** and SQLITE_TRANSIENT.
  7980. */
  7981. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  7982. /*
  7983. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  7984. ** not support Writable Static Data (WSD) such as global and static variables.
  7985. ** All variables must either be on the stack or dynamically allocated from
  7986. ** the heap. When WSD is unsupported, the variable declarations scattered
  7987. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  7988. ** macro is used for this purpose. And instead of referencing the variable
  7989. ** directly, we use its constant as a key to lookup the run-time allocated
  7990. ** buffer that holds real variable. The constant is also the initializer
  7991. ** for the run-time allocated buffer.
  7992. **
  7993. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  7994. ** macros become no-ops and have zero performance impact.
  7995. */
  7996. #ifdef SQLITE_OMIT_WSD
  7997. #define SQLITE_WSD const
  7998. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  7999. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8000. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8001. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8002. #else
  8003. #define SQLITE_WSD
  8004. #define GLOBAL(t,v) v
  8005. #define sqlite3GlobalConfig sqlite3Config
  8006. #endif
  8007. /*
  8008. ** The following macros are used to suppress compiler warnings and to
  8009. ** make it clear to human readers when a function parameter is deliberately
  8010. ** left unused within the body of a function. This usually happens when
  8011. ** a function is called via a function pointer. For example the
  8012. ** implementation of an SQL aggregate step callback may not use the
  8013. ** parameter indicating the number of arguments passed to the aggregate,
  8014. ** if it knows that this is enforced elsewhere.
  8015. **
  8016. ** When a function parameter is not used at all within the body of a function,
  8017. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8018. ** However, these macros may also be used to suppress warnings related to
  8019. ** parameters that may or may not be used depending on compilation options.
  8020. ** For example those parameters only used in assert() statements. In these
  8021. ** cases the parameters are named as per the usual conventions.
  8022. */
  8023. #define UNUSED_PARAMETER(x) (void)(x)
  8024. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8025. /*
  8026. ** Forward references to structures
  8027. */
  8028. typedef struct AggInfo AggInfo;
  8029. typedef struct AuthContext AuthContext;
  8030. typedef struct AutoincInfo AutoincInfo;
  8031. typedef struct Bitvec Bitvec;
  8032. typedef struct CollSeq CollSeq;
  8033. typedef struct Column Column;
  8034. typedef struct Db Db;
  8035. typedef struct Schema Schema;
  8036. typedef struct Expr Expr;
  8037. typedef struct ExprList ExprList;
  8038. typedef struct ExprSpan ExprSpan;
  8039. typedef struct FKey FKey;
  8040. typedef struct FuncDestructor FuncDestructor;
  8041. typedef struct FuncDef FuncDef;
  8042. typedef struct FuncDefHash FuncDefHash;
  8043. typedef struct IdList IdList;
  8044. typedef struct Index Index;
  8045. typedef struct IndexSample IndexSample;
  8046. typedef struct KeyClass KeyClass;
  8047. typedef struct KeyInfo KeyInfo;
  8048. typedef struct Lookaside Lookaside;
  8049. typedef struct LookasideSlot LookasideSlot;
  8050. typedef struct Module Module;
  8051. typedef struct NameContext NameContext;
  8052. typedef struct Parse Parse;
  8053. typedef struct RowSet RowSet;
  8054. typedef struct Savepoint Savepoint;
  8055. typedef struct Select Select;
  8056. typedef struct SelectDest SelectDest;
  8057. typedef struct SrcList SrcList;
  8058. typedef struct StrAccum StrAccum;
  8059. typedef struct Table Table;
  8060. typedef struct TableLock TableLock;
  8061. typedef struct Token Token;
  8062. typedef struct Trigger Trigger;
  8063. typedef struct TriggerPrg TriggerPrg;
  8064. typedef struct TriggerStep TriggerStep;
  8065. typedef struct UnpackedRecord UnpackedRecord;
  8066. typedef struct VTable VTable;
  8067. typedef struct VtabCtx VtabCtx;
  8068. typedef struct Walker Walker;
  8069. typedef struct WherePlan WherePlan;
  8070. typedef struct WhereInfo WhereInfo;
  8071. typedef struct WhereLevel WhereLevel;
  8072. /*
  8073. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8074. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8075. ** pointer types (i.e. FuncDef) defined above.
  8076. */
  8077. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8078. /************** Begin file btree.h *******************************************/
  8079. /*
  8080. ** 2001 September 15
  8081. **
  8082. ** The author disclaims copyright to this source code. In place of
  8083. ** a legal notice, here is a blessing:
  8084. **
  8085. ** May you do good and not evil.
  8086. ** May you find forgiveness for yourself and forgive others.
  8087. ** May you share freely, never taking more than you give.
  8088. **
  8089. *************************************************************************
  8090. ** This header file defines the interface that the sqlite B-Tree file
  8091. ** subsystem. See comments in the source code for a detailed description
  8092. ** of what each interface routine does.
  8093. */
  8094. #ifndef _BTREE_H_
  8095. #define _BTREE_H_
  8096. /* TODO: This definition is just included so other modules compile. It
  8097. ** needs to be revisited.
  8098. */
  8099. #define SQLITE_N_BTREE_META 10
  8100. /*
  8101. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8102. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8103. */
  8104. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8105. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8106. #endif
  8107. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8108. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8109. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8110. /*
  8111. ** Forward declarations of structure
  8112. */
  8113. typedef struct Btree Btree;
  8114. typedef struct BtCursor BtCursor;
  8115. typedef struct BtShared BtShared;
  8116. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8117. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8118. const char *zFilename, /* Name of database file to open */
  8119. sqlite3 *db, /* Associated database connection */
  8120. Btree **ppBtree, /* Return open Btree* here */
  8121. int flags, /* Flags */
  8122. int vfsFlags /* Flags passed through to VFS open */
  8123. );
  8124. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8125. ** following values.
  8126. **
  8127. ** NOTE: These values must match the corresponding PAGER_ values in
  8128. ** pager.h.
  8129. */
  8130. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8131. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8132. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8133. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8134. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8135. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8136. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
  8137. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8138. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8139. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8140. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8141. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8142. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8143. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8144. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8145. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8146. #endif
  8147. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8148. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8149. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8150. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8151. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8152. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8153. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8154. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8155. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8156. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8157. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8158. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8159. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8160. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8161. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8162. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8163. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8164. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8165. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8166. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8167. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8168. ** of the flags shown below.
  8169. **
  8170. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8171. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8172. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8173. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8174. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8175. ** indices.)
  8176. */
  8177. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8178. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8179. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8180. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8181. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8182. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8183. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8184. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8185. /*
  8186. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8187. ** should be one of the following values. The integer values are assigned
  8188. ** to constants so that the offset of the corresponding field in an
  8189. ** SQLite database header may be found using the following formula:
  8190. **
  8191. ** offset = 36 + (idx * 4)
  8192. **
  8193. ** For example, the free-page-count field is located at byte offset 36 of
  8194. ** the database file header. The incr-vacuum-flag field is located at
  8195. ** byte offset 64 (== 36+4*7).
  8196. */
  8197. #define BTREE_FREE_PAGE_COUNT 0
  8198. #define BTREE_SCHEMA_VERSION 1
  8199. #define BTREE_FILE_FORMAT 2
  8200. #define BTREE_DEFAULT_CACHE_SIZE 3
  8201. #define BTREE_LARGEST_ROOT_PAGE 4
  8202. #define BTREE_TEXT_ENCODING 5
  8203. #define BTREE_USER_VERSION 6
  8204. #define BTREE_INCR_VACUUM 7
  8205. /*
  8206. ** Values that may be OR'd together to form the second argument of an
  8207. ** sqlite3BtreeCursorHints() call.
  8208. */
  8209. #define BTREE_BULKLOAD 0x00000001
  8210. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8211. Btree*, /* BTree containing table to open */
  8212. int iTable, /* Index of root page */
  8213. int wrFlag, /* 1 for writing. 0 for read-only */
  8214. struct KeyInfo*, /* First argument to compare function */
  8215. BtCursor *pCursor /* Space to write cursor structure */
  8216. );
  8217. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8218. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8219. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8220. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8221. BtCursor*,
  8222. UnpackedRecord *pUnKey,
  8223. i64 intKey,
  8224. int bias,
  8225. int *pRes
  8226. );
  8227. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8228. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8229. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8230. const void *pData, int nData,
  8231. int nZero, int bias, int seekResult);
  8232. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8233. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8234. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8235. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8236. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8237. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8238. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8239. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8240. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8241. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8242. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8243. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8244. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8245. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8246. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8247. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8248. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8249. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8250. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8251. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8252. #ifndef NDEBUG
  8253. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8254. #endif
  8255. #ifndef SQLITE_OMIT_BTREECOUNT
  8256. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8257. #endif
  8258. #ifdef SQLITE_TEST
  8259. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8260. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8261. #endif
  8262. #ifndef SQLITE_OMIT_WAL
  8263. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8264. #endif
  8265. /*
  8266. ** If we are not using shared cache, then there is no need to
  8267. ** use mutexes to access the BtShared structures. So make the
  8268. ** Enter and Leave procedures no-ops.
  8269. */
  8270. #ifndef SQLITE_OMIT_SHARED_CACHE
  8271. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8272. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8273. #else
  8274. # define sqlite3BtreeEnter(X)
  8275. # define sqlite3BtreeEnterAll(X)
  8276. #endif
  8277. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8278. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8279. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8280. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8281. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8282. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8283. #ifndef NDEBUG
  8284. /* These routines are used inside assert() statements only. */
  8285. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8286. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8287. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8288. #endif
  8289. #else
  8290. # define sqlite3BtreeSharable(X) 0
  8291. # define sqlite3BtreeLeave(X)
  8292. # define sqlite3BtreeEnterCursor(X)
  8293. # define sqlite3BtreeLeaveCursor(X)
  8294. # define sqlite3BtreeLeaveAll(X)
  8295. # define sqlite3BtreeHoldsMutex(X) 1
  8296. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8297. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8298. #endif
  8299. #endif /* _BTREE_H_ */
  8300. /************** End of btree.h ***********************************************/
  8301. /************** Continuing where we left off in sqliteInt.h ******************/
  8302. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8303. /************** Begin file vdbe.h ********************************************/
  8304. /*
  8305. ** 2001 September 15
  8306. **
  8307. ** The author disclaims copyright to this source code. In place of
  8308. ** a legal notice, here is a blessing:
  8309. **
  8310. ** May you do good and not evil.
  8311. ** May you find forgiveness for yourself and forgive others.
  8312. ** May you share freely, never taking more than you give.
  8313. **
  8314. *************************************************************************
  8315. ** Header file for the Virtual DataBase Engine (VDBE)
  8316. **
  8317. ** This header defines the interface to the virtual database engine
  8318. ** or VDBE. The VDBE implements an abstract machine that runs a
  8319. ** simple program to access and modify the underlying database.
  8320. */
  8321. #ifndef _SQLITE_VDBE_H_
  8322. #define _SQLITE_VDBE_H_
  8323. /* #include <stdio.h> */
  8324. /*
  8325. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8326. ** in the source file sqliteVdbe.c are allowed to see the insides
  8327. ** of this structure.
  8328. */
  8329. typedef struct Vdbe Vdbe;
  8330. /*
  8331. ** The names of the following types declared in vdbeInt.h are required
  8332. ** for the VdbeOp definition.
  8333. */
  8334. typedef struct VdbeFunc VdbeFunc;
  8335. typedef struct Mem Mem;
  8336. typedef struct SubProgram SubProgram;
  8337. /*
  8338. ** A single instruction of the virtual machine has an opcode
  8339. ** and as many as three operands. The instruction is recorded
  8340. ** as an instance of the following structure:
  8341. */
  8342. struct VdbeOp {
  8343. u8 opcode; /* What operation to perform */
  8344. signed char p4type; /* One of the P4_xxx constants for p4 */
  8345. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8346. u8 p5; /* Fifth parameter is an unsigned character */
  8347. int p1; /* First operand */
  8348. int p2; /* Second parameter (often the jump destination) */
  8349. int p3; /* The third parameter */
  8350. union { /* fourth parameter */
  8351. int i; /* Integer value if p4type==P4_INT32 */
  8352. void *p; /* Generic pointer */
  8353. char *z; /* Pointer to data for string (char array) types */
  8354. i64 *pI64; /* Used when p4type is P4_INT64 */
  8355. double *pReal; /* Used when p4type is P4_REAL */
  8356. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8357. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  8358. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8359. Mem *pMem; /* Used when p4type is P4_MEM */
  8360. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8361. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8362. int *ai; /* Used when p4type is P4_INTARRAY */
  8363. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8364. int (*xAdvance)(BtCursor *, int *);
  8365. } p4;
  8366. #ifdef SQLITE_DEBUG
  8367. char *zComment; /* Comment to improve readability */
  8368. #endif
  8369. #ifdef VDBE_PROFILE
  8370. int cnt; /* Number of times this instruction was executed */
  8371. u64 cycles; /* Total time spent executing this instruction */
  8372. #endif
  8373. };
  8374. typedef struct VdbeOp VdbeOp;
  8375. /*
  8376. ** A sub-routine used to implement a trigger program.
  8377. */
  8378. struct SubProgram {
  8379. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8380. int nOp; /* Elements in aOp[] */
  8381. int nMem; /* Number of memory cells required */
  8382. int nCsr; /* Number of cursors required */
  8383. int nOnce; /* Number of OP_Once instructions */
  8384. void *token; /* id that may be used to recursive triggers */
  8385. SubProgram *pNext; /* Next sub-program already visited */
  8386. };
  8387. /*
  8388. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8389. ** it takes up less space.
  8390. */
  8391. struct VdbeOpList {
  8392. u8 opcode; /* What operation to perform */
  8393. signed char p1; /* First operand */
  8394. signed char p2; /* Second parameter (often the jump destination) */
  8395. signed char p3; /* Third parameter */
  8396. };
  8397. typedef struct VdbeOpList VdbeOpList;
  8398. /*
  8399. ** Allowed values of VdbeOp.p4type
  8400. */
  8401. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8402. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8403. #define P4_STATIC (-2) /* Pointer to a static string */
  8404. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8405. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8406. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8407. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  8408. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8409. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8410. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8411. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8412. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8413. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8414. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8415. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8416. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8417. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8418. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8419. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8420. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8421. ** gets freed when the Vdbe is finalized so it still should be obtained
  8422. ** from a single sqliteMalloc(). But no copy is made and the calling
  8423. ** function should *not* try to free the KeyInfo.
  8424. */
  8425. #define P4_KEYINFO_HANDOFF (-16)
  8426. #define P4_KEYINFO_STATIC (-17)
  8427. /*
  8428. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8429. ** number of columns of data returned by the statement.
  8430. */
  8431. #define COLNAME_NAME 0
  8432. #define COLNAME_DECLTYPE 1
  8433. #define COLNAME_DATABASE 2
  8434. #define COLNAME_TABLE 3
  8435. #define COLNAME_COLUMN 4
  8436. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8437. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8438. #else
  8439. # ifdef SQLITE_OMIT_DECLTYPE
  8440. # define COLNAME_N 1 /* Store only the name */
  8441. # else
  8442. # define COLNAME_N 2 /* Store the name and decltype */
  8443. # endif
  8444. #endif
  8445. /*
  8446. ** The following macro converts a relative address in the p2 field
  8447. ** of a VdbeOp structure into a negative number so that
  8448. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8449. ** the macro again restores the address.
  8450. */
  8451. #define ADDR(X) (-1-(X))
  8452. /*
  8453. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8454. ** header file that defines a number for each opcode used by the VDBE.
  8455. */
  8456. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8457. /************** Begin file opcodes.h *****************************************/
  8458. /* Automatically generated. Do not edit */
  8459. /* See the mkopcodeh.awk script for details */
  8460. #define OP_Goto 1
  8461. #define OP_Gosub 2
  8462. #define OP_Return 3
  8463. #define OP_Yield 4
  8464. #define OP_HaltIfNull 5
  8465. #define OP_Halt 6
  8466. #define OP_Integer 7
  8467. #define OP_Int64 8
  8468. #define OP_Real 130 /* same as TK_FLOAT */
  8469. #define OP_String8 94 /* same as TK_STRING */
  8470. #define OP_String 9
  8471. #define OP_Null 10
  8472. #define OP_Blob 11
  8473. #define OP_Variable 12
  8474. #define OP_Move 13
  8475. #define OP_Copy 14
  8476. #define OP_SCopy 15
  8477. #define OP_ResultRow 16
  8478. #define OP_Concat 91 /* same as TK_CONCAT */
  8479. #define OP_Add 86 /* same as TK_PLUS */
  8480. #define OP_Subtract 87 /* same as TK_MINUS */
  8481. #define OP_Multiply 88 /* same as TK_STAR */
  8482. #define OP_Divide 89 /* same as TK_SLASH */
  8483. #define OP_Remainder 90 /* same as TK_REM */
  8484. #define OP_CollSeq 17
  8485. #define OP_Function 18
  8486. #define OP_BitAnd 82 /* same as TK_BITAND */
  8487. #define OP_BitOr 83 /* same as TK_BITOR */
  8488. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8489. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8490. #define OP_AddImm 20
  8491. #define OP_MustBeInt 21
  8492. #define OP_RealAffinity 22
  8493. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8494. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8495. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8496. #define OP_ToInt 144 /* same as TK_TO_INT */
  8497. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8498. #define OP_Eq 76 /* same as TK_EQ */
  8499. #define OP_Ne 75 /* same as TK_NE */
  8500. #define OP_Lt 79 /* same as TK_LT */
  8501. #define OP_Le 78 /* same as TK_LE */
  8502. #define OP_Gt 77 /* same as TK_GT */
  8503. #define OP_Ge 80 /* same as TK_GE */
  8504. #define OP_Permutation 23
  8505. #define OP_Compare 24
  8506. #define OP_Jump 25
  8507. #define OP_And 69 /* same as TK_AND */
  8508. #define OP_Or 68 /* same as TK_OR */
  8509. #define OP_Not 19 /* same as TK_NOT */
  8510. #define OP_BitNot 93 /* same as TK_BITNOT */
  8511. #define OP_Once 26
  8512. #define OP_If 27
  8513. #define OP_IfNot 28
  8514. #define OP_IsNull 73 /* same as TK_ISNULL */
  8515. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8516. #define OP_Column 29
  8517. #define OP_Affinity 30
  8518. #define OP_MakeRecord 31
  8519. #define OP_Count 32
  8520. #define OP_Savepoint 33
  8521. #define OP_AutoCommit 34
  8522. #define OP_Transaction 35
  8523. #define OP_ReadCookie 36
  8524. #define OP_SetCookie 37
  8525. #define OP_VerifyCookie 38
  8526. #define OP_OpenRead 39
  8527. #define OP_OpenWrite 40
  8528. #define OP_OpenAutoindex 41
  8529. #define OP_OpenEphemeral 42
  8530. #define OP_SorterOpen 43
  8531. #define OP_OpenPseudo 44
  8532. #define OP_Close 45
  8533. #define OP_SeekLt 46
  8534. #define OP_SeekLe 47
  8535. #define OP_SeekGe 48
  8536. #define OP_SeekGt 49
  8537. #define OP_Seek 50
  8538. #define OP_NotFound 51
  8539. #define OP_Found 52
  8540. #define OP_IsUnique 53
  8541. #define OP_NotExists 54
  8542. #define OP_Sequence 55
  8543. #define OP_NewRowid 56
  8544. #define OP_Insert 57
  8545. #define OP_InsertInt 58
  8546. #define OP_Delete 59
  8547. #define OP_ResetCount 60
  8548. #define OP_SorterCompare 61
  8549. #define OP_SorterData 62
  8550. #define OP_RowKey 63
  8551. #define OP_RowData 64
  8552. #define OP_Rowid 65
  8553. #define OP_NullRow 66
  8554. #define OP_Last 67
  8555. #define OP_SorterSort 70
  8556. #define OP_Sort 71
  8557. #define OP_Rewind 72
  8558. #define OP_SorterNext 81
  8559. #define OP_Prev 92
  8560. #define OP_Next 95
  8561. #define OP_SorterInsert 96
  8562. #define OP_IdxInsert 97
  8563. #define OP_IdxDelete 98
  8564. #define OP_IdxRowid 99
  8565. #define OP_IdxLT 100
  8566. #define OP_IdxGE 101
  8567. #define OP_Destroy 102
  8568. #define OP_Clear 103
  8569. #define OP_CreateIndex 104
  8570. #define OP_CreateTable 105
  8571. #define OP_ParseSchema 106
  8572. #define OP_LoadAnalysis 107
  8573. #define OP_DropTable 108
  8574. #define OP_DropIndex 109
  8575. #define OP_DropTrigger 110
  8576. #define OP_IntegrityCk 111
  8577. #define OP_RowSetAdd 112
  8578. #define OP_RowSetRead 113
  8579. #define OP_RowSetTest 114
  8580. #define OP_Program 115
  8581. #define OP_Param 116
  8582. #define OP_FkCounter 117
  8583. #define OP_FkIfZero 118
  8584. #define OP_MemMax 119
  8585. #define OP_IfPos 120
  8586. #define OP_IfNeg 121
  8587. #define OP_IfZero 122
  8588. #define OP_AggStep 123
  8589. #define OP_AggFinal 124
  8590. #define OP_Checkpoint 125
  8591. #define OP_JournalMode 126
  8592. #define OP_Vacuum 127
  8593. #define OP_IncrVacuum 128
  8594. #define OP_Expire 129
  8595. #define OP_TableLock 131
  8596. #define OP_VBegin 132
  8597. #define OP_VCreate 133
  8598. #define OP_VDestroy 134
  8599. #define OP_VOpen 135
  8600. #define OP_VFilter 136
  8601. #define OP_VColumn 137
  8602. #define OP_VNext 138
  8603. #define OP_VRename 139
  8604. #define OP_VUpdate 140
  8605. #define OP_Pagecount 146
  8606. #define OP_MaxPgcnt 147
  8607. #define OP_Trace 148
  8608. #define OP_Noop 149
  8609. #define OP_Explain 150
  8610. /* Properties such as "out2" or "jump" that are specified in
  8611. ** comments following the "case" for each opcode in the vdbe.c
  8612. ** are encoded into bitvectors as follows:
  8613. */
  8614. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8615. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8616. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8617. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8618. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8619. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8620. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8621. #define OPFLG_INITIALIZER {\
  8622. /* 0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
  8623. /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
  8624. /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
  8625. /* 24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
  8626. /* 32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
  8627. /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
  8628. /* 48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
  8629. /* 56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8630. /* 64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
  8631. /* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8632. /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8633. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
  8634. /* 96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
  8635. /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8636. /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
  8637. /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
  8638. /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8639. /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
  8640. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8641. /************** End of opcodes.h *********************************************/
  8642. /************** Continuing where we left off in vdbe.h ***********************/
  8643. /*
  8644. ** Prototypes for the VDBE interface. See comments on the implementation
  8645. ** for a description of what each of these routines does.
  8646. */
  8647. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8648. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8649. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8650. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8651. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8652. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8653. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8654. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8655. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8656. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8657. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8658. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8659. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8660. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8661. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8662. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8663. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8664. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8665. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8666. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8667. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8668. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8669. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8670. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8671. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8672. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8673. #ifdef SQLITE_DEBUG
  8674. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8675. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8676. #endif
  8677. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8678. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8679. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8680. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8681. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8682. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8683. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8684. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8685. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8686. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8687. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
  8688. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8689. #ifndef SQLITE_OMIT_TRACE
  8690. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8691. #endif
  8692. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8693. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8694. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8695. #ifndef SQLITE_OMIT_TRIGGER
  8696. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8697. #endif
  8698. #ifndef NDEBUG
  8699. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8700. # define VdbeComment(X) sqlite3VdbeComment X
  8701. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8702. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8703. #else
  8704. # define VdbeComment(X)
  8705. # define VdbeNoopComment(X)
  8706. #endif
  8707. #endif
  8708. /************** End of vdbe.h ************************************************/
  8709. /************** Continuing where we left off in sqliteInt.h ******************/
  8710. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8711. /************** Begin file pager.h *******************************************/
  8712. /*
  8713. ** 2001 September 15
  8714. **
  8715. ** The author disclaims copyright to this source code. In place of
  8716. ** a legal notice, here is a blessing:
  8717. **
  8718. ** May you do good and not evil.
  8719. ** May you find forgiveness for yourself and forgive others.
  8720. ** May you share freely, never taking more than you give.
  8721. **
  8722. *************************************************************************
  8723. ** This header file defines the interface that the sqlite page cache
  8724. ** subsystem. The page cache subsystem reads and writes a file a page
  8725. ** at a time and provides a journal for rollback.
  8726. */
  8727. #ifndef _PAGER_H_
  8728. #define _PAGER_H_
  8729. /*
  8730. ** Default maximum size for persistent journal files. A negative
  8731. ** value means no limit. This value may be overridden using the
  8732. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8733. */
  8734. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8735. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8736. #endif
  8737. /*
  8738. ** The type used to represent a page number. The first page in a file
  8739. ** is called page 1. 0 is used to represent "not a page".
  8740. */
  8741. typedef u32 Pgno;
  8742. /*
  8743. ** Each open file is managed by a separate instance of the "Pager" structure.
  8744. */
  8745. typedef struct Pager Pager;
  8746. /*
  8747. ** Handle type for pages.
  8748. */
  8749. typedef struct PgHdr DbPage;
  8750. /*
  8751. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8752. ** reserved for working around a windows/posix incompatibility). It is
  8753. ** used in the journal to signify that the remainder of the journal file
  8754. ** is devoted to storing a master journal name - there are no more pages to
  8755. ** roll back. See comments for function writeMasterJournal() in pager.c
  8756. ** for details.
  8757. */
  8758. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8759. /*
  8760. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8761. **
  8762. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8763. */
  8764. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8765. #define PAGER_MEMORY 0x0002 /* In-memory database */
  8766. /*
  8767. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8768. */
  8769. #define PAGER_LOCKINGMODE_QUERY -1
  8770. #define PAGER_LOCKINGMODE_NORMAL 0
  8771. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8772. /*
  8773. ** Numeric constants that encode the journalmode.
  8774. */
  8775. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8776. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8777. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8778. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8779. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8780. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8781. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8782. /*
  8783. ** The remainder of this file contains the declarations of the functions
  8784. ** that make up the Pager sub-system API. See source code comments for
  8785. ** a detailed description of each routine.
  8786. */
  8787. /* Open and close a Pager connection. */
  8788. SQLITE_PRIVATE int sqlite3PagerOpen(
  8789. sqlite3_vfs*,
  8790. Pager **ppPager,
  8791. const char*,
  8792. int,
  8793. int,
  8794. int,
  8795. void(*)(DbPage*)
  8796. );
  8797. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  8798. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  8799. /* Functions used to configure a Pager object. */
  8800. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  8801. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  8802. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  8803. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  8804. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  8805. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
  8806. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  8807. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  8808. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  8809. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  8810. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  8811. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  8812. /* Functions used to obtain and release page references. */
  8813. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  8814. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  8815. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  8816. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  8817. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  8818. /* Operations on page references. */
  8819. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  8820. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  8821. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  8822. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  8823. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  8824. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  8825. /* Functions used to manage pager transactions and savepoints. */
  8826. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  8827. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  8828. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  8829. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  8830. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  8831. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  8832. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  8833. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  8834. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  8835. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  8836. #ifndef SQLITE_OMIT_WAL
  8837. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  8838. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  8839. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  8840. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  8841. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  8842. #endif
  8843. #ifdef SQLITE_ENABLE_ZIPVFS
  8844. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  8845. #endif
  8846. /* Functions used to query pager state and configuration. */
  8847. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  8848. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  8849. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  8850. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  8851. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  8852. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  8853. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  8854. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  8855. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  8856. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  8857. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  8858. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  8859. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  8860. /* Functions used to truncate the database file. */
  8861. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  8862. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  8863. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  8864. #endif
  8865. /* Functions to support testing and debugging. */
  8866. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  8867. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  8868. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  8869. #endif
  8870. #ifdef SQLITE_TEST
  8871. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  8872. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  8873. void disable_simulated_io_errors(void);
  8874. void enable_simulated_io_errors(void);
  8875. #else
  8876. # define disable_simulated_io_errors()
  8877. # define enable_simulated_io_errors()
  8878. #endif
  8879. #endif /* _PAGER_H_ */
  8880. /************** End of pager.h ***********************************************/
  8881. /************** Continuing where we left off in sqliteInt.h ******************/
  8882. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  8883. /************** Begin file pcache.h ******************************************/
  8884. /*
  8885. ** 2008 August 05
  8886. **
  8887. ** The author disclaims copyright to this source code. In place of
  8888. ** a legal notice, here is a blessing:
  8889. **
  8890. ** May you do good and not evil.
  8891. ** May you find forgiveness for yourself and forgive others.
  8892. ** May you share freely, never taking more than you give.
  8893. **
  8894. *************************************************************************
  8895. ** This header file defines the interface that the sqlite page cache
  8896. ** subsystem.
  8897. */
  8898. #ifndef _PCACHE_H_
  8899. typedef struct PgHdr PgHdr;
  8900. typedef struct PCache PCache;
  8901. /*
  8902. ** Every page in the cache is controlled by an instance of the following
  8903. ** structure.
  8904. */
  8905. struct PgHdr {
  8906. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  8907. void *pData; /* Page data */
  8908. void *pExtra; /* Extra content */
  8909. PgHdr *pDirty; /* Transient list of dirty pages */
  8910. Pager *pPager; /* The pager this page is part of */
  8911. Pgno pgno; /* Page number for this page */
  8912. #ifdef SQLITE_CHECK_PAGES
  8913. u32 pageHash; /* Hash of page content */
  8914. #endif
  8915. u16 flags; /* PGHDR flags defined below */
  8916. /**********************************************************************
  8917. ** Elements above are public. All that follows is private to pcache.c
  8918. ** and should not be accessed by other modules.
  8919. */
  8920. i16 nRef; /* Number of users of this page */
  8921. PCache *pCache; /* Cache that owns this page */
  8922. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  8923. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  8924. };
  8925. /* Bit values for PgHdr.flags */
  8926. #define PGHDR_DIRTY 0x002 /* Page has changed */
  8927. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  8928. ** writing this page to the database */
  8929. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  8930. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  8931. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  8932. /* Initialize and shutdown the page cache subsystem */
  8933. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  8934. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  8935. /* Page cache buffer management:
  8936. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  8937. */
  8938. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  8939. /* Create a new pager cache.
  8940. ** Under memory stress, invoke xStress to try to make pages clean.
  8941. ** Only clean and unpinned pages can be reclaimed.
  8942. */
  8943. SQLITE_PRIVATE void sqlite3PcacheOpen(
  8944. int szPage, /* Size of every page */
  8945. int szExtra, /* Extra space associated with each page */
  8946. int bPurgeable, /* True if pages are on backing store */
  8947. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  8948. void *pStress, /* Argument to xStress */
  8949. PCache *pToInit /* Preallocated space for the PCache */
  8950. );
  8951. /* Modify the page-size after the cache has been created. */
  8952. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  8953. /* Return the size in bytes of a PCache object. Used to preallocate
  8954. ** storage space.
  8955. */
  8956. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  8957. /* One release per successful fetch. Page is pinned until released.
  8958. ** Reference counted.
  8959. */
  8960. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  8961. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  8962. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  8963. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  8964. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  8965. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  8966. /* Change a page number. Used by incr-vacuum. */
  8967. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  8968. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  8969. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  8970. /* Get a list of all dirty pages in the cache, sorted by page number */
  8971. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  8972. /* Reset and close the cache object */
  8973. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  8974. /* Clear flags from pages of the page cache */
  8975. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  8976. /* Discard the contents of the cache */
  8977. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  8978. /* Return the total number of outstanding page references */
  8979. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  8980. /* Increment the reference count of an existing page */
  8981. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  8982. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  8983. /* Return the total number of pages stored in the cache */
  8984. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  8985. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  8986. /* Iterate through all dirty pages currently stored in the cache. This
  8987. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  8988. ** library is built.
  8989. */
  8990. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  8991. #endif
  8992. /* Set and get the suggested cache-size for the specified pager-cache.
  8993. **
  8994. ** If no global maximum is configured, then the system attempts to limit
  8995. ** the total number of pages cached by purgeable pager-caches to the sum
  8996. ** of the suggested cache-sizes.
  8997. */
  8998. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  8999. #ifdef SQLITE_TEST
  9000. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9001. #endif
  9002. /* Free up as much memory as possible from the page cache */
  9003. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9004. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9005. /* Try to return memory used by the pcache module to the main memory heap */
  9006. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9007. #endif
  9008. #ifdef SQLITE_TEST
  9009. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9010. #endif
  9011. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9012. #endif /* _PCACHE_H_ */
  9013. /************** End of pcache.h **********************************************/
  9014. /************** Continuing where we left off in sqliteInt.h ******************/
  9015. /************** Include os.h in the middle of sqliteInt.h ********************/
  9016. /************** Begin file os.h **********************************************/
  9017. /*
  9018. ** 2001 September 16
  9019. **
  9020. ** The author disclaims copyright to this source code. In place of
  9021. ** a legal notice, here is a blessing:
  9022. **
  9023. ** May you do good and not evil.
  9024. ** May you find forgiveness for yourself and forgive others.
  9025. ** May you share freely, never taking more than you give.
  9026. **
  9027. ******************************************************************************
  9028. **
  9029. ** This header file (together with is companion C source-code file
  9030. ** "os.c") attempt to abstract the underlying operating system so that
  9031. ** the SQLite library will work on both POSIX and windows systems.
  9032. **
  9033. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9034. ** being included by every source file.
  9035. */
  9036. #ifndef _SQLITE_OS_H_
  9037. #define _SQLITE_OS_H_
  9038. /*
  9039. ** Figure out if we are dealing with Unix, Windows, or some other
  9040. ** operating system. After the following block of preprocess macros,
  9041. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9042. ** will defined to either 1 or 0. One of the four will be 1. The other
  9043. ** three will be 0.
  9044. */
  9045. #if defined(SQLITE_OS_OTHER)
  9046. # if SQLITE_OS_OTHER==1
  9047. # undef SQLITE_OS_UNIX
  9048. # define SQLITE_OS_UNIX 0
  9049. # undef SQLITE_OS_WIN
  9050. # define SQLITE_OS_WIN 0
  9051. # else
  9052. # undef SQLITE_OS_OTHER
  9053. # endif
  9054. #endif
  9055. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9056. # define SQLITE_OS_OTHER 0
  9057. # ifndef SQLITE_OS_WIN
  9058. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9059. # define SQLITE_OS_WIN 1
  9060. # define SQLITE_OS_UNIX 0
  9061. # else
  9062. # define SQLITE_OS_WIN 0
  9063. # define SQLITE_OS_UNIX 1
  9064. # endif
  9065. # else
  9066. # define SQLITE_OS_UNIX 0
  9067. # endif
  9068. #else
  9069. # ifndef SQLITE_OS_WIN
  9070. # define SQLITE_OS_WIN 0
  9071. # endif
  9072. #endif
  9073. #if SQLITE_OS_WIN
  9074. # include <windows.h>
  9075. #endif
  9076. /*
  9077. ** Determine if we are dealing with Windows NT.
  9078. **
  9079. ** We ought to be able to determine if we are compiling for win98 or winNT
  9080. ** using the _WIN32_WINNT macro as follows:
  9081. **
  9082. ** #if defined(_WIN32_WINNT)
  9083. ** # define SQLITE_OS_WINNT 1
  9084. ** #else
  9085. ** # define SQLITE_OS_WINNT 0
  9086. ** #endif
  9087. **
  9088. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9089. ** so the above test does not work. We'll just assume that everything is
  9090. ** winNT unless the programmer explicitly says otherwise by setting
  9091. ** SQLITE_OS_WINNT to 0.
  9092. */
  9093. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9094. # define SQLITE_OS_WINNT 1
  9095. #endif
  9096. /*
  9097. ** Determine if we are dealing with WindowsCE - which has a much
  9098. ** reduced API.
  9099. */
  9100. #if defined(_WIN32_WCE)
  9101. # define SQLITE_OS_WINCE 1
  9102. #else
  9103. # define SQLITE_OS_WINCE 0
  9104. #endif
  9105. /*
  9106. ** Determine if we are dealing with WinRT, which provides only a subset of
  9107. ** the full Win32 API.
  9108. */
  9109. #if !defined(SQLITE_OS_WINRT)
  9110. # define SQLITE_OS_WINRT 0
  9111. #endif
  9112. /*
  9113. ** When compiled for WinCE or WinRT, there is no concept of the current
  9114. ** directory.
  9115. */
  9116. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  9117. # define SQLITE_CURDIR 1
  9118. #endif
  9119. /* If the SET_FULLSYNC macro is not defined above, then make it
  9120. ** a no-op
  9121. */
  9122. #ifndef SET_FULLSYNC
  9123. # define SET_FULLSYNC(x,y)
  9124. #endif
  9125. /*
  9126. ** The default size of a disk sector
  9127. */
  9128. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9129. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9130. #endif
  9131. /*
  9132. ** Temporary files are named starting with this prefix followed by 16 random
  9133. ** alphanumeric characters, and no file extension. They are stored in the
  9134. ** OS's standard temporary file directory, and are deleted prior to exit.
  9135. ** If sqlite is being embedded in another program, you may wish to change the
  9136. ** prefix to reflect your program's name, so that if your program exits
  9137. ** prematurely, old temporary files can be easily identified. This can be done
  9138. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9139. **
  9140. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9141. ** Mcafee started using SQLite in their anti-virus product and it
  9142. ** started putting files with the "sqlite" name in the c:/temp folder.
  9143. ** This annoyed many windows users. Those users would then do a
  9144. ** Google search for "sqlite", find the telephone numbers of the
  9145. ** developers and call to wake them up at night and complain.
  9146. ** For this reason, the default name prefix is changed to be "sqlite"
  9147. ** spelled backwards. So the temp files are still identified, but
  9148. ** anybody smart enough to figure out the code is also likely smart
  9149. ** enough to know that calling the developer will not help get rid
  9150. ** of the file.
  9151. */
  9152. #ifndef SQLITE_TEMP_FILE_PREFIX
  9153. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9154. #endif
  9155. /*
  9156. ** The following values may be passed as the second argument to
  9157. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9158. **
  9159. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9160. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9161. ** any time. Other processes may hold and obtain new SHARED locks.
  9162. ** PENDING: A single process may hold a PENDING lock on a file at
  9163. ** any one time. Existing SHARED locks may persist, but no new
  9164. ** SHARED locks may be obtained by other processes.
  9165. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9166. **
  9167. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9168. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9169. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9170. ** sqlite3OsLock().
  9171. */
  9172. #define NO_LOCK 0
  9173. #define SHARED_LOCK 1
  9174. #define RESERVED_LOCK 2
  9175. #define PENDING_LOCK 3
  9176. #define EXCLUSIVE_LOCK 4
  9177. /*
  9178. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9179. **
  9180. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9181. ** those functions are not available. So we use only LockFile() and
  9182. ** UnlockFile().
  9183. **
  9184. ** LockFile() prevents not just writing but also reading by other processes.
  9185. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9186. ** byte out of a specific range of bytes. The lock byte is obtained at
  9187. ** random so two separate readers can probably access the file at the
  9188. ** same time, unless they are unlucky and choose the same lock byte.
  9189. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9190. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9191. ** a single byte of the file that is designated as the reserved lock byte.
  9192. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9193. ** the RESERVED_LOCK byte.
  9194. **
  9195. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9196. ** which means we can use reader/writer locks. When reader/writer locks
  9197. ** are used, the lock is placed on the same range of bytes that is used
  9198. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9199. ** will support two or more Win95 readers or two or more WinNT readers.
  9200. ** But a single Win95 reader will lock out all WinNT readers and a single
  9201. ** WinNT reader will lock out all other Win95 readers.
  9202. **
  9203. ** The following #defines specify the range of bytes used for locking.
  9204. ** SHARED_SIZE is the number of bytes available in the pool from which
  9205. ** a random byte is selected for a shared lock. The pool of bytes for
  9206. ** shared locks begins at SHARED_FIRST.
  9207. **
  9208. ** The same locking strategy and
  9209. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9210. ** clients on win95, winNT, and unix all talking to the same shared file
  9211. ** and all locking correctly. To do so would require that samba (or whatever
  9212. ** tool is being used for file sharing) implements locks correctly between
  9213. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9214. ** using the same locking range we are at least open to the possibility.
  9215. **
  9216. ** Locking in windows is manditory. For this reason, we cannot store
  9217. ** actual data in the bytes used for locking. The pager never allocates
  9218. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9219. ** that all locks will fit on a single page even at the minimum page size.
  9220. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9221. ** is set high so that we don't have to allocate an unused page except
  9222. ** for very large databases. But one should test the page skipping logic
  9223. ** by setting PENDING_BYTE low and running the entire regression suite.
  9224. **
  9225. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9226. ** file format. Depending on how it is changed, you might not notice
  9227. ** the incompatibility right away, even running a full regression test.
  9228. ** The default location of PENDING_BYTE is the first byte past the
  9229. ** 1GB boundary.
  9230. **
  9231. */
  9232. #ifdef SQLITE_OMIT_WSD
  9233. # define PENDING_BYTE (0x40000000)
  9234. #else
  9235. # define PENDING_BYTE sqlite3PendingByte
  9236. #endif
  9237. #define RESERVED_BYTE (PENDING_BYTE+1)
  9238. #define SHARED_FIRST (PENDING_BYTE+2)
  9239. #define SHARED_SIZE 510
  9240. /*
  9241. ** Wrapper around OS specific sqlite3_os_init() function.
  9242. */
  9243. SQLITE_PRIVATE int sqlite3OsInit(void);
  9244. /*
  9245. ** Functions for accessing sqlite3_file methods
  9246. */
  9247. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9248. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9249. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9250. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9251. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9252. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9253. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9254. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9255. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9256. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9257. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9258. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9259. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9260. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9261. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9262. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9263. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9264. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9265. /*
  9266. ** Functions for accessing sqlite3_vfs methods
  9267. */
  9268. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9269. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9270. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9271. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9272. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9273. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9274. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9275. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9276. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9277. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9278. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9279. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9280. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9281. /*
  9282. ** Convenience functions for opening and closing files using
  9283. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9284. */
  9285. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9286. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9287. #endif /* _SQLITE_OS_H_ */
  9288. /************** End of os.h **************************************************/
  9289. /************** Continuing where we left off in sqliteInt.h ******************/
  9290. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9291. /************** Begin file mutex.h *******************************************/
  9292. /*
  9293. ** 2007 August 28
  9294. **
  9295. ** The author disclaims copyright to this source code. In place of
  9296. ** a legal notice, here is a blessing:
  9297. **
  9298. ** May you do good and not evil.
  9299. ** May you find forgiveness for yourself and forgive others.
  9300. ** May you share freely, never taking more than you give.
  9301. **
  9302. *************************************************************************
  9303. **
  9304. ** This file contains the common header for all mutex implementations.
  9305. ** The sqliteInt.h header #includes this file so that it is available
  9306. ** to all source files. We break it out in an effort to keep the code
  9307. ** better organized.
  9308. **
  9309. ** NOTE: source files should *not* #include this header file directly.
  9310. ** Source files should #include the sqliteInt.h file and let that file
  9311. ** include this one indirectly.
  9312. */
  9313. /*
  9314. ** Figure out what version of the code to use. The choices are
  9315. **
  9316. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9317. ** mutexes implemention cannot be overridden
  9318. ** at start-time.
  9319. **
  9320. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9321. ** mutual exclusion is provided. But this
  9322. ** implementation can be overridden at
  9323. ** start-time.
  9324. **
  9325. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9326. **
  9327. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9328. */
  9329. #if !SQLITE_THREADSAFE
  9330. # define SQLITE_MUTEX_OMIT
  9331. #endif
  9332. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9333. # if SQLITE_OS_UNIX
  9334. # define SQLITE_MUTEX_PTHREADS
  9335. # elif SQLITE_OS_WIN
  9336. # define SQLITE_MUTEX_W32
  9337. # else
  9338. # define SQLITE_MUTEX_NOOP
  9339. # endif
  9340. #endif
  9341. #ifdef SQLITE_MUTEX_OMIT
  9342. /*
  9343. ** If this is a no-op implementation, implement everything as macros.
  9344. */
  9345. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9346. #define sqlite3_mutex_free(X)
  9347. #define sqlite3_mutex_enter(X)
  9348. #define sqlite3_mutex_try(X) SQLITE_OK
  9349. #define sqlite3_mutex_leave(X)
  9350. #define sqlite3_mutex_held(X) ((void)(X),1)
  9351. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9352. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9353. #define sqlite3MutexInit() SQLITE_OK
  9354. #define sqlite3MutexEnd()
  9355. #define MUTEX_LOGIC(X)
  9356. #else
  9357. #define MUTEX_LOGIC(X) X
  9358. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9359. /************** End of mutex.h ***********************************************/
  9360. /************** Continuing where we left off in sqliteInt.h ******************/
  9361. /*
  9362. ** Each database file to be accessed by the system is an instance
  9363. ** of the following structure. There are normally two of these structures
  9364. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9365. ** aDb[1] is the database file used to hold temporary tables. Additional
  9366. ** databases may be attached.
  9367. */
  9368. struct Db {
  9369. char *zName; /* Name of this database */
  9370. Btree *pBt; /* The B*Tree structure for this database file */
  9371. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  9372. u8 safety_level; /* How aggressive at syncing data to disk */
  9373. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9374. };
  9375. /*
  9376. ** An instance of the following structure stores a database schema.
  9377. **
  9378. ** Most Schema objects are associated with a Btree. The exception is
  9379. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9380. ** In shared cache mode, a single Schema object can be shared by multiple
  9381. ** Btrees that refer to the same underlying BtShared object.
  9382. **
  9383. ** Schema objects are automatically deallocated when the last Btree that
  9384. ** references them is destroyed. The TEMP Schema is manually freed by
  9385. ** sqlite3_close().
  9386. *
  9387. ** A thread must be holding a mutex on the corresponding Btree in order
  9388. ** to access Schema content. This implies that the thread must also be
  9389. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9390. ** For a TEMP Schema, only the connection mutex is required.
  9391. */
  9392. struct Schema {
  9393. int schema_cookie; /* Database schema version number for this file */
  9394. int iGeneration; /* Generation counter. Incremented with each change */
  9395. Hash tblHash; /* All tables indexed by name */
  9396. Hash idxHash; /* All (named) indices indexed by name */
  9397. Hash trigHash; /* All triggers indexed by name */
  9398. Hash fkeyHash; /* All foreign keys by referenced table name */
  9399. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9400. u8 file_format; /* Schema format version for this file */
  9401. u8 enc; /* Text encoding used by this database */
  9402. u16 flags; /* Flags associated with this schema */
  9403. int cache_size; /* Number of pages to use in the cache */
  9404. };
  9405. /*
  9406. ** These macros can be used to test, set, or clear bits in the
  9407. ** Db.pSchema->flags field.
  9408. */
  9409. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9410. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9411. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9412. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9413. /*
  9414. ** Allowed values for the DB.pSchema->flags field.
  9415. **
  9416. ** The DB_SchemaLoaded flag is set after the database schema has been
  9417. ** read into internal hash tables.
  9418. **
  9419. ** DB_UnresetViews means that one or more views have column names that
  9420. ** have been filled out. If the schema changes, these column names might
  9421. ** changes and so the view will need to be reset.
  9422. */
  9423. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9424. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9425. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9426. /*
  9427. ** The number of different kinds of things that can be limited
  9428. ** using the sqlite3_limit() interface.
  9429. */
  9430. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9431. /*
  9432. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9433. ** to satisfy small transient memory allocation requests for objects
  9434. ** associated with a particular database connection. The use of
  9435. ** lookaside malloc provides a significant performance enhancement
  9436. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9437. ** SQL statements.
  9438. **
  9439. ** The Lookaside structure holds configuration information about the
  9440. ** lookaside malloc subsystem. Each available memory allocation in
  9441. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9442. ** objects.
  9443. **
  9444. ** Lookaside allocations are only allowed for objects that are associated
  9445. ** with a particular database connection. Hence, schema information cannot
  9446. ** be stored in lookaside because in shared cache mode the schema information
  9447. ** is shared by multiple database connections. Therefore, while parsing
  9448. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9449. ** lookaside allocations are not used to construct the schema objects.
  9450. */
  9451. struct Lookaside {
  9452. u16 sz; /* Size of each buffer in bytes */
  9453. u8 bEnabled; /* False to disable new lookaside allocations */
  9454. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9455. int nOut; /* Number of buffers currently checked out */
  9456. int mxOut; /* Highwater mark for nOut */
  9457. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9458. LookasideSlot *pFree; /* List of available buffers */
  9459. void *pStart; /* First byte of available memory space */
  9460. void *pEnd; /* First byte past end of available space */
  9461. };
  9462. struct LookasideSlot {
  9463. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9464. };
  9465. /*
  9466. ** A hash table for function definitions.
  9467. **
  9468. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9469. ** Collisions are on the FuncDef.pHash chain.
  9470. */
  9471. struct FuncDefHash {
  9472. FuncDef *a[23]; /* Hash table for functions */
  9473. };
  9474. /*
  9475. ** Each database connection is an instance of the following structure.
  9476. */
  9477. struct sqlite3 {
  9478. sqlite3_vfs *pVfs; /* OS Interface */
  9479. struct Vdbe *pVdbe; /* List of active virtual machines */
  9480. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9481. sqlite3_mutex *mutex; /* Connection mutex */
  9482. Db *aDb; /* All backends */
  9483. int nDb; /* Number of backends currently in use */
  9484. int flags; /* Miscellaneous flags. See below */
  9485. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9486. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9487. int errCode; /* Most recent error code (SQLITE_*) */
  9488. int errMask; /* & result codes with this before returning */
  9489. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9490. u8 autoCommit; /* The auto-commit flag. */
  9491. u8 temp_store; /* 1: file 2: memory 0: default */
  9492. u8 mallocFailed; /* True if we have seen a malloc failure */
  9493. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9494. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9495. u8 suppressErr; /* Do not issue error messages if true */
  9496. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9497. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9498. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9499. u32 magic; /* Magic number for detect library misuse */
  9500. int nChange; /* Value returned by sqlite3_changes() */
  9501. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9502. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9503. struct sqlite3InitInfo { /* Information used during initialization */
  9504. int newTnum; /* Rootpage of table being initialized */
  9505. u8 iDb; /* Which db file is being initialized */
  9506. u8 busy; /* TRUE if currently initializing */
  9507. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9508. } init;
  9509. int activeVdbeCnt; /* Number of VDBEs currently executing */
  9510. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  9511. int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
  9512. int nExtension; /* Number of loaded extensions */
  9513. void **aExtension; /* Array of shared library handles */
  9514. void (*xTrace)(void*,const char*); /* Trace function */
  9515. void *pTraceArg; /* Argument to the trace function */
  9516. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9517. void *pProfileArg; /* Argument to profile function */
  9518. void *pCommitArg; /* Argument to xCommitCallback() */
  9519. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9520. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9521. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9522. void *pUpdateArg;
  9523. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9524. #ifndef SQLITE_OMIT_WAL
  9525. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9526. void *pWalArg;
  9527. #endif
  9528. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9529. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9530. void *pCollNeededArg;
  9531. sqlite3_value *pErr; /* Most recent error message */
  9532. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  9533. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  9534. union {
  9535. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9536. double notUsed1; /* Spacer */
  9537. } u1;
  9538. Lookaside lookaside; /* Lookaside malloc configuration */
  9539. #ifndef SQLITE_OMIT_AUTHORIZATION
  9540. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9541. /* Access authorization function */
  9542. void *pAuthArg; /* 1st argument to the access auth function */
  9543. #endif
  9544. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9545. int (*xProgress)(void *); /* The progress callback */
  9546. void *pProgressArg; /* Argument to the progress callback */
  9547. int nProgressOps; /* Number of opcodes for progress callback */
  9548. #endif
  9549. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9550. int nVTrans; /* Allocated size of aVTrans */
  9551. Hash aModule; /* populated by sqlite3_create_module() */
  9552. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9553. VTable **aVTrans; /* Virtual tables with open transactions */
  9554. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9555. #endif
  9556. FuncDefHash aFunc; /* Hash table of connection functions */
  9557. Hash aCollSeq; /* All collating sequences */
  9558. BusyHandler busyHandler; /* Busy callback */
  9559. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9560. Savepoint *pSavepoint; /* List of active savepoints */
  9561. int busyTimeout; /* Busy handler timeout, in msec */
  9562. int nSavepoint; /* Number of non-transaction savepoints */
  9563. int nStatement; /* Number of nested statement-transactions */
  9564. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9565. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9566. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9567. /* The following variables are all protected by the STATIC_MASTER
  9568. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9569. **
  9570. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9571. ** unlock so that it can proceed.
  9572. **
  9573. ** When X.pBlockingConnection==Y, that means that something that X tried
  9574. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9575. ** held by Y.
  9576. */
  9577. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9578. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9579. void *pUnlockArg; /* Argument to xUnlockNotify */
  9580. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9581. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9582. #endif
  9583. };
  9584. /*
  9585. ** A macro to discover the encoding of a database.
  9586. */
  9587. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9588. /*
  9589. ** Possible values for the sqlite3.flags.
  9590. */
  9591. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9592. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9593. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  9594. #define SQLITE_ShortColNames 0x00000008 /* Show short columns names */
  9595. #define SQLITE_CountRows 0x00000010 /* Count rows changed by INSERT, */
  9596. /* DELETE, or UPDATE and return */
  9597. /* the count using a callback. */
  9598. #define SQLITE_NullCallback 0x00000020 /* Invoke the callback once if the */
  9599. /* result set is empty */
  9600. #define SQLITE_SqlTrace 0x00000040 /* Debug print SQL as it executes */
  9601. #define SQLITE_VdbeListing 0x00000080 /* Debug listings of VDBE programs */
  9602. #define SQLITE_WriteSchema 0x00000100 /* OK to update SQLITE_MASTER */
  9603. /* 0x00000200 Unused */
  9604. #define SQLITE_IgnoreChecks 0x00000400 /* Do not enforce check constraints */
  9605. #define SQLITE_ReadUncommitted 0x0000800 /* For shared-cache mode */
  9606. #define SQLITE_LegacyFileFmt 0x00001000 /* Create new databases in format 1 */
  9607. #define SQLITE_FullFSync 0x00002000 /* Use full fsync on the backend */
  9608. #define SQLITE_CkptFullFSync 0x00004000 /* Use full fsync for checkpoint */
  9609. #define SQLITE_RecoveryMode 0x00008000 /* Ignore schema errors */
  9610. #define SQLITE_ReverseOrder 0x00010000 /* Reverse unordered SELECTs */
  9611. #define SQLITE_RecTriggers 0x00020000 /* Enable recursive triggers */
  9612. #define SQLITE_ForeignKeys 0x00040000 /* Enforce foreign key constraints */
  9613. #define SQLITE_AutoIndex 0x00080000 /* Enable automatic indexes */
  9614. #define SQLITE_PreferBuiltin 0x00100000 /* Preference to built-in funcs */
  9615. #define SQLITE_LoadExtension 0x00200000 /* Enable load_extension */
  9616. #define SQLITE_EnableTrigger 0x00400000 /* True to enable triggers */
  9617. /*
  9618. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9619. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9620. ** selectively disable various optimizations.
  9621. */
  9622. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9623. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9624. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9625. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9626. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9627. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9628. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9629. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9630. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9631. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9632. /*
  9633. ** Macros for testing whether or not optimizations are enabled or disabled.
  9634. */
  9635. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9636. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9637. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9638. #else
  9639. #define OptimizationDisabled(db, mask) 0
  9640. #define OptimizationEnabled(db, mask) 1
  9641. #endif
  9642. /*
  9643. ** Possible values for the sqlite.magic field.
  9644. ** The numbers are obtained at random and have no special meaning, other
  9645. ** than being distinct from one another.
  9646. */
  9647. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9648. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9649. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9650. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9651. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9652. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9653. /*
  9654. ** Each SQL function is defined by an instance of the following
  9655. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9656. ** hash table. When multiple functions have the same name, the hash table
  9657. ** points to a linked list of these structures.
  9658. */
  9659. struct FuncDef {
  9660. i16 nArg; /* Number of arguments. -1 means unlimited */
  9661. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  9662. u8 flags; /* Some combination of SQLITE_FUNC_* */
  9663. void *pUserData; /* User data parameter */
  9664. FuncDef *pNext; /* Next function with same name */
  9665. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9666. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9667. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9668. char *zName; /* SQL name of the function. */
  9669. FuncDef *pHash; /* Next with a different name but the same hash */
  9670. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9671. };
  9672. /*
  9673. ** This structure encapsulates a user-function destructor callback (as
  9674. ** configured using create_function_v2()) and a reference counter. When
  9675. ** create_function_v2() is called to create a function with a destructor,
  9676. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9677. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9678. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9679. ** member of each of the new FuncDef objects is set to point to the allocated
  9680. ** FuncDestructor.
  9681. **
  9682. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9683. ** count on this object is decremented. When it reaches 0, the destructor
  9684. ** is invoked and the FuncDestructor structure freed.
  9685. */
  9686. struct FuncDestructor {
  9687. int nRef;
  9688. void (*xDestroy)(void *);
  9689. void *pUserData;
  9690. };
  9691. /*
  9692. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9693. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9694. ** are assert() statements in the code to verify this.
  9695. */
  9696. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  9697. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  9698. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  9699. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  9700. #define SQLITE_FUNC_COUNT 0x10 /* Built-in count(*) aggregate */
  9701. #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
  9702. #define SQLITE_FUNC_LENGTH 0x40 /* Built-in length() function */
  9703. #define SQLITE_FUNC_TYPEOF 0x80 /* Built-in typeof() function */
  9704. /*
  9705. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9706. ** used to create the initializers for the FuncDef structures.
  9707. **
  9708. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9709. ** Used to create a scalar function definition of a function zName
  9710. ** implemented by C function xFunc that accepts nArg arguments. The
  9711. ** value passed as iArg is cast to a (void*) and made available
  9712. ** as the user-data (sqlite3_user_data()) for the function. If
  9713. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9714. **
  9715. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9716. ** Used to create an aggregate function definition implemented by
  9717. ** the C functions xStep and xFinal. The first four parameters
  9718. ** are interpreted in the same way as the first 4 parameters to
  9719. ** FUNCTION().
  9720. **
  9721. ** LIKEFUNC(zName, nArg, pArg, flags)
  9722. ** Used to create a scalar function definition of a function zName
  9723. ** that accepts nArg arguments and is implemented by a call to C
  9724. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9725. ** available as the function user-data (sqlite3_user_data()). The
  9726. ** FuncDef.flags variable is set to the value passed as the flags
  9727. ** parameter.
  9728. */
  9729. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9730. {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
  9731. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9732. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  9733. {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  9734. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9735. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9736. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  9737. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9738. #define LIKEFUNC(zName, nArg, arg, flags) \
  9739. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9740. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9741. {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
  9742. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9743. /*
  9744. ** All current savepoints are stored in a linked list starting at
  9745. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9746. ** opened savepoint. Savepoints are added to the list by the vdbe
  9747. ** OP_Savepoint instruction.
  9748. */
  9749. struct Savepoint {
  9750. char *zName; /* Savepoint name (nul-terminated) */
  9751. i64 nDeferredCons; /* Number of deferred fk violations */
  9752. Savepoint *pNext; /* Parent savepoint (if any) */
  9753. };
  9754. /*
  9755. ** The following are used as the second parameter to sqlite3Savepoint(),
  9756. ** and as the P1 argument to the OP_Savepoint instruction.
  9757. */
  9758. #define SAVEPOINT_BEGIN 0
  9759. #define SAVEPOINT_RELEASE 1
  9760. #define SAVEPOINT_ROLLBACK 2
  9761. /*
  9762. ** Each SQLite module (virtual table definition) is defined by an
  9763. ** instance of the following structure, stored in the sqlite3.aModule
  9764. ** hash table.
  9765. */
  9766. struct Module {
  9767. const sqlite3_module *pModule; /* Callback pointers */
  9768. const char *zName; /* Name passed to create_module() */
  9769. void *pAux; /* pAux passed to create_module() */
  9770. void (*xDestroy)(void *); /* Module destructor function */
  9771. };
  9772. /*
  9773. ** information about each column of an SQL table is held in an instance
  9774. ** of this structure.
  9775. */
  9776. struct Column {
  9777. char *zName; /* Name of this column */
  9778. Expr *pDflt; /* Default value of this column */
  9779. char *zDflt; /* Original text of the default value */
  9780. char *zType; /* Data type for this column */
  9781. char *zColl; /* Collating sequence. If NULL, use the default */
  9782. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  9783. char affinity; /* One of the SQLITE_AFF_... values */
  9784. u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  9785. };
  9786. /* Allowed values for Column.colFlags:
  9787. */
  9788. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  9789. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  9790. /*
  9791. ** A "Collating Sequence" is defined by an instance of the following
  9792. ** structure. Conceptually, a collating sequence consists of a name and
  9793. ** a comparison routine that defines the order of that sequence.
  9794. **
  9795. ** If CollSeq.xCmp is NULL, it means that the
  9796. ** collating sequence is undefined. Indices built on an undefined
  9797. ** collating sequence may not be read or written.
  9798. */
  9799. struct CollSeq {
  9800. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  9801. u8 enc; /* Text encoding handled by xCmp() */
  9802. void *pUser; /* First argument to xCmp() */
  9803. int (*xCmp)(void*,int, const void*, int, const void*);
  9804. void (*xDel)(void*); /* Destructor for pUser */
  9805. };
  9806. /*
  9807. ** A sort order can be either ASC or DESC.
  9808. */
  9809. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  9810. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  9811. /*
  9812. ** Column affinity types.
  9813. **
  9814. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  9815. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  9816. ** the speed a little by numbering the values consecutively.
  9817. **
  9818. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  9819. ** when multiple affinity types are concatenated into a string and
  9820. ** used as the P4 operand, they will be more readable.
  9821. **
  9822. ** Note also that the numeric types are grouped together so that testing
  9823. ** for a numeric type is a single comparison.
  9824. */
  9825. #define SQLITE_AFF_TEXT 'a'
  9826. #define SQLITE_AFF_NONE 'b'
  9827. #define SQLITE_AFF_NUMERIC 'c'
  9828. #define SQLITE_AFF_INTEGER 'd'
  9829. #define SQLITE_AFF_REAL 'e'
  9830. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  9831. /*
  9832. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  9833. ** affinity value.
  9834. */
  9835. #define SQLITE_AFF_MASK 0x67
  9836. /*
  9837. ** Additional bit values that can be ORed with an affinity without
  9838. ** changing the affinity.
  9839. */
  9840. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  9841. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  9842. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  9843. /*
  9844. ** An object of this type is created for each virtual table present in
  9845. ** the database schema.
  9846. **
  9847. ** If the database schema is shared, then there is one instance of this
  9848. ** structure for each database connection (sqlite3*) that uses the shared
  9849. ** schema. This is because each database connection requires its own unique
  9850. ** instance of the sqlite3_vtab* handle used to access the virtual table
  9851. ** implementation. sqlite3_vtab* handles can not be shared between
  9852. ** database connections, even when the rest of the in-memory database
  9853. ** schema is shared, as the implementation often stores the database
  9854. ** connection handle passed to it via the xConnect() or xCreate() method
  9855. ** during initialization internally. This database connection handle may
  9856. ** then be used by the virtual table implementation to access real tables
  9857. ** within the database. So that they appear as part of the callers
  9858. ** transaction, these accesses need to be made via the same database
  9859. ** connection as that used to execute SQL operations on the virtual table.
  9860. **
  9861. ** All VTable objects that correspond to a single table in a shared
  9862. ** database schema are initially stored in a linked-list pointed to by
  9863. ** the Table.pVTable member variable of the corresponding Table object.
  9864. ** When an sqlite3_prepare() operation is required to access the virtual
  9865. ** table, it searches the list for the VTable that corresponds to the
  9866. ** database connection doing the preparing so as to use the correct
  9867. ** sqlite3_vtab* handle in the compiled query.
  9868. **
  9869. ** When an in-memory Table object is deleted (for example when the
  9870. ** schema is being reloaded for some reason), the VTable objects are not
  9871. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  9872. ** immediately. Instead, they are moved from the Table.pVTable list to
  9873. ** another linked list headed by the sqlite3.pDisconnect member of the
  9874. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  9875. ** next time a statement is prepared using said sqlite3*. This is done
  9876. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  9877. ** Refer to comments above function sqlite3VtabUnlockList() for an
  9878. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  9879. ** list without holding the corresponding sqlite3.mutex mutex.
  9880. **
  9881. ** The memory for objects of this type is always allocated by
  9882. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  9883. ** the first argument.
  9884. */
  9885. struct VTable {
  9886. sqlite3 *db; /* Database connection associated with this table */
  9887. Module *pMod; /* Pointer to module implementation */
  9888. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  9889. int nRef; /* Number of pointers to this structure */
  9890. u8 bConstraint; /* True if constraints are supported */
  9891. int iSavepoint; /* Depth of the SAVEPOINT stack */
  9892. VTable *pNext; /* Next in linked list (see above) */
  9893. };
  9894. /*
  9895. ** Each SQL table is represented in memory by an instance of the
  9896. ** following structure.
  9897. **
  9898. ** Table.zName is the name of the table. The case of the original
  9899. ** CREATE TABLE statement is stored, but case is not significant for
  9900. ** comparisons.
  9901. **
  9902. ** Table.nCol is the number of columns in this table. Table.aCol is a
  9903. ** pointer to an array of Column structures, one for each column.
  9904. **
  9905. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  9906. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  9907. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  9908. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  9909. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  9910. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  9911. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  9912. **
  9913. ** Table.tnum is the page number for the root BTree page of the table in the
  9914. ** database file. If Table.iDb is the index of the database table backend
  9915. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  9916. ** holds temporary tables and indices. If TF_Ephemeral is set
  9917. ** then the table is stored in a file that is automatically deleted
  9918. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  9919. ** refers VDBE cursor number that holds the table open, not to the root
  9920. ** page number. Transient tables are used to hold the results of a
  9921. ** sub-query that appears instead of a real table name in the FROM clause
  9922. ** of a SELECT statement.
  9923. */
  9924. struct Table {
  9925. char *zName; /* Name of the table or view */
  9926. Column *aCol; /* Information about each column */
  9927. Index *pIndex; /* List of SQL indexes on this table. */
  9928. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  9929. FKey *pFKey; /* Linked list of all foreign keys in this table */
  9930. char *zColAff; /* String defining the affinity of each column */
  9931. #ifndef SQLITE_OMIT_CHECK
  9932. ExprList *pCheck; /* All CHECK constraints */
  9933. #endif
  9934. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  9935. int tnum; /* Root BTree node for this table (see note above) */
  9936. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  9937. i16 nCol; /* Number of columns in this table */
  9938. u16 nRef; /* Number of pointers to this Table */
  9939. u8 tabFlags; /* Mask of TF_* values */
  9940. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  9941. #ifndef SQLITE_OMIT_ALTERTABLE
  9942. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  9943. #endif
  9944. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9945. int nModuleArg; /* Number of arguments to the module */
  9946. char **azModuleArg; /* Text of all module args. [0] is module name */
  9947. VTable *pVTable; /* List of VTable objects. */
  9948. #endif
  9949. Trigger *pTrigger; /* List of triggers stored in pSchema */
  9950. Schema *pSchema; /* Schema that contains this table */
  9951. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  9952. };
  9953. /*
  9954. ** Allowed values for Tabe.tabFlags.
  9955. */
  9956. #define TF_Readonly 0x01 /* Read-only system table */
  9957. #define TF_Ephemeral 0x02 /* An ephemeral table */
  9958. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  9959. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  9960. #define TF_Virtual 0x10 /* Is a virtual table */
  9961. /*
  9962. ** Test to see whether or not a table is a virtual table. This is
  9963. ** done as a macro so that it will be optimized out when virtual
  9964. ** table support is omitted from the build.
  9965. */
  9966. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9967. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  9968. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  9969. #else
  9970. # define IsVirtual(X) 0
  9971. # define IsHiddenColumn(X) 0
  9972. #endif
  9973. /*
  9974. ** Each foreign key constraint is an instance of the following structure.
  9975. **
  9976. ** A foreign key is associated with two tables. The "from" table is
  9977. ** the table that contains the REFERENCES clause that creates the foreign
  9978. ** key. The "to" table is the table that is named in the REFERENCES clause.
  9979. ** Consider this example:
  9980. **
  9981. ** CREATE TABLE ex1(
  9982. ** a INTEGER PRIMARY KEY,
  9983. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  9984. ** );
  9985. **
  9986. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  9987. **
  9988. ** Each REFERENCES clause generates an instance of the following structure
  9989. ** which is attached to the from-table. The to-table need not exist when
  9990. ** the from-table is created. The existence of the to-table is not checked.
  9991. */
  9992. struct FKey {
  9993. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  9994. FKey *pNextFrom; /* Next foreign key in pFrom */
  9995. char *zTo; /* Name of table that the key points to (aka: Parent) */
  9996. FKey *pNextTo; /* Next foreign key on table named zTo */
  9997. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  9998. int nCol; /* Number of columns in this key */
  9999. /* EV: R-30323-21917 */
  10000. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10001. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10002. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10003. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10004. int iFrom; /* Index of column in pFrom */
  10005. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10006. } aCol[1]; /* One entry for each of nCol column s */
  10007. };
  10008. /*
  10009. ** SQLite supports many different ways to resolve a constraint
  10010. ** error. ROLLBACK processing means that a constraint violation
  10011. ** causes the operation in process to fail and for the current transaction
  10012. ** to be rolled back. ABORT processing means the operation in process
  10013. ** fails and any prior changes from that one operation are backed out,
  10014. ** but the transaction is not rolled back. FAIL processing means that
  10015. ** the operation in progress stops and returns an error code. But prior
  10016. ** changes due to the same operation are not backed out and no rollback
  10017. ** occurs. IGNORE means that the particular row that caused the constraint
  10018. ** error is not inserted or updated. Processing continues and no error
  10019. ** is returned. REPLACE means that preexisting database rows that caused
  10020. ** a UNIQUE constraint violation are removed so that the new insert or
  10021. ** update can proceed. Processing continues and no error is reported.
  10022. **
  10023. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10024. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10025. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10026. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10027. ** referenced table row is propagated into the row that holds the
  10028. ** foreign key.
  10029. **
  10030. ** The following symbolic values are used to record which type
  10031. ** of action to take.
  10032. */
  10033. #define OE_None 0 /* There is no constraint to check */
  10034. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10035. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10036. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10037. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10038. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10039. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10040. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10041. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10042. #define OE_Cascade 9 /* Cascade the changes */
  10043. #define OE_Default 99 /* Do whatever the default action is */
  10044. /*
  10045. ** An instance of the following structure is passed as the first
  10046. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10047. ** comparison of the two index keys.
  10048. */
  10049. struct KeyInfo {
  10050. sqlite3 *db; /* The database connection */
  10051. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10052. u16 nField; /* Number of entries in aColl[] */
  10053. u8 *aSortOrder; /* Sort order for each column. May be NULL */
  10054. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10055. };
  10056. /*
  10057. ** An instance of the following structure holds information about a
  10058. ** single index record that has already been parsed out into individual
  10059. ** values.
  10060. **
  10061. ** A record is an object that contains one or more fields of data.
  10062. ** Records are used to store the content of a table row and to store
  10063. ** the key of an index. A blob encoding of a record is created by
  10064. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10065. ** OP_Column opcode.
  10066. **
  10067. ** This structure holds a record that has already been disassembled
  10068. ** into its constituent fields.
  10069. */
  10070. struct UnpackedRecord {
  10071. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10072. u16 nField; /* Number of entries in apMem[] */
  10073. u8 flags; /* Boolean settings. UNPACKED_... below */
  10074. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10075. Mem *aMem; /* Values */
  10076. };
  10077. /*
  10078. ** Allowed values of UnpackedRecord.flags
  10079. */
  10080. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10081. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10082. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10083. /*
  10084. ** Each SQL index is represented in memory by an
  10085. ** instance of the following structure.
  10086. **
  10087. ** The columns of the table that are to be indexed are described
  10088. ** by the aiColumn[] field of this structure. For example, suppose
  10089. ** we have the following table and index:
  10090. **
  10091. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10092. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10093. **
  10094. ** In the Table structure describing Ex1, nCol==3 because there are
  10095. ** three columns in the table. In the Index structure describing
  10096. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10097. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10098. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10099. ** The second column to be indexed (c1) has an index of 0 in
  10100. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10101. **
  10102. ** The Index.onError field determines whether or not the indexed columns
  10103. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10104. ** it means this is not a unique index. Otherwise it is a unique index
  10105. ** and the value of Index.onError indicate the which conflict resolution
  10106. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10107. ** element.
  10108. */
  10109. struct Index {
  10110. char *zName; /* Name of this index */
  10111. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10112. tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  10113. Table *pTable; /* The SQL table being indexed */
  10114. char *zColAff; /* String defining the affinity of each column */
  10115. Index *pNext; /* The next index associated with the same table */
  10116. Schema *pSchema; /* Schema containing this index */
  10117. u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
  10118. char **azColl; /* Array of collation sequence names for index */
  10119. int nColumn; /* Number of columns in the table used by this index */
  10120. int tnum; /* Page containing root of this index in database file */
  10121. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10122. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  10123. u8 bUnordered; /* Use this index for == or IN queries only */
  10124. #ifdef SQLITE_ENABLE_STAT3
  10125. int nSample; /* Number of elements in aSample[] */
  10126. tRowcnt avgEq; /* Average nEq value for key values not in aSample */
  10127. IndexSample *aSample; /* Samples of the left-most key */
  10128. #endif
  10129. };
  10130. /*
  10131. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10132. ** using a structure of this type. See documentation at the top of the
  10133. ** analyze.c source file for additional information.
  10134. */
  10135. struct IndexSample {
  10136. union {
  10137. char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
  10138. double r; /* Value if eType is SQLITE_FLOAT */
  10139. i64 i; /* Value if eType is SQLITE_INTEGER */
  10140. } u;
  10141. u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
  10142. int nByte; /* Size in byte of text or blob. */
  10143. tRowcnt nEq; /* Est. number of rows where the key equals this sample */
  10144. tRowcnt nLt; /* Est. number of rows where key is less than this sample */
  10145. tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
  10146. };
  10147. /*
  10148. ** Each token coming out of the lexer is an instance of
  10149. ** this structure. Tokens are also used as part of an expression.
  10150. **
  10151. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10152. ** may contain random values. Do not make any assumptions about Token.dyn
  10153. ** and Token.n when Token.z==0.
  10154. */
  10155. struct Token {
  10156. const char *z; /* Text of the token. Not NULL-terminated! */
  10157. unsigned int n; /* Number of characters in this token */
  10158. };
  10159. /*
  10160. ** An instance of this structure contains information needed to generate
  10161. ** code for a SELECT that contains aggregate functions.
  10162. **
  10163. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10164. ** pointer to this structure. The Expr.iColumn field is the index in
  10165. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10166. ** code for that node.
  10167. **
  10168. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10169. ** original Select structure that describes the SELECT statement. These
  10170. ** fields do not need to be freed when deallocating the AggInfo structure.
  10171. */
  10172. struct AggInfo {
  10173. u8 directMode; /* Direct rendering mode means take data directly
  10174. ** from source tables rather than from accumulators */
  10175. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10176. ** than the source table */
  10177. int sortingIdx; /* Cursor number of the sorting index */
  10178. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10179. int nSortingColumn; /* Number of columns in the sorting index */
  10180. ExprList *pGroupBy; /* The group by clause */
  10181. struct AggInfo_col { /* For each column used in source tables */
  10182. Table *pTab; /* Source table */
  10183. int iTable; /* Cursor number of the source table */
  10184. int iColumn; /* Column number within the source table */
  10185. int iSorterColumn; /* Column number in the sorting index */
  10186. int iMem; /* Memory location that acts as accumulator */
  10187. Expr *pExpr; /* The original expression */
  10188. } *aCol;
  10189. int nColumn; /* Number of used entries in aCol[] */
  10190. int nAccumulator; /* Number of columns that show through to the output.
  10191. ** Additional columns are used only as parameters to
  10192. ** aggregate functions */
  10193. struct AggInfo_func { /* For each aggregate function */
  10194. Expr *pExpr; /* Expression encoding the function */
  10195. FuncDef *pFunc; /* The aggregate function implementation */
  10196. int iMem; /* Memory location that acts as accumulator */
  10197. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10198. } *aFunc;
  10199. int nFunc; /* Number of entries in aFunc[] */
  10200. };
  10201. /*
  10202. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10203. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10204. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10205. ** it uses less memory in the Expr object, which is a big memory user
  10206. ** in systems with lots of prepared statements. And few applications
  10207. ** need more than about 10 or 20 variables. But some extreme users want
  10208. ** to have prepared statements with over 32767 variables, and for them
  10209. ** the option is available (at compile-time).
  10210. */
  10211. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10212. typedef i16 ynVar;
  10213. #else
  10214. typedef int ynVar;
  10215. #endif
  10216. /*
  10217. ** Each node of an expression in the parse tree is an instance
  10218. ** of this structure.
  10219. **
  10220. ** Expr.op is the opcode. The integer parser token codes are reused
  10221. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10222. ** code representing the ">=" operator. This same integer code is reused
  10223. ** to represent the greater-than-or-equal-to operator in the expression
  10224. ** tree.
  10225. **
  10226. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10227. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10228. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10229. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10230. ** then Expr.token contains the name of the function.
  10231. **
  10232. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10233. ** binary operator. Either or both may be NULL.
  10234. **
  10235. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10236. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10237. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10238. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10239. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10240. ** valid.
  10241. **
  10242. ** An expression of the form ID or ID.ID refers to a column in a table.
  10243. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10244. ** the integer cursor number of a VDBE cursor pointing to that table and
  10245. ** Expr.iColumn is the column number for the specific column. If the
  10246. ** expression is used as a result in an aggregate SELECT, then the
  10247. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10248. ** it can be accessed after all aggregates are computed.
  10249. **
  10250. ** If the expression is an unbound variable marker (a question mark
  10251. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10252. ** number for that variable.
  10253. **
  10254. ** If the expression is a subquery then Expr.iColumn holds an integer
  10255. ** register number containing the result of the subquery. If the
  10256. ** subquery gives a constant result, then iTable is -1. If the subquery
  10257. ** gives a different answer at different times during statement processing
  10258. ** then iTable is the address of a subroutine that computes the subquery.
  10259. **
  10260. ** If the Expr is of type OP_Column, and the table it is selecting from
  10261. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10262. ** corresponding table definition.
  10263. **
  10264. ** ALLOCATION NOTES:
  10265. **
  10266. ** Expr objects can use a lot of memory space in database schema. To
  10267. ** help reduce memory requirements, sometimes an Expr object will be
  10268. ** truncated. And to reduce the number of memory allocations, sometimes
  10269. ** two or more Expr objects will be stored in a single memory allocation,
  10270. ** together with Expr.zToken strings.
  10271. **
  10272. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10273. ** an Expr object is truncated. When EP_Reduced is set, then all
  10274. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10275. ** are contained within the same memory allocation. Note, however, that
  10276. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10277. ** allocated, regardless of whether or not EP_Reduced is set.
  10278. */
  10279. struct Expr {
  10280. u8 op; /* Operation performed by this node */
  10281. char affinity; /* The affinity of the column or 0 if not a column */
  10282. u16 flags; /* Various flags. EP_* See below */
  10283. union {
  10284. char *zToken; /* Token value. Zero terminated and dequoted */
  10285. int iValue; /* Non-negative integer value if EP_IntValue */
  10286. } u;
  10287. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10288. ** space is allocated for the fields below this point. An attempt to
  10289. ** access them will result in a segfault or malfunction.
  10290. *********************************************************************/
  10291. Expr *pLeft; /* Left subnode */
  10292. Expr *pRight; /* Right subnode */
  10293. union {
  10294. ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
  10295. Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
  10296. } x;
  10297. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10298. ** space is allocated for the fields below this point. An attempt to
  10299. ** access them will result in a segfault or malfunction.
  10300. *********************************************************************/
  10301. #if SQLITE_MAX_EXPR_DEPTH>0
  10302. int nHeight; /* Height of the tree headed by this node */
  10303. #endif
  10304. int iTable; /* TK_COLUMN: cursor number of table holding column
  10305. ** TK_REGISTER: register number
  10306. ** TK_TRIGGER: 1 -> new, 0 -> old */
  10307. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10308. ** TK_VARIABLE: variable number (always >= 1). */
  10309. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10310. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10311. u8 flags2; /* Second set of flags. EP2_... */
  10312. u8 op2; /* TK_REGISTER: original value of Expr.op
  10313. ** TK_COLUMN: the value of p5 for OP_Column
  10314. ** TK_AGG_FUNCTION: nesting depth */
  10315. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10316. Table *pTab; /* Table for TK_COLUMN expressions. */
  10317. };
  10318. /*
  10319. ** The following are the meanings of bits in the Expr.flags field.
  10320. */
  10321. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  10322. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  10323. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  10324. #define EP_Error 0x0008 /* Expression contains one or more errors */
  10325. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  10326. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  10327. #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
  10328. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  10329. #define EP_Collate 0x0100 /* Tree contains a TK_COLLATE opeartor */
  10330. #define EP_FixedDest 0x0200 /* Result needed in a specific register */
  10331. #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
  10332. #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
  10333. #define EP_Hint 0x1000 /* Not used */
  10334. #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
  10335. #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
  10336. #define EP_Static 0x8000 /* Held in memory not obtained from malloc() */
  10337. /*
  10338. ** The following are the meanings of bits in the Expr.flags2 field.
  10339. */
  10340. #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
  10341. #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
  10342. /*
  10343. ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
  10344. ** flag on an expression structure. This flag is used for VV&A only. The
  10345. ** routine is implemented as a macro that only works when in debugging mode,
  10346. ** so as not to burden production code.
  10347. */
  10348. #ifdef SQLITE_DEBUG
  10349. # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
  10350. #else
  10351. # define ExprSetIrreducible(X)
  10352. #endif
  10353. /*
  10354. ** These macros can be used to test, set, or clear bits in the
  10355. ** Expr.flags field.
  10356. */
  10357. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  10358. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  10359. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10360. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10361. /*
  10362. ** Macros to determine the number of bytes required by a normal Expr
  10363. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10364. ** and an Expr struct with the EP_TokenOnly flag set.
  10365. */
  10366. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10367. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10368. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10369. /*
  10370. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10371. ** above sqlite3ExprDup() for details.
  10372. */
  10373. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10374. /*
  10375. ** A list of expressions. Each expression may optionally have a
  10376. ** name. An expr/name combination can be used in several ways, such
  10377. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10378. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10379. ** also be used as the argument to a function, in which case the a.zName
  10380. ** field is not used.
  10381. */
  10382. struct ExprList {
  10383. int nExpr; /* Number of expressions on the list */
  10384. int iECursor; /* VDBE Cursor associated with this ExprList */
  10385. struct ExprList_item { /* For each expression in the list */
  10386. Expr *pExpr; /* The list of expressions */
  10387. char *zName; /* Token associated with this expression */
  10388. char *zSpan; /* Original text of the expression */
  10389. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10390. u8 done; /* A flag to indicate when processing is finished */
  10391. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10392. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10393. } *a; /* Alloc a power of two greater or equal to nExpr */
  10394. };
  10395. /*
  10396. ** An instance of this structure is used by the parser to record both
  10397. ** the parse tree for an expression and the span of input text for an
  10398. ** expression.
  10399. */
  10400. struct ExprSpan {
  10401. Expr *pExpr; /* The expression parse tree */
  10402. const char *zStart; /* First character of input text */
  10403. const char *zEnd; /* One character past the end of input text */
  10404. };
  10405. /*
  10406. ** An instance of this structure can hold a simple list of identifiers,
  10407. ** such as the list "a,b,c" in the following statements:
  10408. **
  10409. ** INSERT INTO t(a,b,c) VALUES ...;
  10410. ** CREATE INDEX idx ON t(a,b,c);
  10411. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10412. **
  10413. ** The IdList.a.idx field is used when the IdList represents the list of
  10414. ** column names after a table name in an INSERT statement. In the statement
  10415. **
  10416. ** INSERT INTO t(a,b,c) ...
  10417. **
  10418. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10419. */
  10420. struct IdList {
  10421. struct IdList_item {
  10422. char *zName; /* Name of the identifier */
  10423. int idx; /* Index in some Table.aCol[] of a column named zName */
  10424. } *a;
  10425. int nId; /* Number of identifiers on the list */
  10426. };
  10427. /*
  10428. ** The bitmask datatype defined below is used for various optimizations.
  10429. **
  10430. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10431. ** tables in a join to 32 instead of 64. But it also reduces the size
  10432. ** of the library by 738 bytes on ix86.
  10433. */
  10434. typedef u64 Bitmask;
  10435. /*
  10436. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10437. */
  10438. #define BMS ((int)(sizeof(Bitmask)*8))
  10439. /*
  10440. ** The following structure describes the FROM clause of a SELECT statement.
  10441. ** Each table or subquery in the FROM clause is a separate element of
  10442. ** the SrcList.a[] array.
  10443. **
  10444. ** With the addition of multiple database support, the following structure
  10445. ** can also be used to describe a particular table such as the table that
  10446. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10447. ** such a table must be a simple name: ID. But in SQLite, the table can
  10448. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10449. **
  10450. ** The jointype starts out showing the join type between the current table
  10451. ** and the next table on the list. The parser builds the list this way.
  10452. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10453. ** jointype expresses the join between the table and the previous table.
  10454. **
  10455. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10456. ** contains more than 63 columns and the 64-th or later column is used.
  10457. */
  10458. struct SrcList {
  10459. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  10460. i16 nAlloc; /* Number of entries allocated in a[] below */
  10461. struct SrcList_item {
  10462. Schema *pSchema; /* Schema to which this item is fixed */
  10463. char *zDatabase; /* Name of database holding this table */
  10464. char *zName; /* Name of the table */
  10465. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10466. Table *pTab; /* An SQL table corresponding to zName */
  10467. Select *pSelect; /* A SELECT statement used in place of a table name */
  10468. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10469. int regReturn; /* Register holding return address of addrFillSub */
  10470. u8 jointype; /* Type of join between this able and the previous */
  10471. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10472. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10473. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10474. #ifndef SQLITE_OMIT_EXPLAIN
  10475. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10476. #endif
  10477. int iCursor; /* The VDBE cursor number used to access this table */
  10478. Expr *pOn; /* The ON clause of a join */
  10479. IdList *pUsing; /* The USING clause of a join */
  10480. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10481. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10482. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10483. } a[1]; /* One entry for each identifier on the list */
  10484. };
  10485. /*
  10486. ** Permitted values of the SrcList.a.jointype field
  10487. */
  10488. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10489. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10490. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10491. #define JT_LEFT 0x0008 /* Left outer join */
  10492. #define JT_RIGHT 0x0010 /* Right outer join */
  10493. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10494. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10495. /*
  10496. ** A WherePlan object holds information that describes a lookup
  10497. ** strategy.
  10498. **
  10499. ** This object is intended to be opaque outside of the where.c module.
  10500. ** It is included here only so that that compiler will know how big it
  10501. ** is. None of the fields in this object should be used outside of
  10502. ** the where.c module.
  10503. **
  10504. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  10505. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  10506. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  10507. ** case that more than one of these conditions is true.
  10508. */
  10509. struct WherePlan {
  10510. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  10511. u16 nEq; /* Number of == constraints */
  10512. u16 nOBSat; /* Number of ORDER BY terms satisfied */
  10513. double nRow; /* Estimated number of rows (for EQP) */
  10514. union {
  10515. Index *pIdx; /* Index when WHERE_INDEXED is true */
  10516. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  10517. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  10518. } u;
  10519. };
  10520. /*
  10521. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  10522. ** structure contains a single instance of this structure. This structure
  10523. ** is intended to be private to the where.c module and should not be
  10524. ** access or modified by other modules.
  10525. **
  10526. ** The pIdxInfo field is used to help pick the best index on a
  10527. ** virtual table. The pIdxInfo pointer contains indexing
  10528. ** information for the i-th table in the FROM clause before reordering.
  10529. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  10530. ** All other information in the i-th WhereLevel object for the i-th table
  10531. ** after FROM clause ordering.
  10532. */
  10533. struct WhereLevel {
  10534. WherePlan plan; /* query plan for this element of the FROM clause */
  10535. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  10536. int iTabCur; /* The VDBE cursor used to access the table */
  10537. int iIdxCur; /* The VDBE cursor used to access pIdx */
  10538. int addrBrk; /* Jump here to break out of the loop */
  10539. int addrNxt; /* Jump here to start the next IN combination */
  10540. int addrCont; /* Jump here to continue with the next loop cycle */
  10541. int addrFirst; /* First instruction of interior of the loop */
  10542. u8 iFrom; /* Which entry in the FROM clause */
  10543. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  10544. int p1, p2; /* Operands of the opcode used to ends the loop */
  10545. union { /* Information that depends on plan.wsFlags */
  10546. struct {
  10547. int nIn; /* Number of entries in aInLoop[] */
  10548. struct InLoop {
  10549. int iCur; /* The VDBE cursor used by this IN operator */
  10550. int addrInTop; /* Top of the IN loop */
  10551. } *aInLoop; /* Information about each nested IN operator */
  10552. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  10553. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  10554. } u;
  10555. double rOptCost; /* "Optimal" cost for this level */
  10556. /* The following field is really not part of the current level. But
  10557. ** we need a place to cache virtual table index information for each
  10558. ** virtual table in the FROM clause and the WhereLevel structure is
  10559. ** a convenient place since there is one WhereLevel for each FROM clause
  10560. ** element.
  10561. */
  10562. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  10563. };
  10564. /*
  10565. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10566. ** and the WhereInfo.wctrlFlags member.
  10567. */
  10568. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10569. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10570. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10571. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10572. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10573. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10574. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10575. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10576. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10577. /*
  10578. ** The WHERE clause processing routine has two halves. The
  10579. ** first part does the start of the WHERE loop and the second
  10580. ** half does the tail of the WHERE loop. An instance of
  10581. ** this structure is returned by the first half and passed
  10582. ** into the second half to give some continuity.
  10583. */
  10584. struct WhereInfo {
  10585. Parse *pParse; /* Parsing and code generating context */
  10586. SrcList *pTabList; /* List of tables in the join */
  10587. u16 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  10588. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  10589. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  10590. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  10591. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  10592. int iTop; /* The very beginning of the WHERE loop */
  10593. int iContinue; /* Jump here to continue with next record */
  10594. int iBreak; /* Jump here to break out of the loop */
  10595. int nLevel; /* Number of nested loop */
  10596. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  10597. double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  10598. double nRowOut; /* Estimated number of output rows */
  10599. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  10600. };
  10601. /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
  10602. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  10603. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  10604. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  10605. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  10606. /*
  10607. ** A NameContext defines a context in which to resolve table and column
  10608. ** names. The context consists of a list of tables (the pSrcList) field and
  10609. ** a list of named expression (pEList). The named expression list may
  10610. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10611. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10612. ** pEList corresponds to the result set of a SELECT and is NULL for
  10613. ** other statements.
  10614. **
  10615. ** NameContexts can be nested. When resolving names, the inner-most
  10616. ** context is searched first. If no match is found, the next outer
  10617. ** context is checked. If there is still no match, the next context
  10618. ** is checked. This process continues until either a match is found
  10619. ** or all contexts are check. When a match is found, the nRef member of
  10620. ** the context containing the match is incremented.
  10621. **
  10622. ** Each subquery gets a new NameContext. The pNext field points to the
  10623. ** NameContext in the parent query. Thus the process of scanning the
  10624. ** NameContext list corresponds to searching through successively outer
  10625. ** subqueries looking for a match.
  10626. */
  10627. struct NameContext {
  10628. Parse *pParse; /* The parser */
  10629. SrcList *pSrcList; /* One or more tables used to resolve names */
  10630. ExprList *pEList; /* Optional list of named expressions */
  10631. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10632. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10633. int nRef; /* Number of names resolved by this context */
  10634. int nErr; /* Number of errors encountered while resolving names */
  10635. u8 ncFlags; /* Zero or more NC_* flags defined below */
  10636. };
  10637. /*
  10638. ** Allowed values for the NameContext, ncFlags field.
  10639. */
  10640. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  10641. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  10642. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  10643. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  10644. /*
  10645. ** An instance of the following structure contains all information
  10646. ** needed to generate code for a single SELECT statement.
  10647. **
  10648. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10649. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10650. ** limit and nOffset to the value of the offset (or 0 if there is not
  10651. ** offset). But later on, nLimit and nOffset become the memory locations
  10652. ** in the VDBE that record the limit and offset counters.
  10653. **
  10654. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10655. ** These addresses must be stored so that we can go back and fill in
  10656. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10657. ** the number of columns in P2 can be computed at the same time
  10658. ** as the OP_OpenEphm instruction is coded because not
  10659. ** enough information about the compound query is known at that point.
  10660. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10661. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10662. ** sequences for the ORDER BY clause.
  10663. */
  10664. struct Select {
  10665. ExprList *pEList; /* The fields of the result */
  10666. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10667. u16 selFlags; /* Various SF_* values */
  10668. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10669. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10670. double nSelectRow; /* Estimated number of result rows */
  10671. SrcList *pSrc; /* The FROM clause */
  10672. Expr *pWhere; /* The WHERE clause */
  10673. ExprList *pGroupBy; /* The GROUP BY clause */
  10674. Expr *pHaving; /* The HAVING clause */
  10675. ExprList *pOrderBy; /* The ORDER BY clause */
  10676. Select *pPrior; /* Prior select in a compound select statement */
  10677. Select *pNext; /* Next select to the left in a compound */
  10678. Select *pRightmost; /* Right-most select in a compound select statement */
  10679. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10680. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10681. };
  10682. /*
  10683. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10684. ** "Select Flag".
  10685. */
  10686. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10687. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10688. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10689. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10690. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10691. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10692. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10693. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10694. #define SF_Materialize 0x0100 /* Force materialization of views */
  10695. /*
  10696. ** The results of a select can be distributed in several ways. The
  10697. ** "SRT" prefix means "SELECT Result Type".
  10698. */
  10699. #define SRT_Union 1 /* Store result as keys in an index */
  10700. #define SRT_Except 2 /* Remove result from a UNION index */
  10701. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10702. #define SRT_Discard 4 /* Do not save the results anywhere */
  10703. /* The ORDER BY clause is ignored for all of the above */
  10704. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10705. #define SRT_Output 5 /* Output each row of result */
  10706. #define SRT_Mem 6 /* Store result in a memory cell */
  10707. #define SRT_Set 7 /* Store results as keys in an index */
  10708. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10709. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10710. #define SRT_Coroutine 10 /* Generate a single row of result */
  10711. /*
  10712. ** An instance of this object describes where to put of the results of
  10713. ** a SELECT statement.
  10714. */
  10715. struct SelectDest {
  10716. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  10717. char affSdst; /* Affinity used when eDest==SRT_Set */
  10718. int iSDParm; /* A parameter used by the eDest disposal method */
  10719. int iSdst; /* Base register where results are written */
  10720. int nSdst; /* Number of registers allocated */
  10721. };
  10722. /*
  10723. ** During code generation of statements that do inserts into AUTOINCREMENT
  10724. ** tables, the following information is attached to the Table.u.autoInc.p
  10725. ** pointer of each autoincrement table to record some side information that
  10726. ** the code generator needs. We have to keep per-table autoincrement
  10727. ** information in case inserts are down within triggers. Triggers do not
  10728. ** normally coordinate their activities, but we do need to coordinate the
  10729. ** loading and saving of autoincrement information.
  10730. */
  10731. struct AutoincInfo {
  10732. AutoincInfo *pNext; /* Next info block in a list of them all */
  10733. Table *pTab; /* Table this info block refers to */
  10734. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10735. int regCtr; /* Memory register holding the rowid counter */
  10736. };
  10737. /*
  10738. ** Size of the column cache
  10739. */
  10740. #ifndef SQLITE_N_COLCACHE
  10741. # define SQLITE_N_COLCACHE 10
  10742. #endif
  10743. /*
  10744. ** At least one instance of the following structure is created for each
  10745. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10746. ** statement. All such objects are stored in the linked list headed at
  10747. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10748. ** completed.
  10749. **
  10750. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10751. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10752. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10753. ** The Parse.pTriggerPrg list never contains two entries with the same
  10754. ** values for both pTrigger and orconf.
  10755. **
  10756. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10757. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10758. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10759. ** a mask of new.* columns used by the program.
  10760. */
  10761. struct TriggerPrg {
  10762. Trigger *pTrigger; /* Trigger this program was coded from */
  10763. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10764. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10765. int orconf; /* Default ON CONFLICT policy */
  10766. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10767. };
  10768. /*
  10769. ** The yDbMask datatype for the bitmask of all attached databases.
  10770. */
  10771. #if SQLITE_MAX_ATTACHED>30
  10772. typedef sqlite3_uint64 yDbMask;
  10773. #else
  10774. typedef unsigned int yDbMask;
  10775. #endif
  10776. /*
  10777. ** An SQL parser context. A copy of this structure is passed through
  10778. ** the parser and down into all the parser action routine in order to
  10779. ** carry around information that is global to the entire parse.
  10780. **
  10781. ** The structure is divided into two parts. When the parser and code
  10782. ** generate call themselves recursively, the first part of the structure
  10783. ** is constant but the second part is reset at the beginning and end of
  10784. ** each recursion.
  10785. **
  10786. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10787. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10788. ** used to store the set of table-locks required by the statement being
  10789. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10790. ** list.
  10791. */
  10792. struct Parse {
  10793. sqlite3 *db; /* The main database structure */
  10794. char *zErrMsg; /* An error message */
  10795. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10796. int rc; /* Return code from execution */
  10797. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10798. u8 checkSchema; /* Causes schema cookie check after an error */
  10799. u8 nested; /* Number of nested calls to the parser/code generator */
  10800. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10801. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10802. u8 nColCache; /* Number of entries in aColCache[] */
  10803. u8 iColCache; /* Next entry in aColCache[] to replace */
  10804. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  10805. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10806. int aTempReg[8]; /* Holding area for temporary registers */
  10807. int nRangeReg; /* Size of the temporary register block */
  10808. int iRangeReg; /* First register in temporary register block */
  10809. int nErr; /* Number of errors seen */
  10810. int nTab; /* Number of previously allocated VDBE cursors */
  10811. int nMem; /* Number of memory cells used so far */
  10812. int nSet; /* Number of sets used so far */
  10813. int nOnce; /* Number of OP_Once instructions so far */
  10814. int ckBase; /* Base register of data during check constraints */
  10815. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10816. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10817. struct yColCache {
  10818. int iTable; /* Table cursor number */
  10819. int iColumn; /* Table column number */
  10820. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10821. int iLevel; /* Nesting level */
  10822. int iReg; /* Reg with value of this column. 0 means none. */
  10823. int lru; /* Least recently used entry has the smallest value */
  10824. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10825. yDbMask writeMask; /* Start a write transaction on these databases */
  10826. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10827. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10828. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10829. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10830. int regRoot; /* Register holding root page number for new objects */
  10831. int nMaxArg; /* Max args passed to user function by sub-program */
  10832. Token constraintName;/* Name of the constraint currently being parsed */
  10833. #ifndef SQLITE_OMIT_SHARED_CACHE
  10834. int nTableLock; /* Number of locks in aTableLock */
  10835. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  10836. #endif
  10837. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  10838. /* Information used while coding trigger programs. */
  10839. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  10840. Table *pTriggerTab; /* Table triggers are being coded for */
  10841. double nQueryLoop; /* Estimated number of iterations of a query */
  10842. u32 oldmask; /* Mask of old.* columns referenced */
  10843. u32 newmask; /* Mask of new.* columns referenced */
  10844. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  10845. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  10846. u8 disableTriggers; /* True to disable triggers */
  10847. /* Above is constant between recursions. Below is reset before and after
  10848. ** each recursion */
  10849. int nVar; /* Number of '?' variables seen in the SQL so far */
  10850. int nzVar; /* Number of available slots in azVar[] */
  10851. u8 explain; /* True if the EXPLAIN flag is found on the query */
  10852. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10853. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  10854. int nVtabLock; /* Number of virtual tables to lock */
  10855. #endif
  10856. int nAlias; /* Number of aliased result set columns */
  10857. int nHeight; /* Expression tree height of current sub-select */
  10858. #ifndef SQLITE_OMIT_EXPLAIN
  10859. int iSelectId; /* ID of current select for EXPLAIN output */
  10860. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  10861. #endif
  10862. char **azVar; /* Pointers to names of parameters */
  10863. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  10864. int *aAlias; /* Register used to hold aliased result */
  10865. const char *zTail; /* All SQL text past the last semicolon parsed */
  10866. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  10867. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  10868. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  10869. Token sNameToken; /* Token with unqualified schema object name */
  10870. Token sLastToken; /* The last token parsed */
  10871. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10872. Token sArg; /* Complete text of a module argument */
  10873. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  10874. #endif
  10875. Table *pZombieTab; /* List of Table objects to delete after code gen */
  10876. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  10877. };
  10878. /*
  10879. ** Return true if currently inside an sqlite3_declare_vtab() call.
  10880. */
  10881. #ifdef SQLITE_OMIT_VIRTUALTABLE
  10882. #define IN_DECLARE_VTAB 0
  10883. #else
  10884. #define IN_DECLARE_VTAB (pParse->declareVtab)
  10885. #endif
  10886. /*
  10887. ** An instance of the following structure can be declared on a stack and used
  10888. ** to save the Parse.zAuthContext value so that it can be restored later.
  10889. */
  10890. struct AuthContext {
  10891. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  10892. Parse *pParse; /* The Parse structure */
  10893. };
  10894. /*
  10895. ** Bitfield flags for P5 value in various opcodes.
  10896. */
  10897. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  10898. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  10899. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  10900. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  10901. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  10902. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  10903. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  10904. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  10905. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  10906. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  10907. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  10908. /*
  10909. * Each trigger present in the database schema is stored as an instance of
  10910. * struct Trigger.
  10911. *
  10912. * Pointers to instances of struct Trigger are stored in two ways.
  10913. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  10914. * database). This allows Trigger structures to be retrieved by name.
  10915. * 2. All triggers associated with a single table form a linked list, using the
  10916. * pNext member of struct Trigger. A pointer to the first element of the
  10917. * linked list is stored as the "pTrigger" member of the associated
  10918. * struct Table.
  10919. *
  10920. * The "step_list" member points to the first element of a linked list
  10921. * containing the SQL statements specified as the trigger program.
  10922. */
  10923. struct Trigger {
  10924. char *zName; /* The name of the trigger */
  10925. char *table; /* The table or view to which the trigger applies */
  10926. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  10927. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  10928. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  10929. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  10930. the <column-list> is stored here */
  10931. Schema *pSchema; /* Schema containing the trigger */
  10932. Schema *pTabSchema; /* Schema containing the table */
  10933. TriggerStep *step_list; /* Link list of trigger program steps */
  10934. Trigger *pNext; /* Next trigger associated with the table */
  10935. };
  10936. /*
  10937. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  10938. ** determine which.
  10939. **
  10940. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  10941. ** In that cases, the constants below can be ORed together.
  10942. */
  10943. #define TRIGGER_BEFORE 1
  10944. #define TRIGGER_AFTER 2
  10945. /*
  10946. * An instance of struct TriggerStep is used to store a single SQL statement
  10947. * that is a part of a trigger-program.
  10948. *
  10949. * Instances of struct TriggerStep are stored in a singly linked list (linked
  10950. * using the "pNext" member) referenced by the "step_list" member of the
  10951. * associated struct Trigger instance. The first element of the linked list is
  10952. * the first step of the trigger-program.
  10953. *
  10954. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  10955. * "SELECT" statement. The meanings of the other members is determined by the
  10956. * value of "op" as follows:
  10957. *
  10958. * (op == TK_INSERT)
  10959. * orconf -> stores the ON CONFLICT algorithm
  10960. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  10961. * this stores a pointer to the SELECT statement. Otherwise NULL.
  10962. * target -> A token holding the quoted name of the table to insert into.
  10963. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  10964. * this stores values to be inserted. Otherwise NULL.
  10965. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  10966. * statement, then this stores the column-names to be
  10967. * inserted into.
  10968. *
  10969. * (op == TK_DELETE)
  10970. * target -> A token holding the quoted name of the table to delete from.
  10971. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  10972. * Otherwise NULL.
  10973. *
  10974. * (op == TK_UPDATE)
  10975. * target -> A token holding the quoted name of the table to update rows of.
  10976. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  10977. * Otherwise NULL.
  10978. * pExprList -> A list of the columns to update and the expressions to update
  10979. * them to. See sqlite3Update() documentation of "pChanges"
  10980. * argument.
  10981. *
  10982. */
  10983. struct TriggerStep {
  10984. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  10985. u8 orconf; /* OE_Rollback etc. */
  10986. Trigger *pTrig; /* The trigger that this step is a part of */
  10987. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  10988. Token target; /* Target table for DELETE, UPDATE, INSERT */
  10989. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  10990. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  10991. IdList *pIdList; /* Column names for INSERT */
  10992. TriggerStep *pNext; /* Next in the link-list */
  10993. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  10994. };
  10995. /*
  10996. ** The following structure contains information used by the sqliteFix...
  10997. ** routines as they walk the parse tree to make database references
  10998. ** explicit.
  10999. */
  11000. typedef struct DbFixer DbFixer;
  11001. struct DbFixer {
  11002. Parse *pParse; /* The parsing context. Error messages written here */
  11003. Schema *pSchema; /* Fix items to this schema */
  11004. const char *zDb; /* Make sure all objects are contained in this database */
  11005. const char *zType; /* Type of the container - used for error messages */
  11006. const Token *pName; /* Name of the container - used for error messages */
  11007. };
  11008. /*
  11009. ** An objected used to accumulate the text of a string where we
  11010. ** do not necessarily know how big the string will be in the end.
  11011. */
  11012. struct StrAccum {
  11013. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11014. char *zBase; /* A base allocation. Not from malloc. */
  11015. char *zText; /* The string collected so far */
  11016. int nChar; /* Length of the string so far */
  11017. int nAlloc; /* Amount of space allocated in zText */
  11018. int mxAlloc; /* Maximum allowed string length */
  11019. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  11020. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11021. u8 tooBig; /* Becomes true if string size exceeds limits */
  11022. };
  11023. /*
  11024. ** A pointer to this structure is used to communicate information
  11025. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11026. */
  11027. typedef struct {
  11028. sqlite3 *db; /* The database being initialized */
  11029. char **pzErrMsg; /* Error message stored here */
  11030. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11031. int rc; /* Result code stored here */
  11032. } InitData;
  11033. /*
  11034. ** Structure containing global configuration data for the SQLite library.
  11035. **
  11036. ** This structure also contains some state information.
  11037. */
  11038. struct Sqlite3Config {
  11039. int bMemstat; /* True to enable memory status */
  11040. int bCoreMutex; /* True to enable core mutexing */
  11041. int bFullMutex; /* True to enable full mutexing */
  11042. int bOpenUri; /* True to interpret filenames as URIs */
  11043. int bUseCis; /* Use covering indices for full-scans */
  11044. int mxStrlen; /* Maximum string length */
  11045. int szLookaside; /* Default lookaside buffer size */
  11046. int nLookaside; /* Default lookaside buffer count */
  11047. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11048. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11049. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11050. void *pHeap; /* Heap storage space */
  11051. int nHeap; /* Size of pHeap[] */
  11052. int mnReq, mxReq; /* Min and max heap requests sizes */
  11053. void *pScratch; /* Scratch memory */
  11054. int szScratch; /* Size of each scratch buffer */
  11055. int nScratch; /* Number of scratch buffers */
  11056. void *pPage; /* Page cache memory */
  11057. int szPage; /* Size of each page in pPage[] */
  11058. int nPage; /* Number of pages in pPage[] */
  11059. int mxParserStack; /* maximum depth of the parser stack */
  11060. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11061. /* The above might be initialized to non-zero. The following need to always
  11062. ** initially be zero, however. */
  11063. int isInit; /* True after initialization has finished */
  11064. int inProgress; /* True while initialization in progress */
  11065. int isMutexInit; /* True after mutexes are initialized */
  11066. int isMallocInit; /* True after malloc is initialized */
  11067. int isPCacheInit; /* True after malloc is initialized */
  11068. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11069. int nRefInitMutex; /* Number of users of pInitMutex */
  11070. void (*xLog)(void*,int,const char*); /* Function for logging */
  11071. void *pLogArg; /* First argument to xLog() */
  11072. int bLocaltimeFault; /* True to fail localtime() calls */
  11073. #ifdef SQLITE_ENABLE_SQLLOG
  11074. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11075. void *pSqllogArg;
  11076. #endif
  11077. };
  11078. /*
  11079. ** Context pointer passed down through the tree-walk.
  11080. */
  11081. struct Walker {
  11082. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11083. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11084. Parse *pParse; /* Parser context. */
  11085. int walkerDepth; /* Number of subqueries */
  11086. union { /* Extra data for callback */
  11087. NameContext *pNC; /* Naming context */
  11088. int i; /* Integer value */
  11089. SrcList *pSrcList; /* FROM clause */
  11090. struct SrcCount *pSrcCount; /* Counting column references */
  11091. } u;
  11092. };
  11093. /* Forward declarations */
  11094. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11095. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11096. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11097. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11098. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11099. /*
  11100. ** Return code from the parse-tree walking primitives and their
  11101. ** callbacks.
  11102. */
  11103. #define WRC_Continue 0 /* Continue down into children */
  11104. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11105. #define WRC_Abort 2 /* Abandon the tree walk */
  11106. /*
  11107. ** Assuming zIn points to the first byte of a UTF-8 character,
  11108. ** advance zIn to point to the first byte of the next UTF-8 character.
  11109. */
  11110. #define SQLITE_SKIP_UTF8(zIn) { \
  11111. if( (*(zIn++))>=0xc0 ){ \
  11112. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11113. } \
  11114. }
  11115. /*
  11116. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11117. ** the same name but without the _BKPT suffix. These macros invoke
  11118. ** routines that report the line-number on which the error originated
  11119. ** using sqlite3_log(). The routines also provide a convenient place
  11120. ** to set a debugger breakpoint.
  11121. */
  11122. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11123. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11124. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11125. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11126. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11127. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11128. /*
  11129. ** FTS4 is really an extension for FTS3. It is enabled using the
  11130. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11131. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11132. */
  11133. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11134. # define SQLITE_ENABLE_FTS3
  11135. #endif
  11136. /*
  11137. ** The ctype.h header is needed for non-ASCII systems. It is also
  11138. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11139. */
  11140. #if !defined(SQLITE_ASCII) || \
  11141. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11142. # include <ctype.h>
  11143. #endif
  11144. /*
  11145. ** The following macros mimic the standard library functions toupper(),
  11146. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11147. ** sqlite versions only work for ASCII characters, regardless of locale.
  11148. */
  11149. #ifdef SQLITE_ASCII
  11150. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11151. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11152. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11153. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11154. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11155. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11156. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11157. #else
  11158. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11159. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11160. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11161. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11162. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11163. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11164. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11165. #endif
  11166. /*
  11167. ** Internal function prototypes
  11168. */
  11169. #define sqlite3StrICmp sqlite3_stricmp
  11170. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11171. #define sqlite3StrNICmp sqlite3_strnicmp
  11172. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11173. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11174. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11175. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11176. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11177. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11178. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11179. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11180. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11181. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11182. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11183. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11184. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11185. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11186. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11187. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11188. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11189. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11190. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11191. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11192. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11193. /*
  11194. ** On systems with ample stack space and that support alloca(), make
  11195. ** use of alloca() to obtain space for large automatic objects. By default,
  11196. ** obtain space from malloc().
  11197. **
  11198. ** The alloca() routine never returns NULL. This will cause code paths
  11199. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11200. */
  11201. #ifdef SQLITE_USE_ALLOCA
  11202. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11203. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11204. # define sqlite3StackFree(D,P)
  11205. #else
  11206. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11207. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11208. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11209. #endif
  11210. #ifdef SQLITE_ENABLE_MEMSYS3
  11211. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11212. #endif
  11213. #ifdef SQLITE_ENABLE_MEMSYS5
  11214. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11215. #endif
  11216. #ifndef SQLITE_MUTEX_OMIT
  11217. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11218. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11219. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11220. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11221. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11222. #endif
  11223. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11224. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11225. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11226. #ifndef SQLITE_OMIT_FLOATING_POINT
  11227. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11228. #else
  11229. # define sqlite3IsNaN(X) 0
  11230. #endif
  11231. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11232. #ifndef SQLITE_OMIT_TRACE
  11233. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11234. #endif
  11235. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11236. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11237. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11238. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11239. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11240. #endif
  11241. #if defined(SQLITE_TEST)
  11242. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11243. #endif
  11244. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11245. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11246. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11247. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11248. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11249. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11250. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11251. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11252. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11253. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11254. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11255. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11256. #else
  11257. # define sqlite3ExplainBegin(X)
  11258. # define sqlite3ExplainSelect(A,B)
  11259. # define sqlite3ExplainExpr(A,B)
  11260. # define sqlite3ExplainExprList(A,B)
  11261. # define sqlite3ExplainFinish(X)
  11262. # define sqlite3VdbeExplanation(X) 0
  11263. #endif
  11264. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11265. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11266. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11267. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11268. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11269. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11270. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11271. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11272. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11273. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11274. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11275. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11276. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11277. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11278. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11279. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11280. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11281. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11282. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11283. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11284. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11285. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11286. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11287. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11288. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11289. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11290. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11291. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11292. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11293. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11294. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11295. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11296. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11297. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11298. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11299. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11300. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11301. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11302. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11303. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11304. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11305. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11306. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11307. sqlite3_vfs**,char**,char **);
  11308. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11309. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11310. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11311. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11312. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11313. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11314. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11315. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11316. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11317. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11318. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11319. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11320. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11321. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11322. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11323. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11324. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11325. #else
  11326. # define sqlite3ViewGetColumnNames(A,B) 0
  11327. #endif
  11328. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11329. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11330. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11331. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11332. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11333. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11334. #else
  11335. # define sqlite3AutoincrementBegin(X)
  11336. # define sqlite3AutoincrementEnd(X)
  11337. #endif
  11338. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11339. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11340. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11341. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11342. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11343. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11344. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11345. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11346. Token*, Select*, Expr*, IdList*);
  11347. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11348. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11349. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11350. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11351. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11352. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11353. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11354. Token*, int, int);
  11355. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11356. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11357. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11358. Expr*,ExprList*,int,Expr*,Expr*);
  11359. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11360. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11361. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11362. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11363. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11364. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
  11365. #endif
  11366. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11367. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11368. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11369. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11370. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11371. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11372. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11373. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11374. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11375. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11376. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11377. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11378. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11379. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11380. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11381. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11382. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11383. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11384. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11385. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11386. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11387. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11388. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11389. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11390. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11391. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11392. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11393. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11394. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11395. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11396. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  11397. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
  11398. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11399. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11400. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11401. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11402. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11403. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11404. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11405. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11406. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11407. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11408. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11409. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11410. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11411. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11412. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11413. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11414. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11415. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11416. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11417. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11418. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11419. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11420. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11421. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11422. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11423. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11424. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  11425. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11426. int*,int,int,int,int,int*);
  11427. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11428. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11429. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11430. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11431. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11432. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
  11433. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11434. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11435. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11436. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11437. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11438. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11439. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11440. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11441. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11442. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11443. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11444. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11445. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11446. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11447. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11448. #endif
  11449. #ifndef SQLITE_OMIT_TRIGGER
  11450. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11451. Expr*,int, int);
  11452. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11453. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11454. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11455. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11456. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11457. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11458. int, int, int);
  11459. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11460. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11461. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11462. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11463. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11464. ExprList*,Select*,u8);
  11465. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11466. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11467. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11468. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11469. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11470. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11471. #else
  11472. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11473. # define sqlite3DeleteTrigger(A,B)
  11474. # define sqlite3DropTriggerPtr(A,B)
  11475. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11476. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11477. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11478. # define sqlite3TriggerList(X, Y) 0
  11479. # define sqlite3ParseToplevel(p) p
  11480. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11481. #endif
  11482. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11483. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11484. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11485. #ifndef SQLITE_OMIT_AUTHORIZATION
  11486. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11487. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11488. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11489. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11490. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11491. #else
  11492. # define sqlite3AuthRead(a,b,c,d)
  11493. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11494. # define sqlite3AuthContextPush(a,b,c)
  11495. # define sqlite3AuthContextPop(a) ((void)(a))
  11496. #endif
  11497. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11498. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11499. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11500. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11501. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11502. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11503. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11504. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11505. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11506. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11507. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11508. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11509. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11510. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11511. /*
  11512. ** Routines to read and write variable-length integers. These used to
  11513. ** be defined locally, but now we use the varint routines in the util.c
  11514. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11515. ** are coded to assume the single byte case is already handled (which
  11516. ** the MACRO form does).
  11517. */
  11518. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11519. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11520. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11521. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11522. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11523. /*
  11524. ** The header of a record consists of a sequence variable-length integers.
  11525. ** These integers are almost always small and are encoded as a single byte.
  11526. ** The following macros take advantage this fact to provide a fast encode
  11527. ** and decode of the integers in a record header. It is faster for the common
  11528. ** case where the integer is a single byte. It is a little slower when the
  11529. ** integer is two or more bytes. But overall it is faster.
  11530. **
  11531. ** The following expressions are equivalent:
  11532. **
  11533. ** x = sqlite3GetVarint32( A, &B );
  11534. ** x = sqlite3PutVarint32( A, B );
  11535. **
  11536. ** x = getVarint32( A, B );
  11537. ** x = putVarint32( A, B );
  11538. **
  11539. */
  11540. #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
  11541. #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
  11542. #define getVarint sqlite3GetVarint
  11543. #define putVarint sqlite3PutVarint
  11544. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11545. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11546. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11547. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11548. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11549. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11550. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11551. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11552. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11553. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11554. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11555. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11556. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11557. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11558. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11559. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11560. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11561. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11562. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11563. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11564. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11565. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11566. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11567. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11568. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11569. #ifdef SQLITE_ENABLE_8_3_NAMES
  11570. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11571. #else
  11572. # define sqlite3FileSuffix3(X,Y)
  11573. #endif
  11574. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11575. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11576. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11577. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11578. void(*)(void*));
  11579. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11580. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11581. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11582. #ifdef SQLITE_ENABLE_STAT3
  11583. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
  11584. #endif
  11585. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11586. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11587. #ifndef SQLITE_AMALGAMATION
  11588. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11589. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11590. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11591. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11592. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11593. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11594. #ifndef SQLITE_OMIT_WSD
  11595. SQLITE_PRIVATE int sqlite3PendingByte;
  11596. #endif
  11597. #endif
  11598. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11599. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11600. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11601. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11602. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11603. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11604. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11605. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11606. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11607. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11608. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11609. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11610. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11611. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11612. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11613. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11614. SQLITE_PRIVATE char sqlite3AffinityType(const char*);
  11615. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11616. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11617. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11618. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11619. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11620. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11621. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11622. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11623. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11624. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11625. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11626. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11627. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11628. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11629. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11630. void (*)(sqlite3_context*,int,sqlite3_value **),
  11631. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11632. FuncDestructor *pDestructor
  11633. );
  11634. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11635. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11636. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11637. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11638. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11639. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11640. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11641. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11642. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11643. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11644. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11645. /*
  11646. ** The interface to the LEMON-generated parser
  11647. */
  11648. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11649. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11650. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11651. #ifdef YYTRACKMAXSTACKDEPTH
  11652. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11653. #endif
  11654. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11655. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11656. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11657. #else
  11658. # define sqlite3CloseExtensions(X)
  11659. #endif
  11660. #ifndef SQLITE_OMIT_SHARED_CACHE
  11661. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11662. #else
  11663. #define sqlite3TableLock(v,w,x,y,z)
  11664. #endif
  11665. #ifdef SQLITE_TEST
  11666. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11667. #endif
  11668. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11669. # define sqlite3VtabClear(Y)
  11670. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11671. # define sqlite3VtabRollback(X)
  11672. # define sqlite3VtabCommit(X)
  11673. # define sqlite3VtabInSync(db) 0
  11674. # define sqlite3VtabLock(X)
  11675. # define sqlite3VtabUnlock(X)
  11676. # define sqlite3VtabUnlockList(X)
  11677. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11678. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11679. #else
  11680. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11681. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11682. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  11683. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11684. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11685. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11686. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11687. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11688. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11689. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11690. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11691. #endif
  11692. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11693. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11694. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11695. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11696. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11697. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11698. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11699. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11700. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11701. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11702. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11703. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11704. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11705. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11706. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11707. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11708. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11709. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11710. #ifndef SQLITE_OMIT_WAL
  11711. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11712. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11713. #endif
  11714. /* Declarations for functions in fkey.c. All of these are replaced by
  11715. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11716. ** key functionality is available. If OMIT_TRIGGER is defined but
  11717. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11718. ** this case foreign keys are parsed, but no other functionality is
  11719. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11720. */
  11721. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11722. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
  11723. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11724. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
  11725. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11726. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11727. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11728. #else
  11729. #define sqlite3FkActions(a,b,c,d)
  11730. #define sqlite3FkCheck(a,b,c,d)
  11731. #define sqlite3FkDropTable(a,b,c)
  11732. #define sqlite3FkOldmask(a,b) 0
  11733. #define sqlite3FkRequired(a,b,c,d) 0
  11734. #endif
  11735. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11736. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11737. #else
  11738. #define sqlite3FkDelete(a,b)
  11739. #endif
  11740. /*
  11741. ** Available fault injectors. Should be numbered beginning with 0.
  11742. */
  11743. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11744. #define SQLITE_FAULTINJECTOR_COUNT 1
  11745. /*
  11746. ** The interface to the code in fault.c used for identifying "benign"
  11747. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11748. ** is not defined.
  11749. */
  11750. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11751. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11752. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11753. #else
  11754. #define sqlite3BeginBenignMalloc()
  11755. #define sqlite3EndBenignMalloc()
  11756. #endif
  11757. #define IN_INDEX_ROWID 1
  11758. #define IN_INDEX_EPH 2
  11759. #define IN_INDEX_INDEX 3
  11760. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11761. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11762. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11763. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11764. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11765. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  11766. #else
  11767. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11768. #define sqlite3JournalExists(p) 1
  11769. #endif
  11770. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11771. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11772. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11773. #if SQLITE_MAX_EXPR_DEPTH>0
  11774. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11775. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11776. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11777. #else
  11778. #define sqlite3ExprSetHeight(x,y)
  11779. #define sqlite3SelectExprHeight(x) 0
  11780. #define sqlite3ExprCheckHeight(x,y)
  11781. #endif
  11782. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11783. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11784. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11785. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11786. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11787. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11788. #else
  11789. #define sqlite3ConnectionBlocked(x,y)
  11790. #define sqlite3ConnectionUnlocked(x)
  11791. #define sqlite3ConnectionClosed(x)
  11792. #endif
  11793. #ifdef SQLITE_DEBUG
  11794. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11795. #endif
  11796. /*
  11797. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11798. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11799. ** print I/O tracing messages.
  11800. */
  11801. #ifdef SQLITE_ENABLE_IOTRACE
  11802. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  11803. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  11804. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  11805. #else
  11806. # define IOTRACE(A)
  11807. # define sqlite3VdbeIOTraceSql(X)
  11808. #endif
  11809. /*
  11810. ** These routines are available for the mem2.c debugging memory allocator
  11811. ** only. They are used to verify that different "types" of memory
  11812. ** allocations are properly tracked by the system.
  11813. **
  11814. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  11815. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  11816. ** a single bit set.
  11817. **
  11818. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  11819. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11820. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  11821. **
  11822. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  11823. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11824. **
  11825. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  11826. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  11827. ** it might have been allocated by lookaside, except the allocation was
  11828. ** too large or lookaside was already full. It is important to verify
  11829. ** that allocations that might have been satisfied by lookaside are not
  11830. ** passed back to non-lookaside free() routines. Asserts such as the
  11831. ** example above are placed on the non-lookaside free() routines to verify
  11832. ** this constraint.
  11833. **
  11834. ** All of this is no-op for a production build. It only comes into
  11835. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  11836. */
  11837. #ifdef SQLITE_MEMDEBUG
  11838. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  11839. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  11840. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  11841. #else
  11842. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  11843. # define sqlite3MemdebugHasType(X,Y) 1
  11844. # define sqlite3MemdebugNoType(X,Y) 1
  11845. #endif
  11846. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  11847. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  11848. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  11849. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  11850. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  11851. #endif /* _SQLITEINT_H_ */
  11852. /************** End of sqliteInt.h *******************************************/
  11853. /************** Begin file global.c ******************************************/
  11854. /*
  11855. ** 2008 June 13
  11856. **
  11857. ** The author disclaims copyright to this source code. In place of
  11858. ** a legal notice, here is a blessing:
  11859. **
  11860. ** May you do good and not evil.
  11861. ** May you find forgiveness for yourself and forgive others.
  11862. ** May you share freely, never taking more than you give.
  11863. **
  11864. *************************************************************************
  11865. **
  11866. ** This file contains definitions of global variables and contants.
  11867. */
  11868. /* An array to map all upper-case characters into their corresponding
  11869. ** lower-case character.
  11870. **
  11871. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  11872. ** handle case conversions for the UTF character set since the tables
  11873. ** involved are nearly as big or bigger than SQLite itself.
  11874. */
  11875. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  11876. #ifdef SQLITE_ASCII
  11877. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  11878. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  11879. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  11880. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  11881. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  11882. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  11883. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  11884. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  11885. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  11886. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  11887. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  11888. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  11889. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  11890. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  11891. 252,253,254,255
  11892. #endif
  11893. #ifdef SQLITE_EBCDIC
  11894. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  11895. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  11896. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  11897. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  11898. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  11899. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  11900. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  11901. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  11902. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  11903. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  11904. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  11905. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  11906. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  11907. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  11908. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  11909. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  11910. #endif
  11911. };
  11912. /*
  11913. ** The following 256 byte lookup table is used to support SQLites built-in
  11914. ** equivalents to the following standard library functions:
  11915. **
  11916. ** isspace() 0x01
  11917. ** isalpha() 0x02
  11918. ** isdigit() 0x04
  11919. ** isalnum() 0x06
  11920. ** isxdigit() 0x08
  11921. ** toupper() 0x20
  11922. ** SQLite identifier character 0x40
  11923. **
  11924. ** Bit 0x20 is set if the mapped character requires translation to upper
  11925. ** case. i.e. if the character is a lower-case ASCII character.
  11926. ** If x is a lower-case ASCII character, then its upper-case equivalent
  11927. ** is (x - 0x20). Therefore toupper() can be implemented as:
  11928. **
  11929. ** (x & ~(map[x]&0x20))
  11930. **
  11931. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  11932. ** array. tolower() is used more often than toupper() by SQLite.
  11933. **
  11934. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  11935. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  11936. ** non-ASCII UTF character. Hence the test for whether or not a character is
  11937. ** part of an identifier is 0x46.
  11938. **
  11939. ** SQLite's versions are identical to the standard versions assuming a
  11940. ** locale of "C". They are implemented as macros in sqliteInt.h.
  11941. */
  11942. #ifdef SQLITE_ASCII
  11943. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  11944. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  11945. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  11946. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  11947. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  11948. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  11949. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  11950. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  11951. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  11952. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  11953. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  11954. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  11955. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  11956. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  11957. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  11958. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  11959. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  11960. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  11961. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  11962. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  11963. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  11964. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  11965. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  11966. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  11967. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  11968. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  11969. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  11970. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  11971. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  11972. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  11973. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  11974. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  11975. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  11976. };
  11977. #endif
  11978. #ifndef SQLITE_USE_URI
  11979. # define SQLITE_USE_URI 0
  11980. #endif
  11981. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  11982. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  11983. #endif
  11984. /*
  11985. ** The following singleton contains the global configuration for
  11986. ** the SQLite library.
  11987. */
  11988. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  11989. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  11990. 1, /* bCoreMutex */
  11991. SQLITE_THREADSAFE==1, /* bFullMutex */
  11992. SQLITE_USE_URI, /* bOpenUri */
  11993. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  11994. 0x7ffffffe, /* mxStrlen */
  11995. 128, /* szLookaside */
  11996. 500, /* nLookaside */
  11997. {0,0,0,0,0,0,0,0}, /* m */
  11998. {0,0,0,0,0,0,0,0,0}, /* mutex */
  11999. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12000. (void*)0, /* pHeap */
  12001. 0, /* nHeap */
  12002. 0, 0, /* mnHeap, mxHeap */
  12003. (void*)0, /* pScratch */
  12004. 0, /* szScratch */
  12005. 0, /* nScratch */
  12006. (void*)0, /* pPage */
  12007. 0, /* szPage */
  12008. 0, /* nPage */
  12009. 0, /* mxParserStack */
  12010. 0, /* sharedCacheEnabled */
  12011. /* All the rest should always be initialized to zero */
  12012. 0, /* isInit */
  12013. 0, /* inProgress */
  12014. 0, /* isMutexInit */
  12015. 0, /* isMallocInit */
  12016. 0, /* isPCacheInit */
  12017. 0, /* pInitMutex */
  12018. 0, /* nRefInitMutex */
  12019. 0, /* xLog */
  12020. 0, /* pLogArg */
  12021. 0, /* bLocaltimeFault */
  12022. #ifdef SQLITE_ENABLE_SQLLOG
  12023. 0, /* xSqllog */
  12024. 0 /* pSqllogArg */
  12025. #endif
  12026. };
  12027. /*
  12028. ** Hash table for global functions - functions common to all
  12029. ** database connections. After initialization, this table is
  12030. ** read-only.
  12031. */
  12032. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12033. /*
  12034. ** Constant tokens for values 0 and 1.
  12035. */
  12036. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12037. { "0", 1 },
  12038. { "1", 1 }
  12039. };
  12040. /*
  12041. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12042. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12043. ** the database page that contains the pending byte. It never attempts
  12044. ** to read or write that page. The pending byte page is set assign
  12045. ** for use by the VFS layers as space for managing file locks.
  12046. **
  12047. ** During testing, it is often desirable to move the pending byte to
  12048. ** a different position in the file. This allows code that has to
  12049. ** deal with the pending byte to run on files that are much smaller
  12050. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12051. ** move the pending byte.
  12052. **
  12053. ** IMPORTANT: Changing the pending byte to any value other than
  12054. ** 0x40000000 results in an incompatible database file format!
  12055. ** Changing the pending byte during operating results in undefined
  12056. ** and dileterious behavior.
  12057. */
  12058. #ifndef SQLITE_OMIT_WSD
  12059. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12060. #endif
  12061. /*
  12062. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12063. ** created by mkopcodeh.awk during compilation. Data is obtained
  12064. ** from the comments following the "case OP_xxxx:" statements in
  12065. ** the vdbe.c file.
  12066. */
  12067. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12068. /************** End of global.c **********************************************/
  12069. /************** Begin file ctime.c *******************************************/
  12070. /*
  12071. ** 2010 February 23
  12072. **
  12073. ** The author disclaims copyright to this source code. In place of
  12074. ** a legal notice, here is a blessing:
  12075. **
  12076. ** May you do good and not evil.
  12077. ** May you find forgiveness for yourself and forgive others.
  12078. ** May you share freely, never taking more than you give.
  12079. **
  12080. *************************************************************************
  12081. **
  12082. ** This file implements routines used to report what compile-time options
  12083. ** SQLite was built with.
  12084. */
  12085. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12086. /*
  12087. ** An array of names of all compile-time options. This array should
  12088. ** be sorted A-Z.
  12089. **
  12090. ** This array looks large, but in a typical installation actually uses
  12091. ** only a handful of compile-time options, so most times this array is usually
  12092. ** rather short and uses little memory space.
  12093. */
  12094. static const char * const azCompileOpt[] = {
  12095. /* These macros are provided to "stringify" the value of the define
  12096. ** for those options in which the value is meaningful. */
  12097. #define CTIMEOPT_VAL_(opt) #opt
  12098. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12099. #ifdef SQLITE_32BIT_ROWID
  12100. "32BIT_ROWID",
  12101. #endif
  12102. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12103. "4_BYTE_ALIGNED_MALLOC",
  12104. #endif
  12105. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12106. "CASE_SENSITIVE_LIKE",
  12107. #endif
  12108. #ifdef SQLITE_CHECK_PAGES
  12109. "CHECK_PAGES",
  12110. #endif
  12111. #ifdef SQLITE_COVERAGE_TEST
  12112. "COVERAGE_TEST",
  12113. #endif
  12114. #ifdef SQLITE_CURDIR
  12115. "CURDIR",
  12116. #endif
  12117. #ifdef SQLITE_DEBUG
  12118. "DEBUG",
  12119. #endif
  12120. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12121. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12122. #endif
  12123. #ifdef SQLITE_DISABLE_DIRSYNC
  12124. "DISABLE_DIRSYNC",
  12125. #endif
  12126. #ifdef SQLITE_DISABLE_LFS
  12127. "DISABLE_LFS",
  12128. #endif
  12129. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12130. "ENABLE_ATOMIC_WRITE",
  12131. #endif
  12132. #ifdef SQLITE_ENABLE_CEROD
  12133. "ENABLE_CEROD",
  12134. #endif
  12135. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12136. "ENABLE_COLUMN_METADATA",
  12137. #endif
  12138. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12139. "ENABLE_EXPENSIVE_ASSERT",
  12140. #endif
  12141. #ifdef SQLITE_ENABLE_FTS1
  12142. "ENABLE_FTS1",
  12143. #endif
  12144. #ifdef SQLITE_ENABLE_FTS2
  12145. "ENABLE_FTS2",
  12146. #endif
  12147. #ifdef SQLITE_ENABLE_FTS3
  12148. "ENABLE_FTS3",
  12149. #endif
  12150. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12151. "ENABLE_FTS3_PARENTHESIS",
  12152. #endif
  12153. #ifdef SQLITE_ENABLE_FTS4
  12154. "ENABLE_FTS4",
  12155. #endif
  12156. #ifdef SQLITE_ENABLE_ICU
  12157. "ENABLE_ICU",
  12158. #endif
  12159. #ifdef SQLITE_ENABLE_IOTRACE
  12160. "ENABLE_IOTRACE",
  12161. #endif
  12162. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12163. "ENABLE_LOAD_EXTENSION",
  12164. #endif
  12165. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12166. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12167. #endif
  12168. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12169. "ENABLE_MEMORY_MANAGEMENT",
  12170. #endif
  12171. #ifdef SQLITE_ENABLE_MEMSYS3
  12172. "ENABLE_MEMSYS3",
  12173. #endif
  12174. #ifdef SQLITE_ENABLE_MEMSYS5
  12175. "ENABLE_MEMSYS5",
  12176. #endif
  12177. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12178. "ENABLE_OVERSIZE_CELL_CHECK",
  12179. #endif
  12180. #ifdef SQLITE_ENABLE_RTREE
  12181. "ENABLE_RTREE",
  12182. #endif
  12183. #ifdef SQLITE_ENABLE_STAT3
  12184. "ENABLE_STAT3",
  12185. #endif
  12186. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12187. "ENABLE_UNLOCK_NOTIFY",
  12188. #endif
  12189. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12190. "ENABLE_UPDATE_DELETE_LIMIT",
  12191. #endif
  12192. #ifdef SQLITE_HAS_CODEC
  12193. "HAS_CODEC",
  12194. #endif
  12195. #ifdef SQLITE_HAVE_ISNAN
  12196. "HAVE_ISNAN",
  12197. #endif
  12198. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12199. "HOMEGROWN_RECURSIVE_MUTEX",
  12200. #endif
  12201. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12202. "IGNORE_AFP_LOCK_ERRORS",
  12203. #endif
  12204. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12205. "IGNORE_FLOCK_LOCK_ERRORS",
  12206. #endif
  12207. #ifdef SQLITE_INT64_TYPE
  12208. "INT64_TYPE",
  12209. #endif
  12210. #ifdef SQLITE_LOCK_TRACE
  12211. "LOCK_TRACE",
  12212. #endif
  12213. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12214. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12215. #endif
  12216. #ifdef SQLITE_MEMDEBUG
  12217. "MEMDEBUG",
  12218. #endif
  12219. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12220. "MIXED_ENDIAN_64BIT_FLOAT",
  12221. #endif
  12222. #ifdef SQLITE_NO_SYNC
  12223. "NO_SYNC",
  12224. #endif
  12225. #ifdef SQLITE_OMIT_ALTERTABLE
  12226. "OMIT_ALTERTABLE",
  12227. #endif
  12228. #ifdef SQLITE_OMIT_ANALYZE
  12229. "OMIT_ANALYZE",
  12230. #endif
  12231. #ifdef SQLITE_OMIT_ATTACH
  12232. "OMIT_ATTACH",
  12233. #endif
  12234. #ifdef SQLITE_OMIT_AUTHORIZATION
  12235. "OMIT_AUTHORIZATION",
  12236. #endif
  12237. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12238. "OMIT_AUTOINCREMENT",
  12239. #endif
  12240. #ifdef SQLITE_OMIT_AUTOINIT
  12241. "OMIT_AUTOINIT",
  12242. #endif
  12243. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12244. "OMIT_AUTOMATIC_INDEX",
  12245. #endif
  12246. #ifdef SQLITE_OMIT_AUTORESET
  12247. "OMIT_AUTORESET",
  12248. #endif
  12249. #ifdef SQLITE_OMIT_AUTOVACUUM
  12250. "OMIT_AUTOVACUUM",
  12251. #endif
  12252. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12253. "OMIT_BETWEEN_OPTIMIZATION",
  12254. #endif
  12255. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12256. "OMIT_BLOB_LITERAL",
  12257. #endif
  12258. #ifdef SQLITE_OMIT_BTREECOUNT
  12259. "OMIT_BTREECOUNT",
  12260. #endif
  12261. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12262. "OMIT_BUILTIN_TEST",
  12263. #endif
  12264. #ifdef SQLITE_OMIT_CAST
  12265. "OMIT_CAST",
  12266. #endif
  12267. #ifdef SQLITE_OMIT_CHECK
  12268. "OMIT_CHECK",
  12269. #endif
  12270. /* // redundant
  12271. ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12272. ** "OMIT_COMPILEOPTION_DIAGS",
  12273. ** #endif
  12274. */
  12275. #ifdef SQLITE_OMIT_COMPLETE
  12276. "OMIT_COMPLETE",
  12277. #endif
  12278. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12279. "OMIT_COMPOUND_SELECT",
  12280. #endif
  12281. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12282. "OMIT_DATETIME_FUNCS",
  12283. #endif
  12284. #ifdef SQLITE_OMIT_DECLTYPE
  12285. "OMIT_DECLTYPE",
  12286. #endif
  12287. #ifdef SQLITE_OMIT_DEPRECATED
  12288. "OMIT_DEPRECATED",
  12289. #endif
  12290. #ifdef SQLITE_OMIT_DISKIO
  12291. "OMIT_DISKIO",
  12292. #endif
  12293. #ifdef SQLITE_OMIT_EXPLAIN
  12294. "OMIT_EXPLAIN",
  12295. #endif
  12296. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12297. "OMIT_FLAG_PRAGMAS",
  12298. #endif
  12299. #ifdef SQLITE_OMIT_FLOATING_POINT
  12300. "OMIT_FLOATING_POINT",
  12301. #endif
  12302. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12303. "OMIT_FOREIGN_KEY",
  12304. #endif
  12305. #ifdef SQLITE_OMIT_GET_TABLE
  12306. "OMIT_GET_TABLE",
  12307. #endif
  12308. #ifdef SQLITE_OMIT_INCRBLOB
  12309. "OMIT_INCRBLOB",
  12310. #endif
  12311. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12312. "OMIT_INTEGRITY_CHECK",
  12313. #endif
  12314. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12315. "OMIT_LIKE_OPTIMIZATION",
  12316. #endif
  12317. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12318. "OMIT_LOAD_EXTENSION",
  12319. #endif
  12320. #ifdef SQLITE_OMIT_LOCALTIME
  12321. "OMIT_LOCALTIME",
  12322. #endif
  12323. #ifdef SQLITE_OMIT_LOOKASIDE
  12324. "OMIT_LOOKASIDE",
  12325. #endif
  12326. #ifdef SQLITE_OMIT_MEMORYDB
  12327. "OMIT_MEMORYDB",
  12328. #endif
  12329. #ifdef SQLITE_OMIT_MERGE_SORT
  12330. "OMIT_MERGE_SORT",
  12331. #endif
  12332. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12333. "OMIT_OR_OPTIMIZATION",
  12334. #endif
  12335. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12336. "OMIT_PAGER_PRAGMAS",
  12337. #endif
  12338. #ifdef SQLITE_OMIT_PRAGMA
  12339. "OMIT_PRAGMA",
  12340. #endif
  12341. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12342. "OMIT_PROGRESS_CALLBACK",
  12343. #endif
  12344. #ifdef SQLITE_OMIT_QUICKBALANCE
  12345. "OMIT_QUICKBALANCE",
  12346. #endif
  12347. #ifdef SQLITE_OMIT_REINDEX
  12348. "OMIT_REINDEX",
  12349. #endif
  12350. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12351. "OMIT_SCHEMA_PRAGMAS",
  12352. #endif
  12353. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12354. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12355. #endif
  12356. #ifdef SQLITE_OMIT_SHARED_CACHE
  12357. "OMIT_SHARED_CACHE",
  12358. #endif
  12359. #ifdef SQLITE_OMIT_SUBQUERY
  12360. "OMIT_SUBQUERY",
  12361. #endif
  12362. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12363. "OMIT_TCL_VARIABLE",
  12364. #endif
  12365. #ifdef SQLITE_OMIT_TEMPDB
  12366. "OMIT_TEMPDB",
  12367. #endif
  12368. #ifdef SQLITE_OMIT_TRACE
  12369. "OMIT_TRACE",
  12370. #endif
  12371. #ifdef SQLITE_OMIT_TRIGGER
  12372. "OMIT_TRIGGER",
  12373. #endif
  12374. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12375. "OMIT_TRUNCATE_OPTIMIZATION",
  12376. #endif
  12377. #ifdef SQLITE_OMIT_UTF16
  12378. "OMIT_UTF16",
  12379. #endif
  12380. #ifdef SQLITE_OMIT_VACUUM
  12381. "OMIT_VACUUM",
  12382. #endif
  12383. #ifdef SQLITE_OMIT_VIEW
  12384. "OMIT_VIEW",
  12385. #endif
  12386. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12387. "OMIT_VIRTUALTABLE",
  12388. #endif
  12389. #ifdef SQLITE_OMIT_WAL
  12390. "OMIT_WAL",
  12391. #endif
  12392. #ifdef SQLITE_OMIT_WSD
  12393. "OMIT_WSD",
  12394. #endif
  12395. #ifdef SQLITE_OMIT_XFER_OPT
  12396. "OMIT_XFER_OPT",
  12397. #endif
  12398. #ifdef SQLITE_PERFORMANCE_TRACE
  12399. "PERFORMANCE_TRACE",
  12400. #endif
  12401. #ifdef SQLITE_PROXY_DEBUG
  12402. "PROXY_DEBUG",
  12403. #endif
  12404. #ifdef SQLITE_RTREE_INT_ONLY
  12405. "RTREE_INT_ONLY",
  12406. #endif
  12407. #ifdef SQLITE_SECURE_DELETE
  12408. "SECURE_DELETE",
  12409. #endif
  12410. #ifdef SQLITE_SMALL_STACK
  12411. "SMALL_STACK",
  12412. #endif
  12413. #ifdef SQLITE_SOUNDEX
  12414. "SOUNDEX",
  12415. #endif
  12416. #ifdef SQLITE_TCL
  12417. "TCL",
  12418. #endif
  12419. #ifdef SQLITE_TEMP_STORE
  12420. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12421. #endif
  12422. #ifdef SQLITE_TEST
  12423. "TEST",
  12424. #endif
  12425. #ifdef SQLITE_THREADSAFE
  12426. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12427. #endif
  12428. #ifdef SQLITE_USE_ALLOCA
  12429. "USE_ALLOCA",
  12430. #endif
  12431. #ifdef SQLITE_ZERO_MALLOC
  12432. "ZERO_MALLOC"
  12433. #endif
  12434. };
  12435. /*
  12436. ** Given the name of a compile-time option, return true if that option
  12437. ** was used and false if not.
  12438. **
  12439. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12440. ** is not required for a match.
  12441. */
  12442. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12443. int i, n;
  12444. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12445. n = sqlite3Strlen30(zOptName);
  12446. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12447. ** linear search is adequate. No need for a binary search. */
  12448. for(i=0; i<ArraySize(azCompileOpt); i++){
  12449. if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
  12450. && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
  12451. }
  12452. return 0;
  12453. }
  12454. /*
  12455. ** Return the N-th compile-time option string. If N is out of range,
  12456. ** return a NULL pointer.
  12457. */
  12458. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12459. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12460. return azCompileOpt[N];
  12461. }
  12462. return 0;
  12463. }
  12464. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12465. /************** End of ctime.c ***********************************************/
  12466. /************** Begin file status.c ******************************************/
  12467. /*
  12468. ** 2008 June 18
  12469. **
  12470. ** The author disclaims copyright to this source code. In place of
  12471. ** a legal notice, here is a blessing:
  12472. **
  12473. ** May you do good and not evil.
  12474. ** May you find forgiveness for yourself and forgive others.
  12475. ** May you share freely, never taking more than you give.
  12476. **
  12477. *************************************************************************
  12478. **
  12479. ** This module implements the sqlite3_status() interface and related
  12480. ** functionality.
  12481. */
  12482. /************** Include vdbeInt.h in the middle of status.c ******************/
  12483. /************** Begin file vdbeInt.h *****************************************/
  12484. /*
  12485. ** 2003 September 6
  12486. **
  12487. ** The author disclaims copyright to this source code. In place of
  12488. ** a legal notice, here is a blessing:
  12489. **
  12490. ** May you do good and not evil.
  12491. ** May you find forgiveness for yourself and forgive others.
  12492. ** May you share freely, never taking more than you give.
  12493. **
  12494. *************************************************************************
  12495. ** This is the header file for information that is private to the
  12496. ** VDBE. This information used to all be at the top of the single
  12497. ** source code file "vdbe.c". When that file became too big (over
  12498. ** 6000 lines long) it was split up into several smaller files and
  12499. ** this header information was factored out.
  12500. */
  12501. #ifndef _VDBEINT_H_
  12502. #define _VDBEINT_H_
  12503. /*
  12504. ** SQL is translated into a sequence of instructions to be
  12505. ** executed by a virtual machine. Each instruction is an instance
  12506. ** of the following structure.
  12507. */
  12508. typedef struct VdbeOp Op;
  12509. /*
  12510. ** Boolean values
  12511. */
  12512. typedef unsigned char Bool;
  12513. /* Opaque type used by code in vdbesort.c */
  12514. typedef struct VdbeSorter VdbeSorter;
  12515. /* Opaque type used by the explainer */
  12516. typedef struct Explain Explain;
  12517. /*
  12518. ** A cursor is a pointer into a single BTree within a database file.
  12519. ** The cursor can seek to a BTree entry with a particular key, or
  12520. ** loop over all entries of the Btree. You can also insert new BTree
  12521. ** entries or retrieve the key or data from the entry that the cursor
  12522. ** is currently pointing to.
  12523. **
  12524. ** Every cursor that the virtual machine has open is represented by an
  12525. ** instance of the following structure.
  12526. */
  12527. struct VdbeCursor {
  12528. BtCursor *pCursor; /* The cursor structure of the backend */
  12529. Btree *pBt; /* Separate file holding temporary table */
  12530. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12531. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12532. int pseudoTableReg; /* Register holding pseudotable content. */
  12533. int nField; /* Number of fields in the header */
  12534. Bool zeroed; /* True if zeroed out and ready for reuse */
  12535. Bool rowidIsValid; /* True if lastRowid is valid */
  12536. Bool atFirst; /* True if pointing to first entry */
  12537. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12538. Bool nullRow; /* True if pointing to a row with no data */
  12539. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12540. Bool isTable; /* True if a table requiring integer keys */
  12541. Bool isIndex; /* True if an index containing keys only - no data */
  12542. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12543. Bool isSorter; /* True if a new-style sorter */
  12544. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12545. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12546. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12547. i64 seqCount; /* Sequence counter */
  12548. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12549. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12550. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12551. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12552. ** OP_IsUnique opcode on this cursor. */
  12553. int seekResult;
  12554. /* Cached information about the header for the data record that the
  12555. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12556. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12557. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12558. ** the cache is out of date.
  12559. **
  12560. ** aRow might point to (ephemeral) data for the current row, or it might
  12561. ** be NULL.
  12562. */
  12563. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12564. int payloadSize; /* Total number of bytes in the record */
  12565. u32 *aType; /* Type values for all entries in the record */
  12566. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12567. u8 *aRow; /* Data for the current row, if all on one page */
  12568. };
  12569. typedef struct VdbeCursor VdbeCursor;
  12570. /*
  12571. ** When a sub-program is executed (OP_Program), a structure of this type
  12572. ** is allocated to store the current value of the program counter, as
  12573. ** well as the current memory cell array and various other frame specific
  12574. ** values stored in the Vdbe struct. When the sub-program is finished,
  12575. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12576. ** restoring the state of the VM to as it was before the sub-program
  12577. ** began executing.
  12578. **
  12579. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12580. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12581. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12582. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12583. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12584. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12585. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12586. ** child frame are released.
  12587. **
  12588. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12589. ** set to NULL if the currently executing frame is the main program.
  12590. */
  12591. typedef struct VdbeFrame VdbeFrame;
  12592. struct VdbeFrame {
  12593. Vdbe *v; /* VM this frame belongs to */
  12594. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12595. Op *aOp; /* Program instructions for parent frame */
  12596. Mem *aMem; /* Array of memory cells for parent frame */
  12597. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12598. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12599. void *token; /* Copy of SubProgram.token */
  12600. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12601. u16 nCursor; /* Number of entries in apCsr */
  12602. int pc; /* Program Counter in parent (calling) frame */
  12603. int nOp; /* Size of aOp array */
  12604. int nMem; /* Number of entries in aMem */
  12605. int nOnceFlag; /* Number of entries in aOnceFlag */
  12606. int nChildMem; /* Number of memory cells for child frame */
  12607. int nChildCsr; /* Number of cursors for child frame */
  12608. int nChange; /* Statement changes (Vdbe.nChanges) */
  12609. };
  12610. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12611. /*
  12612. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12613. */
  12614. #define CACHE_STALE 0
  12615. /*
  12616. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12617. ** structures. Each Mem struct may cache multiple representations (string,
  12618. ** integer etc.) of the same value.
  12619. */
  12620. struct Mem {
  12621. sqlite3 *db; /* The associated database connection */
  12622. char *z; /* String or BLOB value */
  12623. double r; /* Real value */
  12624. union {
  12625. i64 i; /* Integer value used when MEM_Int is set in flags */
  12626. int nZero; /* Used when bit MEM_Zero is set in flags */
  12627. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12628. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12629. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12630. } u;
  12631. int n; /* Number of characters in string value, excluding '\0' */
  12632. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12633. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12634. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12635. #ifdef SQLITE_DEBUG
  12636. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12637. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12638. #endif
  12639. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12640. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12641. };
  12642. /* One or more of the following flags are set to indicate the validOK
  12643. ** representations of the value stored in the Mem struct.
  12644. **
  12645. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12646. ** No other flags may be set in this case.
  12647. **
  12648. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12649. ** Usually this is encoded in the same unicode encoding as the main
  12650. ** database (see below for exceptions). If the MEM_Term flag is also
  12651. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12652. ** flags may coexist with the MEM_Str flag.
  12653. */
  12654. #define MEM_Null 0x0001 /* Value is NULL */
  12655. #define MEM_Str 0x0002 /* Value is a string */
  12656. #define MEM_Int 0x0004 /* Value is an integer */
  12657. #define MEM_Real 0x0008 /* Value is a real number */
  12658. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12659. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12660. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12661. #define MEM_Invalid 0x0080 /* Value is undefined */
  12662. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12663. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12664. /* Whenever Mem contains a valid string or blob representation, one of
  12665. ** the following flags must be set to determine the memory management
  12666. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12667. ** string is \000 or \u0000 terminated
  12668. */
  12669. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12670. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12671. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12672. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12673. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12674. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12675. #ifdef SQLITE_OMIT_INCRBLOB
  12676. #undef MEM_Zero
  12677. #define MEM_Zero 0x0000
  12678. #endif
  12679. /*
  12680. ** Clear any existing type flags from a Mem and replace them with f
  12681. */
  12682. #define MemSetTypeFlag(p, f) \
  12683. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12684. /*
  12685. ** Return true if a memory cell is not marked as invalid. This macro
  12686. ** is for use inside assert() statements only.
  12687. */
  12688. #ifdef SQLITE_DEBUG
  12689. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12690. #endif
  12691. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  12692. ** additional information about auxiliary information bound to arguments
  12693. ** of the function. This is used to implement the sqlite3_get_auxdata()
  12694. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  12695. ** that can be associated with a constant argument to a function. This
  12696. ** allows functions such as "regexp" to compile their constant regular
  12697. ** expression argument once and reused the compiled code for multiple
  12698. ** invocations.
  12699. */
  12700. struct VdbeFunc {
  12701. FuncDef *pFunc; /* The definition of the function */
  12702. int nAux; /* Number of entries allocated for apAux[] */
  12703. struct AuxData {
  12704. void *pAux; /* Aux data for the i-th argument */
  12705. void (*xDelete)(void *); /* Destructor for the aux data */
  12706. } apAux[1]; /* One slot for each function argument */
  12707. };
  12708. /*
  12709. ** The "context" argument for a installable function. A pointer to an
  12710. ** instance of this structure is the first argument to the routines used
  12711. ** implement the SQL functions.
  12712. **
  12713. ** There is a typedef for this structure in sqlite.h. So all routines,
  12714. ** even the public interface to SQLite, can use a pointer to this structure.
  12715. ** But this file is the only place where the internal details of this
  12716. ** structure are known.
  12717. **
  12718. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12719. ** (Mem) which are only defined there.
  12720. */
  12721. struct sqlite3_context {
  12722. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12723. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  12724. Mem s; /* The return value is stored here */
  12725. Mem *pMem; /* Memory cell used to store aggregate context */
  12726. CollSeq *pColl; /* Collating sequence */
  12727. int isError; /* Error code returned by the function. */
  12728. int skipFlag; /* Skip skip accumulator loading if true */
  12729. };
  12730. /*
  12731. ** An Explain object accumulates indented output which is helpful
  12732. ** in describing recursive data structures.
  12733. */
  12734. struct Explain {
  12735. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12736. StrAccum str; /* The string being accumulated */
  12737. int nIndent; /* Number of elements in aIndent */
  12738. u16 aIndent[100]; /* Levels of indentation */
  12739. char zBase[100]; /* Initial space */
  12740. };
  12741. /* A bitfield type for use inside of structures. Always follow with :N where
  12742. ** N is the number of bits.
  12743. */
  12744. typedef unsigned bft; /* Bit Field Type */
  12745. /*
  12746. ** An instance of the virtual machine. This structure contains the complete
  12747. ** state of the virtual machine.
  12748. **
  12749. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12750. ** is really a pointer to an instance of this structure.
  12751. **
  12752. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12753. ** any virtual table method invocations made by the vdbe program. It is
  12754. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12755. ** variable is used for two purposes: to allow xDestroy methods to execute
  12756. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12757. ** malloc failure when SQLite is invoked recursively by a virtual table
  12758. ** method function.
  12759. */
  12760. struct Vdbe {
  12761. sqlite3 *db; /* The database connection that owns this statement */
  12762. Op *aOp; /* Space to hold the virtual machine's program */
  12763. Mem *aMem; /* The memory locations */
  12764. Mem **apArg; /* Arguments to currently executing user function */
  12765. Mem *aColName; /* Column names to return */
  12766. Mem *pResultSet; /* Pointer to an array of results */
  12767. int nMem; /* Number of memory locations currently allocated */
  12768. int nOp; /* Number of instructions in the program */
  12769. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12770. int nLabel; /* Number of labels used */
  12771. int *aLabel; /* Space to hold the labels */
  12772. u16 nResColumn; /* Number of columns in one row of the result set */
  12773. u16 nCursor; /* Number of slots in apCsr[] */
  12774. u32 magic; /* Magic number for sanity checking */
  12775. char *zErrMsg; /* Error message written here */
  12776. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12777. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12778. Mem *aVar; /* Values for the OP_Variable opcode. */
  12779. char **azVar; /* Name of variables */
  12780. ynVar nVar; /* Number of entries in aVar[] */
  12781. ynVar nzVar; /* Number of entries in azVar[] */
  12782. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12783. int pc; /* The program counter */
  12784. int rc; /* Value to return */
  12785. u8 errorAction; /* Recovery action to do in case of an error */
  12786. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12787. bft explain:2; /* True if EXPLAIN present on SQL command */
  12788. bft inVtabMethod:2; /* See comments above */
  12789. bft changeCntOn:1; /* True to update the change-counter */
  12790. bft expired:1; /* True if the VM needs to be recompiled */
  12791. bft runOnlyOnce:1; /* Automatically expire on reset */
  12792. bft usesStmtJournal:1; /* True if uses a statement journal */
  12793. bft readOnly:1; /* True for read-only statements */
  12794. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  12795. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  12796. int nChange; /* Number of db changes made since last reset */
  12797. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  12798. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  12799. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  12800. int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
  12801. #ifndef SQLITE_OMIT_TRACE
  12802. i64 startTime; /* Time when query started - used for profiling */
  12803. #endif
  12804. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  12805. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  12806. char *zSql; /* Text of the SQL statement that generated this */
  12807. void *pFree; /* Free this when deleting the vdbe */
  12808. #ifdef SQLITE_DEBUG
  12809. FILE *trace; /* Write an execution trace here, if not NULL */
  12810. #endif
  12811. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  12812. Explain *pExplain; /* The explainer */
  12813. char *zExplain; /* Explanation of data structures */
  12814. #endif
  12815. VdbeFrame *pFrame; /* Parent frame */
  12816. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  12817. int nFrame; /* Number of frames in pFrame list */
  12818. u32 expmask; /* Binding to these vars invalidates VM */
  12819. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  12820. int nOnceFlag; /* Size of array aOnceFlag[] */
  12821. u8 *aOnceFlag; /* Flags for OP_Once */
  12822. };
  12823. /*
  12824. ** The following are allowed values for Vdbe.magic
  12825. */
  12826. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  12827. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  12828. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  12829. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  12830. /*
  12831. ** Function prototypes
  12832. */
  12833. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  12834. void sqliteVdbePopStack(Vdbe*,int);
  12835. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  12836. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  12837. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  12838. #endif
  12839. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  12840. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  12841. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  12842. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  12843. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  12844. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  12845. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  12846. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  12847. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  12848. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  12849. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  12850. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  12851. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  12852. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  12853. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  12854. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  12855. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  12856. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  12857. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  12858. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  12859. #ifdef SQLITE_OMIT_FLOATING_POINT
  12860. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  12861. #else
  12862. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  12863. #endif
  12864. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  12865. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  12866. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  12867. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  12868. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  12869. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  12870. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  12871. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  12872. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  12873. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  12874. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  12875. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  12876. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  12877. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  12878. #define VdbeMemRelease(X) \
  12879. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  12880. sqlite3VdbeMemReleaseExternal(X);
  12881. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  12882. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  12883. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  12884. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  12885. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  12886. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  12887. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  12888. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  12889. #ifdef SQLITE_OMIT_MERGE_SORT
  12890. # define sqlite3VdbeSorterInit(Y,Z) SQLITE_OK
  12891. # define sqlite3VdbeSorterWrite(X,Y,Z) SQLITE_OK
  12892. # define sqlite3VdbeSorterClose(Y,Z)
  12893. # define sqlite3VdbeSorterRowkey(Y,Z) SQLITE_OK
  12894. # define sqlite3VdbeSorterRewind(X,Y,Z) SQLITE_OK
  12895. # define sqlite3VdbeSorterNext(X,Y,Z) SQLITE_OK
  12896. # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
  12897. #else
  12898. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  12899. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  12900. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  12901. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  12902. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  12903. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  12904. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  12905. #endif
  12906. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  12907. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  12908. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  12909. #else
  12910. # define sqlite3VdbeEnter(X)
  12911. # define sqlite3VdbeLeave(X)
  12912. #endif
  12913. #ifdef SQLITE_DEBUG
  12914. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  12915. #endif
  12916. #ifndef SQLITE_OMIT_FOREIGN_KEY
  12917. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  12918. #else
  12919. # define sqlite3VdbeCheckFk(p,i) 0
  12920. #endif
  12921. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  12922. #ifdef SQLITE_DEBUG
  12923. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  12924. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  12925. #endif
  12926. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  12927. #ifndef SQLITE_OMIT_INCRBLOB
  12928. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  12929. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  12930. #else
  12931. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  12932. #define ExpandBlob(P) SQLITE_OK
  12933. #endif
  12934. #endif /* !defined(_VDBEINT_H_) */
  12935. /************** End of vdbeInt.h *********************************************/
  12936. /************** Continuing where we left off in status.c *********************/
  12937. /*
  12938. ** Variables in which to record status information.
  12939. */
  12940. typedef struct sqlite3StatType sqlite3StatType;
  12941. static SQLITE_WSD struct sqlite3StatType {
  12942. int nowValue[10]; /* Current value */
  12943. int mxValue[10]; /* Maximum value */
  12944. } sqlite3Stat = { {0,}, {0,} };
  12945. /* The "wsdStat" macro will resolve to the status information
  12946. ** state vector. If writable static data is unsupported on the target,
  12947. ** we have to locate the state vector at run-time. In the more common
  12948. ** case where writable static data is supported, wsdStat can refer directly
  12949. ** to the "sqlite3Stat" state vector declared above.
  12950. */
  12951. #ifdef SQLITE_OMIT_WSD
  12952. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  12953. # define wsdStat x[0]
  12954. #else
  12955. # define wsdStatInit
  12956. # define wsdStat sqlite3Stat
  12957. #endif
  12958. /*
  12959. ** Return the current value of a status parameter.
  12960. */
  12961. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  12962. wsdStatInit;
  12963. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12964. return wsdStat.nowValue[op];
  12965. }
  12966. /*
  12967. ** Add N to the value of a status record. It is assumed that the
  12968. ** caller holds appropriate locks.
  12969. */
  12970. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  12971. wsdStatInit;
  12972. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12973. wsdStat.nowValue[op] += N;
  12974. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12975. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12976. }
  12977. }
  12978. /*
  12979. ** Set the value of a status to X.
  12980. */
  12981. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  12982. wsdStatInit;
  12983. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12984. wsdStat.nowValue[op] = X;
  12985. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12986. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12987. }
  12988. }
  12989. /*
  12990. ** Query status information.
  12991. **
  12992. ** This implementation assumes that reading or writing an aligned
  12993. ** 32-bit integer is an atomic operation. If that assumption is not true,
  12994. ** then this routine is not threadsafe.
  12995. */
  12996. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  12997. wsdStatInit;
  12998. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  12999. return SQLITE_MISUSE_BKPT;
  13000. }
  13001. *pCurrent = wsdStat.nowValue[op];
  13002. *pHighwater = wsdStat.mxValue[op];
  13003. if( resetFlag ){
  13004. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13005. }
  13006. return SQLITE_OK;
  13007. }
  13008. /*
  13009. ** Query status information for a single database connection
  13010. */
  13011. SQLITE_API int sqlite3_db_status(
  13012. sqlite3 *db, /* The database connection whose status is desired */
  13013. int op, /* Status verb */
  13014. int *pCurrent, /* Write current value here */
  13015. int *pHighwater, /* Write high-water mark here */
  13016. int resetFlag /* Reset high-water mark if true */
  13017. ){
  13018. int rc = SQLITE_OK; /* Return code */
  13019. sqlite3_mutex_enter(db->mutex);
  13020. switch( op ){
  13021. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13022. *pCurrent = db->lookaside.nOut;
  13023. *pHighwater = db->lookaside.mxOut;
  13024. if( resetFlag ){
  13025. db->lookaside.mxOut = db->lookaside.nOut;
  13026. }
  13027. break;
  13028. }
  13029. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13030. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13031. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13032. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13033. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13034. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13035. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13036. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13037. *pCurrent = 0;
  13038. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13039. if( resetFlag ){
  13040. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13041. }
  13042. break;
  13043. }
  13044. /*
  13045. ** Return an approximation for the amount of memory currently used
  13046. ** by all pagers associated with the given database connection. The
  13047. ** highwater mark is meaningless and is returned as zero.
  13048. */
  13049. case SQLITE_DBSTATUS_CACHE_USED: {
  13050. int totalUsed = 0;
  13051. int i;
  13052. sqlite3BtreeEnterAll(db);
  13053. for(i=0; i<db->nDb; i++){
  13054. Btree *pBt = db->aDb[i].pBt;
  13055. if( pBt ){
  13056. Pager *pPager = sqlite3BtreePager(pBt);
  13057. totalUsed += sqlite3PagerMemUsed(pPager);
  13058. }
  13059. }
  13060. sqlite3BtreeLeaveAll(db);
  13061. *pCurrent = totalUsed;
  13062. *pHighwater = 0;
  13063. break;
  13064. }
  13065. /*
  13066. ** *pCurrent gets an accurate estimate of the amount of memory used
  13067. ** to store the schema for all databases (main, temp, and any ATTACHed
  13068. ** databases. *pHighwater is set to zero.
  13069. */
  13070. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13071. int i; /* Used to iterate through schemas */
  13072. int nByte = 0; /* Used to accumulate return value */
  13073. sqlite3BtreeEnterAll(db);
  13074. db->pnBytesFreed = &nByte;
  13075. for(i=0; i<db->nDb; i++){
  13076. Schema *pSchema = db->aDb[i].pSchema;
  13077. if( ALWAYS(pSchema!=0) ){
  13078. HashElem *p;
  13079. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13080. pSchema->tblHash.count
  13081. + pSchema->trigHash.count
  13082. + pSchema->idxHash.count
  13083. + pSchema->fkeyHash.count
  13084. );
  13085. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13086. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13087. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13088. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13089. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13090. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13091. }
  13092. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13093. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13094. }
  13095. }
  13096. }
  13097. db->pnBytesFreed = 0;
  13098. sqlite3BtreeLeaveAll(db);
  13099. *pHighwater = 0;
  13100. *pCurrent = nByte;
  13101. break;
  13102. }
  13103. /*
  13104. ** *pCurrent gets an accurate estimate of the amount of memory used
  13105. ** to store all prepared statements.
  13106. ** *pHighwater is set to zero.
  13107. */
  13108. case SQLITE_DBSTATUS_STMT_USED: {
  13109. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13110. int nByte = 0; /* Used to accumulate return value */
  13111. db->pnBytesFreed = &nByte;
  13112. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13113. sqlite3VdbeClearObject(db, pVdbe);
  13114. sqlite3DbFree(db, pVdbe);
  13115. }
  13116. db->pnBytesFreed = 0;
  13117. *pHighwater = 0;
  13118. *pCurrent = nByte;
  13119. break;
  13120. }
  13121. /*
  13122. ** Set *pCurrent to the total cache hits or misses encountered by all
  13123. ** pagers the database handle is connected to. *pHighwater is always set
  13124. ** to zero.
  13125. */
  13126. case SQLITE_DBSTATUS_CACHE_HIT:
  13127. case SQLITE_DBSTATUS_CACHE_MISS:
  13128. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13129. int i;
  13130. int nRet = 0;
  13131. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13132. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13133. for(i=0; i<db->nDb; i++){
  13134. if( db->aDb[i].pBt ){
  13135. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13136. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13137. }
  13138. }
  13139. *pHighwater = 0;
  13140. *pCurrent = nRet;
  13141. break;
  13142. }
  13143. default: {
  13144. rc = SQLITE_ERROR;
  13145. }
  13146. }
  13147. sqlite3_mutex_leave(db->mutex);
  13148. return rc;
  13149. }
  13150. /************** End of status.c **********************************************/
  13151. /************** Begin file date.c ********************************************/
  13152. /*
  13153. ** 2003 October 31
  13154. **
  13155. ** The author disclaims copyright to this source code. In place of
  13156. ** a legal notice, here is a blessing:
  13157. **
  13158. ** May you do good and not evil.
  13159. ** May you find forgiveness for yourself and forgive others.
  13160. ** May you share freely, never taking more than you give.
  13161. **
  13162. *************************************************************************
  13163. ** This file contains the C functions that implement date and time
  13164. ** functions for SQLite.
  13165. **
  13166. ** There is only one exported symbol in this file - the function
  13167. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13168. ** All other code has file scope.
  13169. **
  13170. ** SQLite processes all times and dates as Julian Day numbers. The
  13171. ** dates and times are stored as the number of days since noon
  13172. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13173. ** calendar system.
  13174. **
  13175. ** 1970-01-01 00:00:00 is JD 2440587.5
  13176. ** 2000-01-01 00:00:00 is JD 2451544.5
  13177. **
  13178. ** This implemention requires years to be expressed as a 4-digit number
  13179. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13180. ** be represented, even though julian day numbers allow a much wider
  13181. ** range of dates.
  13182. **
  13183. ** The Gregorian calendar system is used for all dates and times,
  13184. ** even those that predate the Gregorian calendar. Historians usually
  13185. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13186. ** dates afterwards, depending on locale. Beware of this difference.
  13187. **
  13188. ** The conversion algorithms are implemented based on descriptions
  13189. ** in the following text:
  13190. **
  13191. ** Jean Meeus
  13192. ** Astronomical Algorithms, 2nd Edition, 1998
  13193. ** ISBM 0-943396-61-1
  13194. ** Willmann-Bell, Inc
  13195. ** Richmond, Virginia (USA)
  13196. */
  13197. /* #include <stdlib.h> */
  13198. /* #include <assert.h> */
  13199. #include <time.h>
  13200. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13201. /*
  13202. ** A structure for holding a single date and time.
  13203. */
  13204. typedef struct DateTime DateTime;
  13205. struct DateTime {
  13206. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13207. int Y, M, D; /* Year, month, and day */
  13208. int h, m; /* Hour and minutes */
  13209. int tz; /* Timezone offset in minutes */
  13210. double s; /* Seconds */
  13211. char validYMD; /* True (1) if Y,M,D are valid */
  13212. char validHMS; /* True (1) if h,m,s are valid */
  13213. char validJD; /* True (1) if iJD is valid */
  13214. char validTZ; /* True (1) if tz is valid */
  13215. };
  13216. /*
  13217. ** Convert zDate into one or more integers. Additional arguments
  13218. ** come in groups of 5 as follows:
  13219. **
  13220. ** N number of digits in the integer
  13221. ** min minimum allowed value of the integer
  13222. ** max maximum allowed value of the integer
  13223. ** nextC first character after the integer
  13224. ** pVal where to write the integers value.
  13225. **
  13226. ** Conversions continue until one with nextC==0 is encountered.
  13227. ** The function returns the number of successful conversions.
  13228. */
  13229. static int getDigits(const char *zDate, ...){
  13230. va_list ap;
  13231. int val;
  13232. int N;
  13233. int min;
  13234. int max;
  13235. int nextC;
  13236. int *pVal;
  13237. int cnt = 0;
  13238. va_start(ap, zDate);
  13239. do{
  13240. N = va_arg(ap, int);
  13241. min = va_arg(ap, int);
  13242. max = va_arg(ap, int);
  13243. nextC = va_arg(ap, int);
  13244. pVal = va_arg(ap, int*);
  13245. val = 0;
  13246. while( N-- ){
  13247. if( !sqlite3Isdigit(*zDate) ){
  13248. goto end_getDigits;
  13249. }
  13250. val = val*10 + *zDate - '0';
  13251. zDate++;
  13252. }
  13253. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13254. goto end_getDigits;
  13255. }
  13256. *pVal = val;
  13257. zDate++;
  13258. cnt++;
  13259. }while( nextC );
  13260. end_getDigits:
  13261. va_end(ap);
  13262. return cnt;
  13263. }
  13264. /*
  13265. ** Parse a timezone extension on the end of a date-time.
  13266. ** The extension is of the form:
  13267. **
  13268. ** (+/-)HH:MM
  13269. **
  13270. ** Or the "zulu" notation:
  13271. **
  13272. ** Z
  13273. **
  13274. ** If the parse is successful, write the number of minutes
  13275. ** of change in p->tz and return 0. If a parser error occurs,
  13276. ** return non-zero.
  13277. **
  13278. ** A missing specifier is not considered an error.
  13279. */
  13280. static int parseTimezone(const char *zDate, DateTime *p){
  13281. int sgn = 0;
  13282. int nHr, nMn;
  13283. int c;
  13284. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13285. p->tz = 0;
  13286. c = *zDate;
  13287. if( c=='-' ){
  13288. sgn = -1;
  13289. }else if( c=='+' ){
  13290. sgn = +1;
  13291. }else if( c=='Z' || c=='z' ){
  13292. zDate++;
  13293. goto zulu_time;
  13294. }else{
  13295. return c!=0;
  13296. }
  13297. zDate++;
  13298. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13299. return 1;
  13300. }
  13301. zDate += 5;
  13302. p->tz = sgn*(nMn + nHr*60);
  13303. zulu_time:
  13304. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13305. return *zDate!=0;
  13306. }
  13307. /*
  13308. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13309. ** The HH, MM, and SS must each be exactly 2 digits. The
  13310. ** fractional seconds FFFF can be one or more digits.
  13311. **
  13312. ** Return 1 if there is a parsing error and 0 on success.
  13313. */
  13314. static int parseHhMmSs(const char *zDate, DateTime *p){
  13315. int h, m, s;
  13316. double ms = 0.0;
  13317. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13318. return 1;
  13319. }
  13320. zDate += 5;
  13321. if( *zDate==':' ){
  13322. zDate++;
  13323. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13324. return 1;
  13325. }
  13326. zDate += 2;
  13327. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13328. double rScale = 1.0;
  13329. zDate++;
  13330. while( sqlite3Isdigit(*zDate) ){
  13331. ms = ms*10.0 + *zDate - '0';
  13332. rScale *= 10.0;
  13333. zDate++;
  13334. }
  13335. ms /= rScale;
  13336. }
  13337. }else{
  13338. s = 0;
  13339. }
  13340. p->validJD = 0;
  13341. p->validHMS = 1;
  13342. p->h = h;
  13343. p->m = m;
  13344. p->s = s + ms;
  13345. if( parseTimezone(zDate, p) ) return 1;
  13346. p->validTZ = (p->tz!=0)?1:0;
  13347. return 0;
  13348. }
  13349. /*
  13350. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13351. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13352. **
  13353. ** Reference: Meeus page 61
  13354. */
  13355. static void computeJD(DateTime *p){
  13356. int Y, M, D, A, B, X1, X2;
  13357. if( p->validJD ) return;
  13358. if( p->validYMD ){
  13359. Y = p->Y;
  13360. M = p->M;
  13361. D = p->D;
  13362. }else{
  13363. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13364. M = 1;
  13365. D = 1;
  13366. }
  13367. if( M<=2 ){
  13368. Y--;
  13369. M += 12;
  13370. }
  13371. A = Y/100;
  13372. B = 2 - A + (A/4);
  13373. X1 = 36525*(Y+4716)/100;
  13374. X2 = 306001*(M+1)/10000;
  13375. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13376. p->validJD = 1;
  13377. if( p->validHMS ){
  13378. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13379. if( p->validTZ ){
  13380. p->iJD -= p->tz*60000;
  13381. p->validYMD = 0;
  13382. p->validHMS = 0;
  13383. p->validTZ = 0;
  13384. }
  13385. }
  13386. }
  13387. /*
  13388. ** Parse dates of the form
  13389. **
  13390. ** YYYY-MM-DD HH:MM:SS.FFF
  13391. ** YYYY-MM-DD HH:MM:SS
  13392. ** YYYY-MM-DD HH:MM
  13393. ** YYYY-MM-DD
  13394. **
  13395. ** Write the result into the DateTime structure and return 0
  13396. ** on success and 1 if the input string is not a well-formed
  13397. ** date.
  13398. */
  13399. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13400. int Y, M, D, neg;
  13401. if( zDate[0]=='-' ){
  13402. zDate++;
  13403. neg = 1;
  13404. }else{
  13405. neg = 0;
  13406. }
  13407. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13408. return 1;
  13409. }
  13410. zDate += 10;
  13411. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13412. if( parseHhMmSs(zDate, p)==0 ){
  13413. /* We got the time */
  13414. }else if( *zDate==0 ){
  13415. p->validHMS = 0;
  13416. }else{
  13417. return 1;
  13418. }
  13419. p->validJD = 0;
  13420. p->validYMD = 1;
  13421. p->Y = neg ? -Y : Y;
  13422. p->M = M;
  13423. p->D = D;
  13424. if( p->validTZ ){
  13425. computeJD(p);
  13426. }
  13427. return 0;
  13428. }
  13429. /*
  13430. ** Set the time to the current time reported by the VFS.
  13431. **
  13432. ** Return the number of errors.
  13433. */
  13434. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13435. sqlite3 *db = sqlite3_context_db_handle(context);
  13436. if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
  13437. p->validJD = 1;
  13438. return 0;
  13439. }else{
  13440. return 1;
  13441. }
  13442. }
  13443. /*
  13444. ** Attempt to parse the given string into a Julian Day Number. Return
  13445. ** the number of errors.
  13446. **
  13447. ** The following are acceptable forms for the input string:
  13448. **
  13449. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13450. ** DDDD.DD
  13451. ** now
  13452. **
  13453. ** In the first form, the +/-HH:MM is always optional. The fractional
  13454. ** seconds extension (the ".FFF") is optional. The seconds portion
  13455. ** (":SS.FFF") is option. The year and date can be omitted as long
  13456. ** as there is a time string. The time string can be omitted as long
  13457. ** as there is a year and date.
  13458. */
  13459. static int parseDateOrTime(
  13460. sqlite3_context *context,
  13461. const char *zDate,
  13462. DateTime *p
  13463. ){
  13464. double r;
  13465. if( parseYyyyMmDd(zDate,p)==0 ){
  13466. return 0;
  13467. }else if( parseHhMmSs(zDate, p)==0 ){
  13468. return 0;
  13469. }else if( sqlite3StrICmp(zDate,"now")==0){
  13470. return setDateTimeToCurrent(context, p);
  13471. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13472. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13473. p->validJD = 1;
  13474. return 0;
  13475. }
  13476. return 1;
  13477. }
  13478. /*
  13479. ** Compute the Year, Month, and Day from the julian day number.
  13480. */
  13481. static void computeYMD(DateTime *p){
  13482. int Z, A, B, C, D, E, X1;
  13483. if( p->validYMD ) return;
  13484. if( !p->validJD ){
  13485. p->Y = 2000;
  13486. p->M = 1;
  13487. p->D = 1;
  13488. }else{
  13489. Z = (int)((p->iJD + 43200000)/86400000);
  13490. A = (int)((Z - 1867216.25)/36524.25);
  13491. A = Z + 1 + A - (A/4);
  13492. B = A + 1524;
  13493. C = (int)((B - 122.1)/365.25);
  13494. D = (36525*C)/100;
  13495. E = (int)((B-D)/30.6001);
  13496. X1 = (int)(30.6001*E);
  13497. p->D = B - D - X1;
  13498. p->M = E<14 ? E-1 : E-13;
  13499. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13500. }
  13501. p->validYMD = 1;
  13502. }
  13503. /*
  13504. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13505. */
  13506. static void computeHMS(DateTime *p){
  13507. int s;
  13508. if( p->validHMS ) return;
  13509. computeJD(p);
  13510. s = (int)((p->iJD + 43200000) % 86400000);
  13511. p->s = s/1000.0;
  13512. s = (int)p->s;
  13513. p->s -= s;
  13514. p->h = s/3600;
  13515. s -= p->h*3600;
  13516. p->m = s/60;
  13517. p->s += s - p->m*60;
  13518. p->validHMS = 1;
  13519. }
  13520. /*
  13521. ** Compute both YMD and HMS
  13522. */
  13523. static void computeYMD_HMS(DateTime *p){
  13524. computeYMD(p);
  13525. computeHMS(p);
  13526. }
  13527. /*
  13528. ** Clear the YMD and HMS and the TZ
  13529. */
  13530. static void clearYMD_HMS_TZ(DateTime *p){
  13531. p->validYMD = 0;
  13532. p->validHMS = 0;
  13533. p->validTZ = 0;
  13534. }
  13535. /*
  13536. ** On recent Windows platforms, the localtime_s() function is available
  13537. ** as part of the "Secure CRT". It is essentially equivalent to
  13538. ** localtime_r() available under most POSIX platforms, except that the
  13539. ** order of the parameters is reversed.
  13540. **
  13541. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13542. **
  13543. ** If the user has not indicated to use localtime_r() or localtime_s()
  13544. ** already, check for an MSVC build environment that provides
  13545. ** localtime_s().
  13546. */
  13547. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13548. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13549. #define HAVE_LOCALTIME_S 1
  13550. #endif
  13551. #ifndef SQLITE_OMIT_LOCALTIME
  13552. /*
  13553. ** The following routine implements the rough equivalent of localtime_r()
  13554. ** using whatever operating-system specific localtime facility that
  13555. ** is available. This routine returns 0 on success and
  13556. ** non-zero on any kind of error.
  13557. **
  13558. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13559. ** routine will always fail.
  13560. */
  13561. static int osLocaltime(time_t *t, struct tm *pTm){
  13562. int rc;
  13563. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13564. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13565. struct tm *pX;
  13566. #if SQLITE_THREADSAFE>0
  13567. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13568. #endif
  13569. sqlite3_mutex_enter(mutex);
  13570. pX = localtime(t);
  13571. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13572. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13573. #endif
  13574. if( pX ) *pTm = *pX;
  13575. sqlite3_mutex_leave(mutex);
  13576. rc = pX==0;
  13577. #else
  13578. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13579. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13580. #endif
  13581. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13582. rc = localtime_r(t, pTm)==0;
  13583. #else
  13584. rc = localtime_s(pTm, t);
  13585. #endif /* HAVE_LOCALTIME_R */
  13586. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13587. return rc;
  13588. }
  13589. #endif /* SQLITE_OMIT_LOCALTIME */
  13590. #ifndef SQLITE_OMIT_LOCALTIME
  13591. /*
  13592. ** Compute the difference (in milliseconds) between localtime and UTC
  13593. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13594. ** return this value and set *pRc to SQLITE_OK.
  13595. **
  13596. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13597. ** is undefined in this case.
  13598. */
  13599. static sqlite3_int64 localtimeOffset(
  13600. DateTime *p, /* Date at which to calculate offset */
  13601. sqlite3_context *pCtx, /* Write error here if one occurs */
  13602. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13603. ){
  13604. DateTime x, y;
  13605. time_t t;
  13606. struct tm sLocal;
  13607. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13608. memset(&sLocal, 0, sizeof(sLocal));
  13609. x = *p;
  13610. computeYMD_HMS(&x);
  13611. if( x.Y<1971 || x.Y>=2038 ){
  13612. x.Y = 2000;
  13613. x.M = 1;
  13614. x.D = 1;
  13615. x.h = 0;
  13616. x.m = 0;
  13617. x.s = 0.0;
  13618. } else {
  13619. int s = (int)(x.s + 0.5);
  13620. x.s = s;
  13621. }
  13622. x.tz = 0;
  13623. x.validJD = 0;
  13624. computeJD(&x);
  13625. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13626. if( osLocaltime(&t, &sLocal) ){
  13627. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13628. *pRc = SQLITE_ERROR;
  13629. return 0;
  13630. }
  13631. y.Y = sLocal.tm_year + 1900;
  13632. y.M = sLocal.tm_mon + 1;
  13633. y.D = sLocal.tm_mday;
  13634. y.h = sLocal.tm_hour;
  13635. y.m = sLocal.tm_min;
  13636. y.s = sLocal.tm_sec;
  13637. y.validYMD = 1;
  13638. y.validHMS = 1;
  13639. y.validJD = 0;
  13640. y.validTZ = 0;
  13641. computeJD(&y);
  13642. *pRc = SQLITE_OK;
  13643. return y.iJD - x.iJD;
  13644. }
  13645. #endif /* SQLITE_OMIT_LOCALTIME */
  13646. /*
  13647. ** Process a modifier to a date-time stamp. The modifiers are
  13648. ** as follows:
  13649. **
  13650. ** NNN days
  13651. ** NNN hours
  13652. ** NNN minutes
  13653. ** NNN.NNNN seconds
  13654. ** NNN months
  13655. ** NNN years
  13656. ** start of month
  13657. ** start of year
  13658. ** start of week
  13659. ** start of day
  13660. ** weekday N
  13661. ** unixepoch
  13662. ** localtime
  13663. ** utc
  13664. **
  13665. ** Return 0 on success and 1 if there is any kind of error. If the error
  13666. ** is in a system call (i.e. localtime()), then an error message is written
  13667. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13668. ** written to pCtx.
  13669. */
  13670. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13671. int rc = 1;
  13672. int n;
  13673. double r;
  13674. char *z, zBuf[30];
  13675. z = zBuf;
  13676. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13677. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13678. }
  13679. z[n] = 0;
  13680. switch( z[0] ){
  13681. #ifndef SQLITE_OMIT_LOCALTIME
  13682. case 'l': {
  13683. /* localtime
  13684. **
  13685. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13686. ** show local time.
  13687. */
  13688. if( strcmp(z, "localtime")==0 ){
  13689. computeJD(p);
  13690. p->iJD += localtimeOffset(p, pCtx, &rc);
  13691. clearYMD_HMS_TZ(p);
  13692. }
  13693. break;
  13694. }
  13695. #endif
  13696. case 'u': {
  13697. /*
  13698. ** unixepoch
  13699. **
  13700. ** Treat the current value of p->iJD as the number of
  13701. ** seconds since 1970. Convert to a real julian day number.
  13702. */
  13703. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13704. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13705. clearYMD_HMS_TZ(p);
  13706. rc = 0;
  13707. }
  13708. #ifndef SQLITE_OMIT_LOCALTIME
  13709. else if( strcmp(z, "utc")==0 ){
  13710. sqlite3_int64 c1;
  13711. computeJD(p);
  13712. c1 = localtimeOffset(p, pCtx, &rc);
  13713. if( rc==SQLITE_OK ){
  13714. p->iJD -= c1;
  13715. clearYMD_HMS_TZ(p);
  13716. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13717. }
  13718. }
  13719. #endif
  13720. break;
  13721. }
  13722. case 'w': {
  13723. /*
  13724. ** weekday N
  13725. **
  13726. ** Move the date to the same time on the next occurrence of
  13727. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13728. ** date is already on the appropriate weekday, this is a no-op.
  13729. */
  13730. if( strncmp(z, "weekday ", 8)==0
  13731. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13732. && (n=(int)r)==r && n>=0 && r<7 ){
  13733. sqlite3_int64 Z;
  13734. computeYMD_HMS(p);
  13735. p->validTZ = 0;
  13736. p->validJD = 0;
  13737. computeJD(p);
  13738. Z = ((p->iJD + 129600000)/86400000) % 7;
  13739. if( Z>n ) Z -= 7;
  13740. p->iJD += (n - Z)*86400000;
  13741. clearYMD_HMS_TZ(p);
  13742. rc = 0;
  13743. }
  13744. break;
  13745. }
  13746. case 's': {
  13747. /*
  13748. ** start of TTTTT
  13749. **
  13750. ** Move the date backwards to the beginning of the current day,
  13751. ** or month or year.
  13752. */
  13753. if( strncmp(z, "start of ", 9)!=0 ) break;
  13754. z += 9;
  13755. computeYMD(p);
  13756. p->validHMS = 1;
  13757. p->h = p->m = 0;
  13758. p->s = 0.0;
  13759. p->validTZ = 0;
  13760. p->validJD = 0;
  13761. if( strcmp(z,"month")==0 ){
  13762. p->D = 1;
  13763. rc = 0;
  13764. }else if( strcmp(z,"year")==0 ){
  13765. computeYMD(p);
  13766. p->M = 1;
  13767. p->D = 1;
  13768. rc = 0;
  13769. }else if( strcmp(z,"day")==0 ){
  13770. rc = 0;
  13771. }
  13772. break;
  13773. }
  13774. case '+':
  13775. case '-':
  13776. case '0':
  13777. case '1':
  13778. case '2':
  13779. case '3':
  13780. case '4':
  13781. case '5':
  13782. case '6':
  13783. case '7':
  13784. case '8':
  13785. case '9': {
  13786. double rRounder;
  13787. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  13788. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  13789. rc = 1;
  13790. break;
  13791. }
  13792. if( z[n]==':' ){
  13793. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  13794. ** specified number of hours, minutes, seconds, and fractional seconds
  13795. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  13796. ** omitted.
  13797. */
  13798. const char *z2 = z;
  13799. DateTime tx;
  13800. sqlite3_int64 day;
  13801. if( !sqlite3Isdigit(*z2) ) z2++;
  13802. memset(&tx, 0, sizeof(tx));
  13803. if( parseHhMmSs(z2, &tx) ) break;
  13804. computeJD(&tx);
  13805. tx.iJD -= 43200000;
  13806. day = tx.iJD/86400000;
  13807. tx.iJD -= day*86400000;
  13808. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  13809. computeJD(p);
  13810. clearYMD_HMS_TZ(p);
  13811. p->iJD += tx.iJD;
  13812. rc = 0;
  13813. break;
  13814. }
  13815. z += n;
  13816. while( sqlite3Isspace(*z) ) z++;
  13817. n = sqlite3Strlen30(z);
  13818. if( n>10 || n<3 ) break;
  13819. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  13820. computeJD(p);
  13821. rc = 0;
  13822. rRounder = r<0 ? -0.5 : +0.5;
  13823. if( n==3 && strcmp(z,"day")==0 ){
  13824. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  13825. }else if( n==4 && strcmp(z,"hour")==0 ){
  13826. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  13827. }else if( n==6 && strcmp(z,"minute")==0 ){
  13828. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  13829. }else if( n==6 && strcmp(z,"second")==0 ){
  13830. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  13831. }else if( n==5 && strcmp(z,"month")==0 ){
  13832. int x, y;
  13833. computeYMD_HMS(p);
  13834. p->M += (int)r;
  13835. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  13836. p->Y += x;
  13837. p->M -= x*12;
  13838. p->validJD = 0;
  13839. computeJD(p);
  13840. y = (int)r;
  13841. if( y!=r ){
  13842. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  13843. }
  13844. }else if( n==4 && strcmp(z,"year")==0 ){
  13845. int y = (int)r;
  13846. computeYMD_HMS(p);
  13847. p->Y += y;
  13848. p->validJD = 0;
  13849. computeJD(p);
  13850. if( y!=r ){
  13851. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  13852. }
  13853. }else{
  13854. rc = 1;
  13855. }
  13856. clearYMD_HMS_TZ(p);
  13857. break;
  13858. }
  13859. default: {
  13860. break;
  13861. }
  13862. }
  13863. return rc;
  13864. }
  13865. /*
  13866. ** Process time function arguments. argv[0] is a date-time stamp.
  13867. ** argv[1] and following are modifiers. Parse them all and write
  13868. ** the resulting time into the DateTime structure p. Return 0
  13869. ** on success and 1 if there are any errors.
  13870. **
  13871. ** If there are zero parameters (if even argv[0] is undefined)
  13872. ** then assume a default value of "now" for argv[0].
  13873. */
  13874. static int isDate(
  13875. sqlite3_context *context,
  13876. int argc,
  13877. sqlite3_value **argv,
  13878. DateTime *p
  13879. ){
  13880. int i;
  13881. const unsigned char *z;
  13882. int eType;
  13883. memset(p, 0, sizeof(*p));
  13884. if( argc==0 ){
  13885. return setDateTimeToCurrent(context, p);
  13886. }
  13887. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  13888. || eType==SQLITE_INTEGER ){
  13889. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  13890. p->validJD = 1;
  13891. }else{
  13892. z = sqlite3_value_text(argv[0]);
  13893. if( !z || parseDateOrTime(context, (char*)z, p) ){
  13894. return 1;
  13895. }
  13896. }
  13897. for(i=1; i<argc; i++){
  13898. z = sqlite3_value_text(argv[i]);
  13899. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  13900. }
  13901. return 0;
  13902. }
  13903. /*
  13904. ** The following routines implement the various date and time functions
  13905. ** of SQLite.
  13906. */
  13907. /*
  13908. ** julianday( TIMESTRING, MOD, MOD, ...)
  13909. **
  13910. ** Return the julian day number of the date specified in the arguments
  13911. */
  13912. static void juliandayFunc(
  13913. sqlite3_context *context,
  13914. int argc,
  13915. sqlite3_value **argv
  13916. ){
  13917. DateTime x;
  13918. if( isDate(context, argc, argv, &x)==0 ){
  13919. computeJD(&x);
  13920. sqlite3_result_double(context, x.iJD/86400000.0);
  13921. }
  13922. }
  13923. /*
  13924. ** datetime( TIMESTRING, MOD, MOD, ...)
  13925. **
  13926. ** Return YYYY-MM-DD HH:MM:SS
  13927. */
  13928. static void datetimeFunc(
  13929. sqlite3_context *context,
  13930. int argc,
  13931. sqlite3_value **argv
  13932. ){
  13933. DateTime x;
  13934. if( isDate(context, argc, argv, &x)==0 ){
  13935. char zBuf[100];
  13936. computeYMD_HMS(&x);
  13937. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  13938. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  13939. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13940. }
  13941. }
  13942. /*
  13943. ** time( TIMESTRING, MOD, MOD, ...)
  13944. **
  13945. ** Return HH:MM:SS
  13946. */
  13947. static void timeFunc(
  13948. sqlite3_context *context,
  13949. int argc,
  13950. sqlite3_value **argv
  13951. ){
  13952. DateTime x;
  13953. if( isDate(context, argc, argv, &x)==0 ){
  13954. char zBuf[100];
  13955. computeHMS(&x);
  13956. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  13957. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13958. }
  13959. }
  13960. /*
  13961. ** date( TIMESTRING, MOD, MOD, ...)
  13962. **
  13963. ** Return YYYY-MM-DD
  13964. */
  13965. static void dateFunc(
  13966. sqlite3_context *context,
  13967. int argc,
  13968. sqlite3_value **argv
  13969. ){
  13970. DateTime x;
  13971. if( isDate(context, argc, argv, &x)==0 ){
  13972. char zBuf[100];
  13973. computeYMD(&x);
  13974. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  13975. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13976. }
  13977. }
  13978. /*
  13979. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  13980. **
  13981. ** Return a string described by FORMAT. Conversions as follows:
  13982. **
  13983. ** %d day of month
  13984. ** %f ** fractional seconds SS.SSS
  13985. ** %H hour 00-24
  13986. ** %j day of year 000-366
  13987. ** %J ** Julian day number
  13988. ** %m month 01-12
  13989. ** %M minute 00-59
  13990. ** %s seconds since 1970-01-01
  13991. ** %S seconds 00-59
  13992. ** %w day of week 0-6 sunday==0
  13993. ** %W week of year 00-53
  13994. ** %Y year 0000-9999
  13995. ** %% %
  13996. */
  13997. static void strftimeFunc(
  13998. sqlite3_context *context,
  13999. int argc,
  14000. sqlite3_value **argv
  14001. ){
  14002. DateTime x;
  14003. u64 n;
  14004. size_t i,j;
  14005. char *z;
  14006. sqlite3 *db;
  14007. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14008. char zBuf[100];
  14009. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14010. db = sqlite3_context_db_handle(context);
  14011. for(i=0, n=1; zFmt[i]; i++, n++){
  14012. if( zFmt[i]=='%' ){
  14013. switch( zFmt[i+1] ){
  14014. case 'd':
  14015. case 'H':
  14016. case 'm':
  14017. case 'M':
  14018. case 'S':
  14019. case 'W':
  14020. n++;
  14021. /* fall thru */
  14022. case 'w':
  14023. case '%':
  14024. break;
  14025. case 'f':
  14026. n += 8;
  14027. break;
  14028. case 'j':
  14029. n += 3;
  14030. break;
  14031. case 'Y':
  14032. n += 8;
  14033. break;
  14034. case 's':
  14035. case 'J':
  14036. n += 50;
  14037. break;
  14038. default:
  14039. return; /* ERROR. return a NULL */
  14040. }
  14041. i++;
  14042. }
  14043. }
  14044. testcase( n==sizeof(zBuf)-1 );
  14045. testcase( n==sizeof(zBuf) );
  14046. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14047. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14048. if( n<sizeof(zBuf) ){
  14049. z = zBuf;
  14050. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14051. sqlite3_result_error_toobig(context);
  14052. return;
  14053. }else{
  14054. z = sqlite3DbMallocRaw(db, (int)n);
  14055. if( z==0 ){
  14056. sqlite3_result_error_nomem(context);
  14057. return;
  14058. }
  14059. }
  14060. computeJD(&x);
  14061. computeYMD_HMS(&x);
  14062. for(i=j=0; zFmt[i]; i++){
  14063. if( zFmt[i]!='%' ){
  14064. z[j++] = zFmt[i];
  14065. }else{
  14066. i++;
  14067. switch( zFmt[i] ){
  14068. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14069. case 'f': {
  14070. double s = x.s;
  14071. if( s>59.999 ) s = 59.999;
  14072. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14073. j += sqlite3Strlen30(&z[j]);
  14074. break;
  14075. }
  14076. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14077. case 'W': /* Fall thru */
  14078. case 'j': {
  14079. int nDay; /* Number of days since 1st day of year */
  14080. DateTime y = x;
  14081. y.validJD = 0;
  14082. y.M = 1;
  14083. y.D = 1;
  14084. computeJD(&y);
  14085. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14086. if( zFmt[i]=='W' ){
  14087. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14088. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14089. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14090. j += 2;
  14091. }else{
  14092. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14093. j += 3;
  14094. }
  14095. break;
  14096. }
  14097. case 'J': {
  14098. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14099. j+=sqlite3Strlen30(&z[j]);
  14100. break;
  14101. }
  14102. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14103. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14104. case 's': {
  14105. sqlite3_snprintf(30,&z[j],"%lld",
  14106. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14107. j += sqlite3Strlen30(&z[j]);
  14108. break;
  14109. }
  14110. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14111. case 'w': {
  14112. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14113. break;
  14114. }
  14115. case 'Y': {
  14116. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14117. break;
  14118. }
  14119. default: z[j++] = '%'; break;
  14120. }
  14121. }
  14122. }
  14123. z[j] = 0;
  14124. sqlite3_result_text(context, z, -1,
  14125. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14126. }
  14127. /*
  14128. ** current_time()
  14129. **
  14130. ** This function returns the same value as time('now').
  14131. */
  14132. static void ctimeFunc(
  14133. sqlite3_context *context,
  14134. int NotUsed,
  14135. sqlite3_value **NotUsed2
  14136. ){
  14137. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14138. timeFunc(context, 0, 0);
  14139. }
  14140. /*
  14141. ** current_date()
  14142. **
  14143. ** This function returns the same value as date('now').
  14144. */
  14145. static void cdateFunc(
  14146. sqlite3_context *context,
  14147. int NotUsed,
  14148. sqlite3_value **NotUsed2
  14149. ){
  14150. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14151. dateFunc(context, 0, 0);
  14152. }
  14153. /*
  14154. ** current_timestamp()
  14155. **
  14156. ** This function returns the same value as datetime('now').
  14157. */
  14158. static void ctimestampFunc(
  14159. sqlite3_context *context,
  14160. int NotUsed,
  14161. sqlite3_value **NotUsed2
  14162. ){
  14163. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14164. datetimeFunc(context, 0, 0);
  14165. }
  14166. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14167. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14168. /*
  14169. ** If the library is compiled to omit the full-scale date and time
  14170. ** handling (to get a smaller binary), the following minimal version
  14171. ** of the functions current_time(), current_date() and current_timestamp()
  14172. ** are included instead. This is to support column declarations that
  14173. ** include "DEFAULT CURRENT_TIME" etc.
  14174. **
  14175. ** This function uses the C-library functions time(), gmtime()
  14176. ** and strftime(). The format string to pass to strftime() is supplied
  14177. ** as the user-data for the function.
  14178. */
  14179. static void currentTimeFunc(
  14180. sqlite3_context *context,
  14181. int argc,
  14182. sqlite3_value **argv
  14183. ){
  14184. time_t t;
  14185. char *zFormat = (char *)sqlite3_user_data(context);
  14186. sqlite3 *db;
  14187. sqlite3_int64 iT;
  14188. struct tm *pTm;
  14189. struct tm sNow;
  14190. char zBuf[20];
  14191. UNUSED_PARAMETER(argc);
  14192. UNUSED_PARAMETER(argv);
  14193. db = sqlite3_context_db_handle(context);
  14194. if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
  14195. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14196. #ifdef HAVE_GMTIME_R
  14197. pTm = gmtime_r(&t, &sNow);
  14198. #else
  14199. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14200. pTm = gmtime(&t);
  14201. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14202. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14203. #endif
  14204. if( pTm ){
  14205. strftime(zBuf, 20, zFormat, &sNow);
  14206. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14207. }
  14208. }
  14209. #endif
  14210. /*
  14211. ** This function registered all of the above C functions as SQL
  14212. ** functions. This should be the only routine in this file with
  14213. ** external linkage.
  14214. */
  14215. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14216. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14217. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14218. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14219. FUNCTION(date, -1, 0, 0, dateFunc ),
  14220. FUNCTION(time, -1, 0, 0, timeFunc ),
  14221. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14222. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14223. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14224. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14225. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14226. #else
  14227. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14228. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14229. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14230. #endif
  14231. };
  14232. int i;
  14233. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14234. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14235. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14236. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14237. }
  14238. }
  14239. /************** End of date.c ************************************************/
  14240. /************** Begin file os.c **********************************************/
  14241. /*
  14242. ** 2005 November 29
  14243. **
  14244. ** The author disclaims copyright to this source code. In place of
  14245. ** a legal notice, here is a blessing:
  14246. **
  14247. ** May you do good and not evil.
  14248. ** May you find forgiveness for yourself and forgive others.
  14249. ** May you share freely, never taking more than you give.
  14250. **
  14251. ******************************************************************************
  14252. **
  14253. ** This file contains OS interface code that is common to all
  14254. ** architectures.
  14255. */
  14256. #define _SQLITE_OS_C_ 1
  14257. #undef _SQLITE_OS_C_
  14258. /*
  14259. ** The default SQLite sqlite3_vfs implementations do not allocate
  14260. ** memory (actually, os_unix.c allocates a small amount of memory
  14261. ** from within OsOpen()), but some third-party implementations may.
  14262. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14263. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14264. **
  14265. ** The following functions are instrumented for malloc() failure
  14266. ** testing:
  14267. **
  14268. ** sqlite3OsRead()
  14269. ** sqlite3OsWrite()
  14270. ** sqlite3OsSync()
  14271. ** sqlite3OsFileSize()
  14272. ** sqlite3OsLock()
  14273. ** sqlite3OsCheckReservedLock()
  14274. ** sqlite3OsFileControl()
  14275. ** sqlite3OsShmMap()
  14276. ** sqlite3OsOpen()
  14277. ** sqlite3OsDelete()
  14278. ** sqlite3OsAccess()
  14279. ** sqlite3OsFullPathname()
  14280. **
  14281. */
  14282. #if defined(SQLITE_TEST)
  14283. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14284. #define DO_OS_MALLOC_TEST(x) \
  14285. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14286. void *pTstAlloc = sqlite3Malloc(10); \
  14287. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14288. sqlite3_free(pTstAlloc); \
  14289. }
  14290. #else
  14291. #define DO_OS_MALLOC_TEST(x)
  14292. #endif
  14293. /*
  14294. ** The following routines are convenience wrappers around methods
  14295. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14296. ** of this would be completely automatic if SQLite were coded using
  14297. ** C++ instead of plain old C.
  14298. */
  14299. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14300. int rc = SQLITE_OK;
  14301. if( pId->pMethods ){
  14302. rc = pId->pMethods->xClose(pId);
  14303. pId->pMethods = 0;
  14304. }
  14305. return rc;
  14306. }
  14307. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14308. DO_OS_MALLOC_TEST(id);
  14309. return id->pMethods->xRead(id, pBuf, amt, offset);
  14310. }
  14311. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14312. DO_OS_MALLOC_TEST(id);
  14313. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14314. }
  14315. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14316. return id->pMethods->xTruncate(id, size);
  14317. }
  14318. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14319. DO_OS_MALLOC_TEST(id);
  14320. return id->pMethods->xSync(id, flags);
  14321. }
  14322. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14323. DO_OS_MALLOC_TEST(id);
  14324. return id->pMethods->xFileSize(id, pSize);
  14325. }
  14326. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14327. DO_OS_MALLOC_TEST(id);
  14328. return id->pMethods->xLock(id, lockType);
  14329. }
  14330. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14331. return id->pMethods->xUnlock(id, lockType);
  14332. }
  14333. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14334. DO_OS_MALLOC_TEST(id);
  14335. return id->pMethods->xCheckReservedLock(id, pResOut);
  14336. }
  14337. /*
  14338. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14339. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14340. ** when simply tossing information over the wall to the VFS and we do not
  14341. ** really care if the VFS receives and understands the information since it
  14342. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14343. ** routine has no return value since the return value would be meaningless.
  14344. */
  14345. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14346. DO_OS_MALLOC_TEST(id);
  14347. return id->pMethods->xFileControl(id, op, pArg);
  14348. }
  14349. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14350. (void)id->pMethods->xFileControl(id, op, pArg);
  14351. }
  14352. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14353. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14354. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14355. }
  14356. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14357. return id->pMethods->xDeviceCharacteristics(id);
  14358. }
  14359. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14360. return id->pMethods->xShmLock(id, offset, n, flags);
  14361. }
  14362. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14363. id->pMethods->xShmBarrier(id);
  14364. }
  14365. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14366. return id->pMethods->xShmUnmap(id, deleteFlag);
  14367. }
  14368. SQLITE_PRIVATE int sqlite3OsShmMap(
  14369. sqlite3_file *id, /* Database file handle */
  14370. int iPage,
  14371. int pgsz,
  14372. int bExtend, /* True to extend file if necessary */
  14373. void volatile **pp /* OUT: Pointer to mapping */
  14374. ){
  14375. DO_OS_MALLOC_TEST(id);
  14376. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14377. }
  14378. /*
  14379. ** The next group of routines are convenience wrappers around the
  14380. ** VFS methods.
  14381. */
  14382. SQLITE_PRIVATE int sqlite3OsOpen(
  14383. sqlite3_vfs *pVfs,
  14384. const char *zPath,
  14385. sqlite3_file *pFile,
  14386. int flags,
  14387. int *pFlagsOut
  14388. ){
  14389. int rc;
  14390. DO_OS_MALLOC_TEST(0);
  14391. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14392. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14393. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14394. ** reaching the VFS. */
  14395. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14396. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14397. return rc;
  14398. }
  14399. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14400. DO_OS_MALLOC_TEST(0);
  14401. assert( dirSync==0 || dirSync==1 );
  14402. return pVfs->xDelete(pVfs, zPath, dirSync);
  14403. }
  14404. SQLITE_PRIVATE int sqlite3OsAccess(
  14405. sqlite3_vfs *pVfs,
  14406. const char *zPath,
  14407. int flags,
  14408. int *pResOut
  14409. ){
  14410. DO_OS_MALLOC_TEST(0);
  14411. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14412. }
  14413. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14414. sqlite3_vfs *pVfs,
  14415. const char *zPath,
  14416. int nPathOut,
  14417. char *zPathOut
  14418. ){
  14419. DO_OS_MALLOC_TEST(0);
  14420. zPathOut[0] = 0;
  14421. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14422. }
  14423. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14424. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14425. return pVfs->xDlOpen(pVfs, zPath);
  14426. }
  14427. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14428. pVfs->xDlError(pVfs, nByte, zBufOut);
  14429. }
  14430. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14431. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14432. }
  14433. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14434. pVfs->xDlClose(pVfs, pHandle);
  14435. }
  14436. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14437. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14438. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14439. }
  14440. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14441. return pVfs->xSleep(pVfs, nMicro);
  14442. }
  14443. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14444. int rc;
  14445. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14446. ** method to get the current date and time if that method is available
  14447. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14448. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14449. ** unavailable.
  14450. */
  14451. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14452. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14453. }else{
  14454. double r;
  14455. rc = pVfs->xCurrentTime(pVfs, &r);
  14456. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14457. }
  14458. return rc;
  14459. }
  14460. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14461. sqlite3_vfs *pVfs,
  14462. const char *zFile,
  14463. sqlite3_file **ppFile,
  14464. int flags,
  14465. int *pOutFlags
  14466. ){
  14467. int rc = SQLITE_NOMEM;
  14468. sqlite3_file *pFile;
  14469. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14470. if( pFile ){
  14471. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14472. if( rc!=SQLITE_OK ){
  14473. sqlite3_free(pFile);
  14474. }else{
  14475. *ppFile = pFile;
  14476. }
  14477. }
  14478. return rc;
  14479. }
  14480. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14481. int rc = SQLITE_OK;
  14482. assert( pFile );
  14483. rc = sqlite3OsClose(pFile);
  14484. sqlite3_free(pFile);
  14485. return rc;
  14486. }
  14487. /*
  14488. ** This function is a wrapper around the OS specific implementation of
  14489. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14490. ** ability to simulate a malloc failure, so that the handling of an
  14491. ** error in sqlite3_os_init() by the upper layers can be tested.
  14492. */
  14493. SQLITE_PRIVATE int sqlite3OsInit(void){
  14494. void *p = sqlite3_malloc(10);
  14495. if( p==0 ) return SQLITE_NOMEM;
  14496. sqlite3_free(p);
  14497. return sqlite3_os_init();
  14498. }
  14499. /*
  14500. ** The list of all registered VFS implementations.
  14501. */
  14502. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14503. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14504. /*
  14505. ** Locate a VFS by name. If no name is given, simply return the
  14506. ** first VFS on the list.
  14507. */
  14508. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14509. sqlite3_vfs *pVfs = 0;
  14510. #if SQLITE_THREADSAFE
  14511. sqlite3_mutex *mutex;
  14512. #endif
  14513. #ifndef SQLITE_OMIT_AUTOINIT
  14514. int rc = sqlite3_initialize();
  14515. if( rc ) return 0;
  14516. #endif
  14517. #if SQLITE_THREADSAFE
  14518. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14519. #endif
  14520. sqlite3_mutex_enter(mutex);
  14521. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14522. if( zVfs==0 ) break;
  14523. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14524. }
  14525. sqlite3_mutex_leave(mutex);
  14526. return pVfs;
  14527. }
  14528. /*
  14529. ** Unlink a VFS from the linked list
  14530. */
  14531. static void vfsUnlink(sqlite3_vfs *pVfs){
  14532. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14533. if( pVfs==0 ){
  14534. /* No-op */
  14535. }else if( vfsList==pVfs ){
  14536. vfsList = pVfs->pNext;
  14537. }else if( vfsList ){
  14538. sqlite3_vfs *p = vfsList;
  14539. while( p->pNext && p->pNext!=pVfs ){
  14540. p = p->pNext;
  14541. }
  14542. if( p->pNext==pVfs ){
  14543. p->pNext = pVfs->pNext;
  14544. }
  14545. }
  14546. }
  14547. /*
  14548. ** Register a VFS with the system. It is harmless to register the same
  14549. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14550. ** true.
  14551. */
  14552. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14553. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14554. #ifndef SQLITE_OMIT_AUTOINIT
  14555. int rc = sqlite3_initialize();
  14556. if( rc ) return rc;
  14557. #endif
  14558. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14559. sqlite3_mutex_enter(mutex);
  14560. vfsUnlink(pVfs);
  14561. if( makeDflt || vfsList==0 ){
  14562. pVfs->pNext = vfsList;
  14563. vfsList = pVfs;
  14564. }else{
  14565. pVfs->pNext = vfsList->pNext;
  14566. vfsList->pNext = pVfs;
  14567. }
  14568. assert(vfsList);
  14569. sqlite3_mutex_leave(mutex);
  14570. return SQLITE_OK;
  14571. }
  14572. /*
  14573. ** Unregister a VFS so that it is no longer accessible.
  14574. */
  14575. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14576. #if SQLITE_THREADSAFE
  14577. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14578. #endif
  14579. sqlite3_mutex_enter(mutex);
  14580. vfsUnlink(pVfs);
  14581. sqlite3_mutex_leave(mutex);
  14582. return SQLITE_OK;
  14583. }
  14584. /************** End of os.c **************************************************/
  14585. /************** Begin file fault.c *******************************************/
  14586. /*
  14587. ** 2008 Jan 22
  14588. **
  14589. ** The author disclaims copyright to this source code. In place of
  14590. ** a legal notice, here is a blessing:
  14591. **
  14592. ** May you do good and not evil.
  14593. ** May you find forgiveness for yourself and forgive others.
  14594. ** May you share freely, never taking more than you give.
  14595. **
  14596. *************************************************************************
  14597. **
  14598. ** This file contains code to support the concept of "benign"
  14599. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14600. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14601. ** and returns 0).
  14602. **
  14603. ** Most malloc failures are non-benign. After they occur, SQLite
  14604. ** abandons the current operation and returns an error code (usually
  14605. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14606. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14607. ** is completely recoverable simply by not carrying out the resize. The
  14608. ** hash table will continue to function normally. So a malloc failure
  14609. ** during a hash table resize is a benign fault.
  14610. */
  14611. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14612. /*
  14613. ** Global variables.
  14614. */
  14615. typedef struct BenignMallocHooks BenignMallocHooks;
  14616. static SQLITE_WSD struct BenignMallocHooks {
  14617. void (*xBenignBegin)(void);
  14618. void (*xBenignEnd)(void);
  14619. } sqlite3Hooks = { 0, 0 };
  14620. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14621. ** structure. If writable static data is unsupported on the target,
  14622. ** we have to locate the state vector at run-time. In the more common
  14623. ** case where writable static data is supported, wsdHooks can refer directly
  14624. ** to the "sqlite3Hooks" state vector declared above.
  14625. */
  14626. #ifdef SQLITE_OMIT_WSD
  14627. # define wsdHooksInit \
  14628. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14629. # define wsdHooks x[0]
  14630. #else
  14631. # define wsdHooksInit
  14632. # define wsdHooks sqlite3Hooks
  14633. #endif
  14634. /*
  14635. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14636. ** sqlite3EndBenignMalloc() are called, respectively.
  14637. */
  14638. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14639. void (*xBenignBegin)(void),
  14640. void (*xBenignEnd)(void)
  14641. ){
  14642. wsdHooksInit;
  14643. wsdHooks.xBenignBegin = xBenignBegin;
  14644. wsdHooks.xBenignEnd = xBenignEnd;
  14645. }
  14646. /*
  14647. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14648. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14649. ** indicates that subsequent malloc failures are non-benign.
  14650. */
  14651. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14652. wsdHooksInit;
  14653. if( wsdHooks.xBenignBegin ){
  14654. wsdHooks.xBenignBegin();
  14655. }
  14656. }
  14657. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14658. wsdHooksInit;
  14659. if( wsdHooks.xBenignEnd ){
  14660. wsdHooks.xBenignEnd();
  14661. }
  14662. }
  14663. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14664. /************** End of fault.c ***********************************************/
  14665. /************** Begin file mem0.c ********************************************/
  14666. /*
  14667. ** 2008 October 28
  14668. **
  14669. ** The author disclaims copyright to this source code. In place of
  14670. ** a legal notice, here is a blessing:
  14671. **
  14672. ** May you do good and not evil.
  14673. ** May you find forgiveness for yourself and forgive others.
  14674. ** May you share freely, never taking more than you give.
  14675. **
  14676. *************************************************************************
  14677. **
  14678. ** This file contains a no-op memory allocation drivers for use when
  14679. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14680. ** here always fail. SQLite will not operate with these drivers. These
  14681. ** are merely placeholders. Real drivers must be substituted using
  14682. ** sqlite3_config() before SQLite will operate.
  14683. */
  14684. /*
  14685. ** This version of the memory allocator is the default. It is
  14686. ** used when no other memory allocator is specified using compile-time
  14687. ** macros.
  14688. */
  14689. #ifdef SQLITE_ZERO_MALLOC
  14690. /*
  14691. ** No-op versions of all memory allocation routines
  14692. */
  14693. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14694. static void sqlite3MemFree(void *pPrior){ return; }
  14695. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14696. static int sqlite3MemSize(void *pPrior){ return 0; }
  14697. static int sqlite3MemRoundup(int n){ return n; }
  14698. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14699. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14700. /*
  14701. ** This routine is the only routine in this file with external linkage.
  14702. **
  14703. ** Populate the low-level memory allocation function pointers in
  14704. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14705. */
  14706. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14707. static const sqlite3_mem_methods defaultMethods = {
  14708. sqlite3MemMalloc,
  14709. sqlite3MemFree,
  14710. sqlite3MemRealloc,
  14711. sqlite3MemSize,
  14712. sqlite3MemRoundup,
  14713. sqlite3MemInit,
  14714. sqlite3MemShutdown,
  14715. 0
  14716. };
  14717. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14718. }
  14719. #endif /* SQLITE_ZERO_MALLOC */
  14720. /************** End of mem0.c ************************************************/
  14721. /************** Begin file mem1.c ********************************************/
  14722. /*
  14723. ** 2007 August 14
  14724. **
  14725. ** The author disclaims copyright to this source code. In place of
  14726. ** a legal notice, here is a blessing:
  14727. **
  14728. ** May you do good and not evil.
  14729. ** May you find forgiveness for yourself and forgive others.
  14730. ** May you share freely, never taking more than you give.
  14731. **
  14732. *************************************************************************
  14733. **
  14734. ** This file contains low-level memory allocation drivers for when
  14735. ** SQLite will use the standard C-library malloc/realloc/free interface
  14736. ** to obtain the memory it needs.
  14737. **
  14738. ** This file contains implementations of the low-level memory allocation
  14739. ** routines specified in the sqlite3_mem_methods object. The content of
  14740. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  14741. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  14742. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  14743. ** default configuration is to use memory allocation routines in this
  14744. ** file.
  14745. **
  14746. ** C-preprocessor macro summary:
  14747. **
  14748. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  14749. ** the malloc_usable_size() interface exists
  14750. ** on the target platform. Or, this symbol
  14751. ** can be set manually, if desired.
  14752. ** If an equivalent interface exists by
  14753. ** a different name, using a separate -D
  14754. ** option to rename it.
  14755. **
  14756. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  14757. ** memory allocator. Set this symbol to enable
  14758. ** building on older macs.
  14759. **
  14760. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  14761. ** _msize() on windows systems. This might
  14762. ** be necessary when compiling for Delphi,
  14763. ** for example.
  14764. */
  14765. /*
  14766. ** This version of the memory allocator is the default. It is
  14767. ** used when no other memory allocator is specified using compile-time
  14768. ** macros.
  14769. */
  14770. #ifdef SQLITE_SYSTEM_MALLOC
  14771. /*
  14772. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  14773. ** The use of _msize() is automatic, but can be disabled by compiling
  14774. ** with -DSQLITE_WITHOUT_MSIZE
  14775. */
  14776. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  14777. # define SQLITE_MALLOCSIZE _msize
  14778. #endif
  14779. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  14780. /*
  14781. ** Use the zone allocator available on apple products unless the
  14782. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  14783. */
  14784. #include <sys/sysctl.h>
  14785. #include <malloc/malloc.h>
  14786. #include <libkern/OSAtomic.h>
  14787. static malloc_zone_t* _sqliteZone_;
  14788. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  14789. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  14790. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  14791. #define SQLITE_MALLOCSIZE(x) \
  14792. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  14793. #else /* if not __APPLE__ */
  14794. /*
  14795. ** Use standard C library malloc and free on non-Apple systems.
  14796. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  14797. */
  14798. #define SQLITE_MALLOC(x) malloc(x)
  14799. #define SQLITE_FREE(x) free(x)
  14800. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  14801. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  14802. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  14803. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  14804. #endif
  14805. #ifdef HAVE_MALLOC_USABLE_SIZE
  14806. # ifndef SQLITE_MALLOCSIZE
  14807. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  14808. # endif
  14809. #else
  14810. # undef SQLITE_MALLOCSIZE
  14811. #endif
  14812. #endif /* __APPLE__ or not __APPLE__ */
  14813. /*
  14814. ** Like malloc(), but remember the size of the allocation
  14815. ** so that we can find it later using sqlite3MemSize().
  14816. **
  14817. ** For this low-level routine, we are guaranteed that nByte>0 because
  14818. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  14819. ** routines.
  14820. */
  14821. static void *sqlite3MemMalloc(int nByte){
  14822. #ifdef SQLITE_MALLOCSIZE
  14823. void *p = SQLITE_MALLOC( nByte );
  14824. if( p==0 ){
  14825. testcase( sqlite3GlobalConfig.xLog!=0 );
  14826. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  14827. }
  14828. return p;
  14829. #else
  14830. sqlite3_int64 *p;
  14831. assert( nByte>0 );
  14832. nByte = ROUND8(nByte);
  14833. p = SQLITE_MALLOC( nByte+8 );
  14834. if( p ){
  14835. p[0] = nByte;
  14836. p++;
  14837. }else{
  14838. testcase( sqlite3GlobalConfig.xLog!=0 );
  14839. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  14840. }
  14841. return (void *)p;
  14842. #endif
  14843. }
  14844. /*
  14845. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  14846. ** or sqlite3MemRealloc().
  14847. **
  14848. ** For this low-level routine, we already know that pPrior!=0 since
  14849. ** cases where pPrior==0 will have been intecepted and dealt with
  14850. ** by higher-level routines.
  14851. */
  14852. static void sqlite3MemFree(void *pPrior){
  14853. #ifdef SQLITE_MALLOCSIZE
  14854. SQLITE_FREE(pPrior);
  14855. #else
  14856. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  14857. assert( pPrior!=0 );
  14858. p--;
  14859. SQLITE_FREE(p);
  14860. #endif
  14861. }
  14862. /*
  14863. ** Report the allocated size of a prior return from xMalloc()
  14864. ** or xRealloc().
  14865. */
  14866. static int sqlite3MemSize(void *pPrior){
  14867. #ifdef SQLITE_MALLOCSIZE
  14868. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  14869. #else
  14870. sqlite3_int64 *p;
  14871. if( pPrior==0 ) return 0;
  14872. p = (sqlite3_int64*)pPrior;
  14873. p--;
  14874. return (int)p[0];
  14875. #endif
  14876. }
  14877. /*
  14878. ** Like realloc(). Resize an allocation previously obtained from
  14879. ** sqlite3MemMalloc().
  14880. **
  14881. ** For this low-level interface, we know that pPrior!=0. Cases where
  14882. ** pPrior==0 while have been intercepted by higher-level routine and
  14883. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  14884. ** cases where nByte<=0 will have been intercepted by higher-level
  14885. ** routines and redirected to xFree.
  14886. */
  14887. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  14888. #ifdef SQLITE_MALLOCSIZE
  14889. void *p = SQLITE_REALLOC(pPrior, nByte);
  14890. if( p==0 ){
  14891. testcase( sqlite3GlobalConfig.xLog!=0 );
  14892. sqlite3_log(SQLITE_NOMEM,
  14893. "failed memory resize %u to %u bytes",
  14894. SQLITE_MALLOCSIZE(pPrior), nByte);
  14895. }
  14896. return p;
  14897. #else
  14898. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  14899. assert( pPrior!=0 && nByte>0 );
  14900. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  14901. p--;
  14902. p = SQLITE_REALLOC(p, nByte+8 );
  14903. if( p ){
  14904. p[0] = nByte;
  14905. p++;
  14906. }else{
  14907. testcase( sqlite3GlobalConfig.xLog!=0 );
  14908. sqlite3_log(SQLITE_NOMEM,
  14909. "failed memory resize %u to %u bytes",
  14910. sqlite3MemSize(pPrior), nByte);
  14911. }
  14912. return (void*)p;
  14913. #endif
  14914. }
  14915. /*
  14916. ** Round up a request size to the next valid allocation size.
  14917. */
  14918. static int sqlite3MemRoundup(int n){
  14919. return ROUND8(n);
  14920. }
  14921. /*
  14922. ** Initialize this module.
  14923. */
  14924. static int sqlite3MemInit(void *NotUsed){
  14925. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  14926. int cpuCount;
  14927. size_t len;
  14928. if( _sqliteZone_ ){
  14929. return SQLITE_OK;
  14930. }
  14931. len = sizeof(cpuCount);
  14932. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  14933. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  14934. if( cpuCount>1 ){
  14935. /* defer MT decisions to system malloc */
  14936. _sqliteZone_ = malloc_default_zone();
  14937. }else{
  14938. /* only 1 core, use our own zone to contention over global locks,
  14939. ** e.g. we have our own dedicated locks */
  14940. bool success;
  14941. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  14942. malloc_set_zone_name(newzone, "Sqlite_Heap");
  14943. do{
  14944. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  14945. (void * volatile *)&_sqliteZone_);
  14946. }while(!_sqliteZone_);
  14947. if( !success ){
  14948. /* somebody registered a zone first */
  14949. malloc_destroy_zone(newzone);
  14950. }
  14951. }
  14952. #endif
  14953. UNUSED_PARAMETER(NotUsed);
  14954. return SQLITE_OK;
  14955. }
  14956. /*
  14957. ** Deinitialize this module.
  14958. */
  14959. static void sqlite3MemShutdown(void *NotUsed){
  14960. UNUSED_PARAMETER(NotUsed);
  14961. return;
  14962. }
  14963. /*
  14964. ** This routine is the only routine in this file with external linkage.
  14965. **
  14966. ** Populate the low-level memory allocation function pointers in
  14967. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14968. */
  14969. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14970. static const sqlite3_mem_methods defaultMethods = {
  14971. sqlite3MemMalloc,
  14972. sqlite3MemFree,
  14973. sqlite3MemRealloc,
  14974. sqlite3MemSize,
  14975. sqlite3MemRoundup,
  14976. sqlite3MemInit,
  14977. sqlite3MemShutdown,
  14978. 0
  14979. };
  14980. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14981. }
  14982. #endif /* SQLITE_SYSTEM_MALLOC */
  14983. /************** End of mem1.c ************************************************/
  14984. /************** Begin file mem2.c ********************************************/
  14985. /*
  14986. ** 2007 August 15
  14987. **
  14988. ** The author disclaims copyright to this source code. In place of
  14989. ** a legal notice, here is a blessing:
  14990. **
  14991. ** May you do good and not evil.
  14992. ** May you find forgiveness for yourself and forgive others.
  14993. ** May you share freely, never taking more than you give.
  14994. **
  14995. *************************************************************************
  14996. **
  14997. ** This file contains low-level memory allocation drivers for when
  14998. ** SQLite will use the standard C-library malloc/realloc/free interface
  14999. ** to obtain the memory it needs while adding lots of additional debugging
  15000. ** information to each allocation in order to help detect and fix memory
  15001. ** leaks and memory usage errors.
  15002. **
  15003. ** This file contains implementations of the low-level memory allocation
  15004. ** routines specified in the sqlite3_mem_methods object.
  15005. */
  15006. /*
  15007. ** This version of the memory allocator is used only if the
  15008. ** SQLITE_MEMDEBUG macro is defined
  15009. */
  15010. #ifdef SQLITE_MEMDEBUG
  15011. /*
  15012. ** The backtrace functionality is only available with GLIBC
  15013. */
  15014. #ifdef __GLIBC__
  15015. extern int backtrace(void**,int);
  15016. extern void backtrace_symbols_fd(void*const*,int,int);
  15017. #else
  15018. # define backtrace(A,B) 1
  15019. # define backtrace_symbols_fd(A,B,C)
  15020. #endif
  15021. /* #include <stdio.h> */
  15022. /*
  15023. ** Each memory allocation looks like this:
  15024. **
  15025. ** ------------------------------------------------------------------------
  15026. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15027. ** ------------------------------------------------------------------------
  15028. **
  15029. ** The application code sees only a pointer to the allocation. We have
  15030. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15031. ** MemBlockHdr tells us the size of the allocation and the number of
  15032. ** backtrace pointers. There is also a guard word at the end of the
  15033. ** MemBlockHdr.
  15034. */
  15035. struct MemBlockHdr {
  15036. i64 iSize; /* Size of this allocation */
  15037. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15038. char nBacktrace; /* Number of backtraces on this alloc */
  15039. char nBacktraceSlots; /* Available backtrace slots */
  15040. u8 nTitle; /* Bytes of title; includes '\0' */
  15041. u8 eType; /* Allocation type code */
  15042. int iForeGuard; /* Guard word for sanity */
  15043. };
  15044. /*
  15045. ** Guard words
  15046. */
  15047. #define FOREGUARD 0x80F5E153
  15048. #define REARGUARD 0xE4676B53
  15049. /*
  15050. ** Number of malloc size increments to track.
  15051. */
  15052. #define NCSIZE 1000
  15053. /*
  15054. ** All of the static variables used by this module are collected
  15055. ** into a single structure named "mem". This is to keep the
  15056. ** static variables organized and to reduce namespace pollution
  15057. ** when this module is combined with other in the amalgamation.
  15058. */
  15059. static struct {
  15060. /*
  15061. ** Mutex to control access to the memory allocation subsystem.
  15062. */
  15063. sqlite3_mutex *mutex;
  15064. /*
  15065. ** Head and tail of a linked list of all outstanding allocations
  15066. */
  15067. struct MemBlockHdr *pFirst;
  15068. struct MemBlockHdr *pLast;
  15069. /*
  15070. ** The number of levels of backtrace to save in new allocations.
  15071. */
  15072. int nBacktrace;
  15073. void (*xBacktrace)(int, int, void **);
  15074. /*
  15075. ** Title text to insert in front of each block
  15076. */
  15077. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15078. char zTitle[100]; /* The title text */
  15079. /*
  15080. ** sqlite3MallocDisallow() increments the following counter.
  15081. ** sqlite3MallocAllow() decrements it.
  15082. */
  15083. int disallow; /* Do not allow memory allocation */
  15084. /*
  15085. ** Gather statistics on the sizes of memory allocations.
  15086. ** nAlloc[i] is the number of allocation attempts of i*8
  15087. ** bytes. i==NCSIZE is the number of allocation attempts for
  15088. ** sizes more than NCSIZE*8 bytes.
  15089. */
  15090. int nAlloc[NCSIZE]; /* Total number of allocations */
  15091. int nCurrent[NCSIZE]; /* Current number of allocations */
  15092. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15093. } mem;
  15094. /*
  15095. ** Adjust memory usage statistics
  15096. */
  15097. static void adjustStats(int iSize, int increment){
  15098. int i = ROUND8(iSize)/8;
  15099. if( i>NCSIZE-1 ){
  15100. i = NCSIZE - 1;
  15101. }
  15102. if( increment>0 ){
  15103. mem.nAlloc[i]++;
  15104. mem.nCurrent[i]++;
  15105. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15106. mem.mxCurrent[i] = mem.nCurrent[i];
  15107. }
  15108. }else{
  15109. mem.nCurrent[i]--;
  15110. assert( mem.nCurrent[i]>=0 );
  15111. }
  15112. }
  15113. /*
  15114. ** Given an allocation, find the MemBlockHdr for that allocation.
  15115. **
  15116. ** This routine checks the guards at either end of the allocation and
  15117. ** if they are incorrect it asserts.
  15118. */
  15119. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15120. struct MemBlockHdr *p;
  15121. int *pInt;
  15122. u8 *pU8;
  15123. int nReserve;
  15124. p = (struct MemBlockHdr*)pAllocation;
  15125. p--;
  15126. assert( p->iForeGuard==(int)FOREGUARD );
  15127. nReserve = ROUND8(p->iSize);
  15128. pInt = (int*)pAllocation;
  15129. pU8 = (u8*)pAllocation;
  15130. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15131. /* This checks any of the "extra" bytes allocated due
  15132. ** to rounding up to an 8 byte boundary to ensure
  15133. ** they haven't been overwritten.
  15134. */
  15135. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15136. return p;
  15137. }
  15138. /*
  15139. ** Return the number of bytes currently allocated at address p.
  15140. */
  15141. static int sqlite3MemSize(void *p){
  15142. struct MemBlockHdr *pHdr;
  15143. if( !p ){
  15144. return 0;
  15145. }
  15146. pHdr = sqlite3MemsysGetHeader(p);
  15147. return pHdr->iSize;
  15148. }
  15149. /*
  15150. ** Initialize the memory allocation subsystem.
  15151. */
  15152. static int sqlite3MemInit(void *NotUsed){
  15153. UNUSED_PARAMETER(NotUsed);
  15154. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15155. if( !sqlite3GlobalConfig.bMemstat ){
  15156. /* If memory status is enabled, then the malloc.c wrapper will already
  15157. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15158. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15159. }
  15160. return SQLITE_OK;
  15161. }
  15162. /*
  15163. ** Deinitialize the memory allocation subsystem.
  15164. */
  15165. static void sqlite3MemShutdown(void *NotUsed){
  15166. UNUSED_PARAMETER(NotUsed);
  15167. mem.mutex = 0;
  15168. }
  15169. /*
  15170. ** Round up a request size to the next valid allocation size.
  15171. */
  15172. static int sqlite3MemRoundup(int n){
  15173. return ROUND8(n);
  15174. }
  15175. /*
  15176. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15177. ** the content of a new memory allocation to unpredictable values and
  15178. ** to clear the content of a freed allocation to unpredictable values.
  15179. */
  15180. static void randomFill(char *pBuf, int nByte){
  15181. unsigned int x, y, r;
  15182. x = SQLITE_PTR_TO_INT(pBuf);
  15183. y = nByte | 1;
  15184. while( nByte >= 4 ){
  15185. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  15186. y = y*1103515245 + 12345;
  15187. r = x ^ y;
  15188. *(int*)pBuf = r;
  15189. pBuf += 4;
  15190. nByte -= 4;
  15191. }
  15192. while( nByte-- > 0 ){
  15193. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  15194. y = y*1103515245 + 12345;
  15195. r = x ^ y;
  15196. *(pBuf++) = r & 0xff;
  15197. }
  15198. }
  15199. /*
  15200. ** Allocate nByte bytes of memory.
  15201. */
  15202. static void *sqlite3MemMalloc(int nByte){
  15203. struct MemBlockHdr *pHdr;
  15204. void **pBt;
  15205. char *z;
  15206. int *pInt;
  15207. void *p = 0;
  15208. int totalSize;
  15209. int nReserve;
  15210. sqlite3_mutex_enter(mem.mutex);
  15211. assert( mem.disallow==0 );
  15212. nReserve = ROUND8(nByte);
  15213. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15214. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15215. p = malloc(totalSize);
  15216. if( p ){
  15217. z = p;
  15218. pBt = (void**)&z[mem.nTitle];
  15219. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15220. pHdr->pNext = 0;
  15221. pHdr->pPrev = mem.pLast;
  15222. if( mem.pLast ){
  15223. mem.pLast->pNext = pHdr;
  15224. }else{
  15225. mem.pFirst = pHdr;
  15226. }
  15227. mem.pLast = pHdr;
  15228. pHdr->iForeGuard = FOREGUARD;
  15229. pHdr->eType = MEMTYPE_HEAP;
  15230. pHdr->nBacktraceSlots = mem.nBacktrace;
  15231. pHdr->nTitle = mem.nTitle;
  15232. if( mem.nBacktrace ){
  15233. void *aAddr[40];
  15234. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15235. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15236. assert(pBt[0]);
  15237. if( mem.xBacktrace ){
  15238. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15239. }
  15240. }else{
  15241. pHdr->nBacktrace = 0;
  15242. }
  15243. if( mem.nTitle ){
  15244. memcpy(z, mem.zTitle, mem.nTitle);
  15245. }
  15246. pHdr->iSize = nByte;
  15247. adjustStats(nByte, +1);
  15248. pInt = (int*)&pHdr[1];
  15249. pInt[nReserve/sizeof(int)] = REARGUARD;
  15250. randomFill((char*)pInt, nByte);
  15251. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15252. p = (void*)pInt;
  15253. }
  15254. sqlite3_mutex_leave(mem.mutex);
  15255. return p;
  15256. }
  15257. /*
  15258. ** Free memory.
  15259. */
  15260. static void sqlite3MemFree(void *pPrior){
  15261. struct MemBlockHdr *pHdr;
  15262. void **pBt;
  15263. char *z;
  15264. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15265. || mem.mutex!=0 );
  15266. pHdr = sqlite3MemsysGetHeader(pPrior);
  15267. pBt = (void**)pHdr;
  15268. pBt -= pHdr->nBacktraceSlots;
  15269. sqlite3_mutex_enter(mem.mutex);
  15270. if( pHdr->pPrev ){
  15271. assert( pHdr->pPrev->pNext==pHdr );
  15272. pHdr->pPrev->pNext = pHdr->pNext;
  15273. }else{
  15274. assert( mem.pFirst==pHdr );
  15275. mem.pFirst = pHdr->pNext;
  15276. }
  15277. if( pHdr->pNext ){
  15278. assert( pHdr->pNext->pPrev==pHdr );
  15279. pHdr->pNext->pPrev = pHdr->pPrev;
  15280. }else{
  15281. assert( mem.pLast==pHdr );
  15282. mem.pLast = pHdr->pPrev;
  15283. }
  15284. z = (char*)pBt;
  15285. z -= pHdr->nTitle;
  15286. adjustStats(pHdr->iSize, -1);
  15287. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15288. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15289. free(z);
  15290. sqlite3_mutex_leave(mem.mutex);
  15291. }
  15292. /*
  15293. ** Change the size of an existing memory allocation.
  15294. **
  15295. ** For this debugging implementation, we *always* make a copy of the
  15296. ** allocation into a new place in memory. In this way, if the
  15297. ** higher level code is using pointer to the old allocation, it is
  15298. ** much more likely to break and we are much more liking to find
  15299. ** the error.
  15300. */
  15301. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15302. struct MemBlockHdr *pOldHdr;
  15303. void *pNew;
  15304. assert( mem.disallow==0 );
  15305. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15306. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15307. pNew = sqlite3MemMalloc(nByte);
  15308. if( pNew ){
  15309. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  15310. if( nByte>pOldHdr->iSize ){
  15311. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
  15312. }
  15313. sqlite3MemFree(pPrior);
  15314. }
  15315. return pNew;
  15316. }
  15317. /*
  15318. ** Populate the low-level memory allocation function pointers in
  15319. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15320. */
  15321. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15322. static const sqlite3_mem_methods defaultMethods = {
  15323. sqlite3MemMalloc,
  15324. sqlite3MemFree,
  15325. sqlite3MemRealloc,
  15326. sqlite3MemSize,
  15327. sqlite3MemRoundup,
  15328. sqlite3MemInit,
  15329. sqlite3MemShutdown,
  15330. 0
  15331. };
  15332. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15333. }
  15334. /*
  15335. ** Set the "type" of an allocation.
  15336. */
  15337. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15338. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15339. struct MemBlockHdr *pHdr;
  15340. pHdr = sqlite3MemsysGetHeader(p);
  15341. assert( pHdr->iForeGuard==FOREGUARD );
  15342. pHdr->eType = eType;
  15343. }
  15344. }
  15345. /*
  15346. ** Return TRUE if the mask of type in eType matches the type of the
  15347. ** allocation p. Also return true if p==NULL.
  15348. **
  15349. ** This routine is designed for use within an assert() statement, to
  15350. ** verify the type of an allocation. For example:
  15351. **
  15352. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15353. */
  15354. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15355. int rc = 1;
  15356. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15357. struct MemBlockHdr *pHdr;
  15358. pHdr = sqlite3MemsysGetHeader(p);
  15359. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15360. if( (pHdr->eType&eType)==0 ){
  15361. rc = 0;
  15362. }
  15363. }
  15364. return rc;
  15365. }
  15366. /*
  15367. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15368. ** allocation p. Also return true if p==NULL.
  15369. **
  15370. ** This routine is designed for use within an assert() statement, to
  15371. ** verify the type of an allocation. For example:
  15372. **
  15373. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15374. */
  15375. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15376. int rc = 1;
  15377. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15378. struct MemBlockHdr *pHdr;
  15379. pHdr = sqlite3MemsysGetHeader(p);
  15380. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15381. if( (pHdr->eType&eType)!=0 ){
  15382. rc = 0;
  15383. }
  15384. }
  15385. return rc;
  15386. }
  15387. /*
  15388. ** Set the number of backtrace levels kept for each allocation.
  15389. ** A value of zero turns off backtracing. The number is always rounded
  15390. ** up to a multiple of 2.
  15391. */
  15392. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15393. if( depth<0 ){ depth = 0; }
  15394. if( depth>20 ){ depth = 20; }
  15395. depth = (depth+1)&0xfe;
  15396. mem.nBacktrace = depth;
  15397. }
  15398. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15399. mem.xBacktrace = xBacktrace;
  15400. }
  15401. /*
  15402. ** Set the title string for subsequent allocations.
  15403. */
  15404. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15405. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15406. sqlite3_mutex_enter(mem.mutex);
  15407. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15408. memcpy(mem.zTitle, zTitle, n);
  15409. mem.zTitle[n] = 0;
  15410. mem.nTitle = ROUND8(n);
  15411. sqlite3_mutex_leave(mem.mutex);
  15412. }
  15413. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15414. struct MemBlockHdr *pHdr;
  15415. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15416. void **pBt = (void**)pHdr;
  15417. pBt -= pHdr->nBacktraceSlots;
  15418. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15419. }
  15420. }
  15421. /*
  15422. ** Open the file indicated and write a log of all unfreed memory
  15423. ** allocations into that log.
  15424. */
  15425. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15426. FILE *out;
  15427. struct MemBlockHdr *pHdr;
  15428. void **pBt;
  15429. int i;
  15430. out = fopen(zFilename, "w");
  15431. if( out==0 ){
  15432. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15433. zFilename);
  15434. return;
  15435. }
  15436. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15437. char *z = (char*)pHdr;
  15438. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15439. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15440. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15441. if( pHdr->nBacktrace ){
  15442. fflush(out);
  15443. pBt = (void**)pHdr;
  15444. pBt -= pHdr->nBacktraceSlots;
  15445. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15446. fprintf(out, "\n");
  15447. }
  15448. }
  15449. fprintf(out, "COUNTS:\n");
  15450. for(i=0; i<NCSIZE-1; i++){
  15451. if( mem.nAlloc[i] ){
  15452. fprintf(out, " %5d: %10d %10d %10d\n",
  15453. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15454. }
  15455. }
  15456. if( mem.nAlloc[NCSIZE-1] ){
  15457. fprintf(out, " %5d: %10d %10d %10d\n",
  15458. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15459. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15460. }
  15461. fclose(out);
  15462. }
  15463. /*
  15464. ** Return the number of times sqlite3MemMalloc() has been called.
  15465. */
  15466. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15467. int i;
  15468. int nTotal = 0;
  15469. for(i=0; i<NCSIZE; i++){
  15470. nTotal += mem.nAlloc[i];
  15471. }
  15472. return nTotal;
  15473. }
  15474. #endif /* SQLITE_MEMDEBUG */
  15475. /************** End of mem2.c ************************************************/
  15476. /************** Begin file mem3.c ********************************************/
  15477. /*
  15478. ** 2007 October 14
  15479. **
  15480. ** The author disclaims copyright to this source code. In place of
  15481. ** a legal notice, here is a blessing:
  15482. **
  15483. ** May you do good and not evil.
  15484. ** May you find forgiveness for yourself and forgive others.
  15485. ** May you share freely, never taking more than you give.
  15486. **
  15487. *************************************************************************
  15488. ** This file contains the C functions that implement a memory
  15489. ** allocation subsystem for use by SQLite.
  15490. **
  15491. ** This version of the memory allocation subsystem omits all
  15492. ** use of malloc(). The SQLite user supplies a block of memory
  15493. ** before calling sqlite3_initialize() from which allocations
  15494. ** are made and returned by the xMalloc() and xRealloc()
  15495. ** implementations. Once sqlite3_initialize() has been called,
  15496. ** the amount of memory available to SQLite is fixed and cannot
  15497. ** be changed.
  15498. **
  15499. ** This version of the memory allocation subsystem is included
  15500. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15501. */
  15502. /*
  15503. ** This version of the memory allocator is only built into the library
  15504. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15505. ** mean that the library will use a memory-pool by default, just that
  15506. ** it is available. The mempool allocator is activated by calling
  15507. ** sqlite3_config().
  15508. */
  15509. #ifdef SQLITE_ENABLE_MEMSYS3
  15510. /*
  15511. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15512. */
  15513. #define MX_SMALL 10
  15514. /*
  15515. ** Number of freelist hash slots
  15516. */
  15517. #define N_HASH 61
  15518. /*
  15519. ** A memory allocation (also called a "chunk") consists of two or
  15520. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15521. ** a header that is not returned to the user.
  15522. **
  15523. ** A chunk is two or more blocks that is either checked out or
  15524. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15525. ** size of the allocation in blocks if the allocation is free.
  15526. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15527. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15528. ** is true if the previous chunk is checked out and false if the
  15529. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15530. ** the previous chunk in blocks if the previous chunk is on the
  15531. ** freelist. If the previous chunk is checked out, then
  15532. ** u.hdr.prevSize can be part of the data for that chunk and should
  15533. ** not be read or written.
  15534. **
  15535. ** We often identify a chunk by its index in mem3.aPool[]. When
  15536. ** this is done, the chunk index refers to the second block of
  15537. ** the chunk. In this way, the first chunk has an index of 1.
  15538. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15539. ** of a NULL pointer.
  15540. **
  15541. ** The second block of free chunks is of the form u.list. The
  15542. ** two fields form a double-linked list of chunks of related sizes.
  15543. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15544. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15545. **
  15546. ** The second block of a chunk is user data if the chunk is checked
  15547. ** out. If a chunk is checked out, the user data may extend into
  15548. ** the u.hdr.prevSize value of the following chunk.
  15549. */
  15550. typedef struct Mem3Block Mem3Block;
  15551. struct Mem3Block {
  15552. union {
  15553. struct {
  15554. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15555. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15556. } hdr;
  15557. struct {
  15558. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15559. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15560. } list;
  15561. } u;
  15562. };
  15563. /*
  15564. ** All of the static variables used by this module are collected
  15565. ** into a single structure named "mem3". This is to keep the
  15566. ** static variables organized and to reduce namespace pollution
  15567. ** when this module is combined with other in the amalgamation.
  15568. */
  15569. static SQLITE_WSD struct Mem3Global {
  15570. /*
  15571. ** Memory available for allocation. nPool is the size of the array
  15572. ** (in Mem3Blocks) pointed to by aPool less 2.
  15573. */
  15574. u32 nPool;
  15575. Mem3Block *aPool;
  15576. /*
  15577. ** True if we are evaluating an out-of-memory callback.
  15578. */
  15579. int alarmBusy;
  15580. /*
  15581. ** Mutex to control access to the memory allocation subsystem.
  15582. */
  15583. sqlite3_mutex *mutex;
  15584. /*
  15585. ** The minimum amount of free space that we have seen.
  15586. */
  15587. u32 mnMaster;
  15588. /*
  15589. ** iMaster is the index of the master chunk. Most new allocations
  15590. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15591. ** of the current master. iMaster is 0 if there is not master chunk.
  15592. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15593. */
  15594. u32 iMaster;
  15595. u32 szMaster;
  15596. /*
  15597. ** Array of lists of free blocks according to the block size
  15598. ** for smaller chunks, or a hash on the block size for larger
  15599. ** chunks.
  15600. */
  15601. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15602. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15603. } mem3 = { 97535575 };
  15604. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15605. /*
  15606. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15607. ** on. *pRoot is the list that i is a member of.
  15608. */
  15609. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15610. u32 next = mem3.aPool[i].u.list.next;
  15611. u32 prev = mem3.aPool[i].u.list.prev;
  15612. assert( sqlite3_mutex_held(mem3.mutex) );
  15613. if( prev==0 ){
  15614. *pRoot = next;
  15615. }else{
  15616. mem3.aPool[prev].u.list.next = next;
  15617. }
  15618. if( next ){
  15619. mem3.aPool[next].u.list.prev = prev;
  15620. }
  15621. mem3.aPool[i].u.list.next = 0;
  15622. mem3.aPool[i].u.list.prev = 0;
  15623. }
  15624. /*
  15625. ** Unlink the chunk at index i from
  15626. ** whatever list is currently a member of.
  15627. */
  15628. static void memsys3Unlink(u32 i){
  15629. u32 size, hash;
  15630. assert( sqlite3_mutex_held(mem3.mutex) );
  15631. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15632. assert( i>=1 );
  15633. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15634. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15635. assert( size>=2 );
  15636. if( size <= MX_SMALL ){
  15637. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15638. }else{
  15639. hash = size % N_HASH;
  15640. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15641. }
  15642. }
  15643. /*
  15644. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15645. ** at *pRoot.
  15646. */
  15647. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15648. assert( sqlite3_mutex_held(mem3.mutex) );
  15649. mem3.aPool[i].u.list.next = *pRoot;
  15650. mem3.aPool[i].u.list.prev = 0;
  15651. if( *pRoot ){
  15652. mem3.aPool[*pRoot].u.list.prev = i;
  15653. }
  15654. *pRoot = i;
  15655. }
  15656. /*
  15657. ** Link the chunk at index i into either the appropriate
  15658. ** small chunk list, or into the large chunk hash table.
  15659. */
  15660. static void memsys3Link(u32 i){
  15661. u32 size, hash;
  15662. assert( sqlite3_mutex_held(mem3.mutex) );
  15663. assert( i>=1 );
  15664. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15665. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15666. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15667. assert( size>=2 );
  15668. if( size <= MX_SMALL ){
  15669. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15670. }else{
  15671. hash = size % N_HASH;
  15672. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15673. }
  15674. }
  15675. /*
  15676. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15677. ** will already be held (obtained by code in malloc.c) if
  15678. ** sqlite3GlobalConfig.bMemStat is true.
  15679. */
  15680. static void memsys3Enter(void){
  15681. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15682. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15683. }
  15684. sqlite3_mutex_enter(mem3.mutex);
  15685. }
  15686. static void memsys3Leave(void){
  15687. sqlite3_mutex_leave(mem3.mutex);
  15688. }
  15689. /*
  15690. ** Called when we are unable to satisfy an allocation of nBytes.
  15691. */
  15692. static void memsys3OutOfMemory(int nByte){
  15693. if( !mem3.alarmBusy ){
  15694. mem3.alarmBusy = 1;
  15695. assert( sqlite3_mutex_held(mem3.mutex) );
  15696. sqlite3_mutex_leave(mem3.mutex);
  15697. sqlite3_release_memory(nByte);
  15698. sqlite3_mutex_enter(mem3.mutex);
  15699. mem3.alarmBusy = 0;
  15700. }
  15701. }
  15702. /*
  15703. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15704. ** size parameters for check-out and return a pointer to the
  15705. ** user portion of the chunk.
  15706. */
  15707. static void *memsys3Checkout(u32 i, u32 nBlock){
  15708. u32 x;
  15709. assert( sqlite3_mutex_held(mem3.mutex) );
  15710. assert( i>=1 );
  15711. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15712. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15713. x = mem3.aPool[i-1].u.hdr.size4x;
  15714. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15715. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15716. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15717. return &mem3.aPool[i];
  15718. }
  15719. /*
  15720. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15721. ** Return a pointer to the new allocation. Or, if the master chunk
  15722. ** is not large enough, return 0.
  15723. */
  15724. static void *memsys3FromMaster(u32 nBlock){
  15725. assert( sqlite3_mutex_held(mem3.mutex) );
  15726. assert( mem3.szMaster>=nBlock );
  15727. if( nBlock>=mem3.szMaster-1 ){
  15728. /* Use the entire master */
  15729. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15730. mem3.iMaster = 0;
  15731. mem3.szMaster = 0;
  15732. mem3.mnMaster = 0;
  15733. return p;
  15734. }else{
  15735. /* Split the master block. Return the tail. */
  15736. u32 newi, x;
  15737. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15738. assert( newi > mem3.iMaster+1 );
  15739. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15740. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15741. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15742. mem3.szMaster -= nBlock;
  15743. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  15744. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15745. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15746. if( mem3.szMaster < mem3.mnMaster ){
  15747. mem3.mnMaster = mem3.szMaster;
  15748. }
  15749. return (void*)&mem3.aPool[newi];
  15750. }
  15751. }
  15752. /*
  15753. ** *pRoot is the head of a list of free chunks of the same size
  15754. ** or same size hash. In other words, *pRoot is an entry in either
  15755. ** mem3.aiSmall[] or mem3.aiHash[].
  15756. **
  15757. ** This routine examines all entries on the given list and tries
  15758. ** to coalesce each entries with adjacent free chunks.
  15759. **
  15760. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  15761. ** the current mem3.iMaster with the new larger chunk. In order for
  15762. ** this mem3.iMaster replacement to work, the master chunk must be
  15763. ** linked into the hash tables. That is not the normal state of
  15764. ** affairs, of course. The calling routine must link the master
  15765. ** chunk before invoking this routine, then must unlink the (possibly
  15766. ** changed) master chunk once this routine has finished.
  15767. */
  15768. static void memsys3Merge(u32 *pRoot){
  15769. u32 iNext, prev, size, i, x;
  15770. assert( sqlite3_mutex_held(mem3.mutex) );
  15771. for(i=*pRoot; i>0; i=iNext){
  15772. iNext = mem3.aPool[i].u.list.next;
  15773. size = mem3.aPool[i-1].u.hdr.size4x;
  15774. assert( (size&1)==0 );
  15775. if( (size&2)==0 ){
  15776. memsys3UnlinkFromList(i, pRoot);
  15777. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  15778. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  15779. if( prev==iNext ){
  15780. iNext = mem3.aPool[prev].u.list.next;
  15781. }
  15782. memsys3Unlink(prev);
  15783. size = i + size/4 - prev;
  15784. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  15785. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  15786. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  15787. memsys3Link(prev);
  15788. i = prev;
  15789. }else{
  15790. size /= 4;
  15791. }
  15792. if( size>mem3.szMaster ){
  15793. mem3.iMaster = i;
  15794. mem3.szMaster = size;
  15795. }
  15796. }
  15797. }
  15798. /*
  15799. ** Return a block of memory of at least nBytes in size.
  15800. ** Return NULL if unable.
  15801. **
  15802. ** This function assumes that the necessary mutexes, if any, are
  15803. ** already held by the caller. Hence "Unsafe".
  15804. */
  15805. static void *memsys3MallocUnsafe(int nByte){
  15806. u32 i;
  15807. u32 nBlock;
  15808. u32 toFree;
  15809. assert( sqlite3_mutex_held(mem3.mutex) );
  15810. assert( sizeof(Mem3Block)==8 );
  15811. if( nByte<=12 ){
  15812. nBlock = 2;
  15813. }else{
  15814. nBlock = (nByte + 11)/8;
  15815. }
  15816. assert( nBlock>=2 );
  15817. /* STEP 1:
  15818. ** Look for an entry of the correct size in either the small
  15819. ** chunk table or in the large chunk hash table. This is
  15820. ** successful most of the time (about 9 times out of 10).
  15821. */
  15822. if( nBlock <= MX_SMALL ){
  15823. i = mem3.aiSmall[nBlock-2];
  15824. if( i>0 ){
  15825. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  15826. return memsys3Checkout(i, nBlock);
  15827. }
  15828. }else{
  15829. int hash = nBlock % N_HASH;
  15830. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  15831. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  15832. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15833. return memsys3Checkout(i, nBlock);
  15834. }
  15835. }
  15836. }
  15837. /* STEP 2:
  15838. ** Try to satisfy the allocation by carving a piece off of the end
  15839. ** of the master chunk. This step usually works if step 1 fails.
  15840. */
  15841. if( mem3.szMaster>=nBlock ){
  15842. return memsys3FromMaster(nBlock);
  15843. }
  15844. /* STEP 3:
  15845. ** Loop through the entire memory pool. Coalesce adjacent free
  15846. ** chunks. Recompute the master chunk as the largest free chunk.
  15847. ** Then try again to satisfy the allocation by carving a piece off
  15848. ** of the end of the master chunk. This step happens very
  15849. ** rarely (we hope!)
  15850. */
  15851. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  15852. memsys3OutOfMemory(toFree);
  15853. if( mem3.iMaster ){
  15854. memsys3Link(mem3.iMaster);
  15855. mem3.iMaster = 0;
  15856. mem3.szMaster = 0;
  15857. }
  15858. for(i=0; i<N_HASH; i++){
  15859. memsys3Merge(&mem3.aiHash[i]);
  15860. }
  15861. for(i=0; i<MX_SMALL-1; i++){
  15862. memsys3Merge(&mem3.aiSmall[i]);
  15863. }
  15864. if( mem3.szMaster ){
  15865. memsys3Unlink(mem3.iMaster);
  15866. if( mem3.szMaster>=nBlock ){
  15867. return memsys3FromMaster(nBlock);
  15868. }
  15869. }
  15870. }
  15871. /* If none of the above worked, then we fail. */
  15872. return 0;
  15873. }
  15874. /*
  15875. ** Free an outstanding memory allocation.
  15876. **
  15877. ** This function assumes that the necessary mutexes, if any, are
  15878. ** already held by the caller. Hence "Unsafe".
  15879. */
  15880. static void memsys3FreeUnsafe(void *pOld){
  15881. Mem3Block *p = (Mem3Block*)pOld;
  15882. int i;
  15883. u32 size, x;
  15884. assert( sqlite3_mutex_held(mem3.mutex) );
  15885. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  15886. i = p - mem3.aPool;
  15887. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  15888. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15889. assert( i+size<=mem3.nPool+1 );
  15890. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  15891. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  15892. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  15893. memsys3Link(i);
  15894. /* Try to expand the master using the newly freed chunk */
  15895. if( mem3.iMaster ){
  15896. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  15897. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  15898. mem3.iMaster -= size;
  15899. mem3.szMaster += size;
  15900. memsys3Unlink(mem3.iMaster);
  15901. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15902. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15903. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  15904. }
  15905. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15906. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  15907. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  15908. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  15909. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15910. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  15911. }
  15912. }
  15913. }
  15914. /*
  15915. ** Return the size of an outstanding allocation, in bytes. The
  15916. ** size returned omits the 8-byte header overhead. This only
  15917. ** works for chunks that are currently checked out.
  15918. */
  15919. static int memsys3Size(void *p){
  15920. Mem3Block *pBlock;
  15921. if( p==0 ) return 0;
  15922. pBlock = (Mem3Block*)p;
  15923. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  15924. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  15925. }
  15926. /*
  15927. ** Round up a request size to the next valid allocation size.
  15928. */
  15929. static int memsys3Roundup(int n){
  15930. if( n<=12 ){
  15931. return 12;
  15932. }else{
  15933. return ((n+11)&~7) - 4;
  15934. }
  15935. }
  15936. /*
  15937. ** Allocate nBytes of memory.
  15938. */
  15939. static void *memsys3Malloc(int nBytes){
  15940. sqlite3_int64 *p;
  15941. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  15942. memsys3Enter();
  15943. p = memsys3MallocUnsafe(nBytes);
  15944. memsys3Leave();
  15945. return (void*)p;
  15946. }
  15947. /*
  15948. ** Free memory.
  15949. */
  15950. static void memsys3Free(void *pPrior){
  15951. assert( pPrior );
  15952. memsys3Enter();
  15953. memsys3FreeUnsafe(pPrior);
  15954. memsys3Leave();
  15955. }
  15956. /*
  15957. ** Change the size of an existing memory allocation
  15958. */
  15959. static void *memsys3Realloc(void *pPrior, int nBytes){
  15960. int nOld;
  15961. void *p;
  15962. if( pPrior==0 ){
  15963. return sqlite3_malloc(nBytes);
  15964. }
  15965. if( nBytes<=0 ){
  15966. sqlite3_free(pPrior);
  15967. return 0;
  15968. }
  15969. nOld = memsys3Size(pPrior);
  15970. if( nBytes<=nOld && nBytes>=nOld-128 ){
  15971. return pPrior;
  15972. }
  15973. memsys3Enter();
  15974. p = memsys3MallocUnsafe(nBytes);
  15975. if( p ){
  15976. if( nOld<nBytes ){
  15977. memcpy(p, pPrior, nOld);
  15978. }else{
  15979. memcpy(p, pPrior, nBytes);
  15980. }
  15981. memsys3FreeUnsafe(pPrior);
  15982. }
  15983. memsys3Leave();
  15984. return p;
  15985. }
  15986. /*
  15987. ** Initialize this module.
  15988. */
  15989. static int memsys3Init(void *NotUsed){
  15990. UNUSED_PARAMETER(NotUsed);
  15991. if( !sqlite3GlobalConfig.pHeap ){
  15992. return SQLITE_ERROR;
  15993. }
  15994. /* Store a pointer to the memory block in global structure mem3. */
  15995. assert( sizeof(Mem3Block)==8 );
  15996. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  15997. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  15998. /* Initialize the master block. */
  15999. mem3.szMaster = mem3.nPool;
  16000. mem3.mnMaster = mem3.szMaster;
  16001. mem3.iMaster = 1;
  16002. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16003. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16004. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16005. return SQLITE_OK;
  16006. }
  16007. /*
  16008. ** Deinitialize this module.
  16009. */
  16010. static void memsys3Shutdown(void *NotUsed){
  16011. UNUSED_PARAMETER(NotUsed);
  16012. mem3.mutex = 0;
  16013. return;
  16014. }
  16015. /*
  16016. ** Open the file indicated and write a log of all unfreed memory
  16017. ** allocations into that log.
  16018. */
  16019. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16020. #ifdef SQLITE_DEBUG
  16021. FILE *out;
  16022. u32 i, j;
  16023. u32 size;
  16024. if( zFilename==0 || zFilename[0]==0 ){
  16025. out = stdout;
  16026. }else{
  16027. out = fopen(zFilename, "w");
  16028. if( out==0 ){
  16029. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16030. zFilename);
  16031. return;
  16032. }
  16033. }
  16034. memsys3Enter();
  16035. fprintf(out, "CHUNKS:\n");
  16036. for(i=1; i<=mem3.nPool; i+=size/4){
  16037. size = mem3.aPool[i-1].u.hdr.size4x;
  16038. if( size/4<=1 ){
  16039. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16040. assert( 0 );
  16041. break;
  16042. }
  16043. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16044. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16045. assert( 0 );
  16046. break;
  16047. }
  16048. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16049. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16050. assert( 0 );
  16051. break;
  16052. }
  16053. if( size&1 ){
  16054. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16055. }else{
  16056. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16057. i==mem3.iMaster ? " **master**" : "");
  16058. }
  16059. }
  16060. for(i=0; i<MX_SMALL-1; i++){
  16061. if( mem3.aiSmall[i]==0 ) continue;
  16062. fprintf(out, "small(%2d):", i);
  16063. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16064. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16065. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16066. }
  16067. fprintf(out, "\n");
  16068. }
  16069. for(i=0; i<N_HASH; i++){
  16070. if( mem3.aiHash[i]==0 ) continue;
  16071. fprintf(out, "hash(%2d):", i);
  16072. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16073. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16074. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16075. }
  16076. fprintf(out, "\n");
  16077. }
  16078. fprintf(out, "master=%d\n", mem3.iMaster);
  16079. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16080. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16081. sqlite3_mutex_leave(mem3.mutex);
  16082. if( out==stdout ){
  16083. fflush(stdout);
  16084. }else{
  16085. fclose(out);
  16086. }
  16087. #else
  16088. UNUSED_PARAMETER(zFilename);
  16089. #endif
  16090. }
  16091. /*
  16092. ** This routine is the only routine in this file with external
  16093. ** linkage.
  16094. **
  16095. ** Populate the low-level memory allocation function pointers in
  16096. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16097. ** arguments specify the block of memory to manage.
  16098. **
  16099. ** This routine is only called by sqlite3_config(), and therefore
  16100. ** is not required to be threadsafe (it is not).
  16101. */
  16102. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16103. static const sqlite3_mem_methods mempoolMethods = {
  16104. memsys3Malloc,
  16105. memsys3Free,
  16106. memsys3Realloc,
  16107. memsys3Size,
  16108. memsys3Roundup,
  16109. memsys3Init,
  16110. memsys3Shutdown,
  16111. 0
  16112. };
  16113. return &mempoolMethods;
  16114. }
  16115. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16116. /************** End of mem3.c ************************************************/
  16117. /************** Begin file mem5.c ********************************************/
  16118. /*
  16119. ** 2007 October 14
  16120. **
  16121. ** The author disclaims copyright to this source code. In place of
  16122. ** a legal notice, here is a blessing:
  16123. **
  16124. ** May you do good and not evil.
  16125. ** May you find forgiveness for yourself and forgive others.
  16126. ** May you share freely, never taking more than you give.
  16127. **
  16128. *************************************************************************
  16129. ** This file contains the C functions that implement a memory
  16130. ** allocation subsystem for use by SQLite.
  16131. **
  16132. ** This version of the memory allocation subsystem omits all
  16133. ** use of malloc(). The application gives SQLite a block of memory
  16134. ** before calling sqlite3_initialize() from which allocations
  16135. ** are made and returned by the xMalloc() and xRealloc()
  16136. ** implementations. Once sqlite3_initialize() has been called,
  16137. ** the amount of memory available to SQLite is fixed and cannot
  16138. ** be changed.
  16139. **
  16140. ** This version of the memory allocation subsystem is included
  16141. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16142. **
  16143. ** This memory allocator uses the following algorithm:
  16144. **
  16145. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16146. **
  16147. ** 2. If two adjacent free blocks are the halves of a larger block,
  16148. ** then the two blocks are coalesed into the single larger block.
  16149. **
  16150. ** 3. New memory is allocated from the first available free block.
  16151. **
  16152. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16153. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16154. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16155. **
  16156. ** Let n be the size of the largest allocation divided by the minimum
  16157. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16158. ** be the maximum amount of memory ever outstanding at one time. Let
  16159. ** N be the total amount of memory available for allocation. Robson
  16160. ** proved that this memory allocator will never breakdown due to
  16161. ** fragmentation as long as the following constraint holds:
  16162. **
  16163. ** N >= M*(1 + log2(n)/2) - n + 1
  16164. **
  16165. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16166. ** that an application can, at any time, verify this constraint.
  16167. */
  16168. /*
  16169. ** This version of the memory allocator is used only when
  16170. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16171. */
  16172. #ifdef SQLITE_ENABLE_MEMSYS5
  16173. /*
  16174. ** A minimum allocation is an instance of the following structure.
  16175. ** Larger allocations are an array of these structures where the
  16176. ** size of the array is a power of 2.
  16177. **
  16178. ** The size of this object must be a power of two. That fact is
  16179. ** verified in memsys5Init().
  16180. */
  16181. typedef struct Mem5Link Mem5Link;
  16182. struct Mem5Link {
  16183. int next; /* Index of next free chunk */
  16184. int prev; /* Index of previous free chunk */
  16185. };
  16186. /*
  16187. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16188. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16189. ** it is not actually possible to reach this limit.
  16190. */
  16191. #define LOGMAX 30
  16192. /*
  16193. ** Masks used for mem5.aCtrl[] elements.
  16194. */
  16195. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16196. #define CTRL_FREE 0x20 /* True if not checked out */
  16197. /*
  16198. ** All of the static variables used by this module are collected
  16199. ** into a single structure named "mem5". This is to keep the
  16200. ** static variables organized and to reduce namespace pollution
  16201. ** when this module is combined with other in the amalgamation.
  16202. */
  16203. static SQLITE_WSD struct Mem5Global {
  16204. /*
  16205. ** Memory available for allocation
  16206. */
  16207. int szAtom; /* Smallest possible allocation in bytes */
  16208. int nBlock; /* Number of szAtom sized blocks in zPool */
  16209. u8 *zPool; /* Memory available to be allocated */
  16210. /*
  16211. ** Mutex to control access to the memory allocation subsystem.
  16212. */
  16213. sqlite3_mutex *mutex;
  16214. /*
  16215. ** Performance statistics
  16216. */
  16217. u64 nAlloc; /* Total number of calls to malloc */
  16218. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16219. u64 totalExcess; /* Total internal fragmentation */
  16220. u32 currentOut; /* Current checkout, including internal fragmentation */
  16221. u32 currentCount; /* Current number of distinct checkouts */
  16222. u32 maxOut; /* Maximum instantaneous currentOut */
  16223. u32 maxCount; /* Maximum instantaneous currentCount */
  16224. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16225. /*
  16226. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16227. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16228. ** and so forth.
  16229. */
  16230. int aiFreelist[LOGMAX+1];
  16231. /*
  16232. ** Space for tracking which blocks are checked out and the size
  16233. ** of each block. One byte per block.
  16234. */
  16235. u8 *aCtrl;
  16236. } mem5;
  16237. /*
  16238. ** Access the static variable through a macro for SQLITE_OMIT_WSD
  16239. */
  16240. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16241. /*
  16242. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16243. ** structures, return a pointer to the idx-th such lik.
  16244. */
  16245. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16246. /*
  16247. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16248. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16249. */
  16250. static void memsys5Unlink(int i, int iLogsize){
  16251. int next, prev;
  16252. assert( i>=0 && i<mem5.nBlock );
  16253. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16254. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16255. next = MEM5LINK(i)->next;
  16256. prev = MEM5LINK(i)->prev;
  16257. if( prev<0 ){
  16258. mem5.aiFreelist[iLogsize] = next;
  16259. }else{
  16260. MEM5LINK(prev)->next = next;
  16261. }
  16262. if( next>=0 ){
  16263. MEM5LINK(next)->prev = prev;
  16264. }
  16265. }
  16266. /*
  16267. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16268. ** free list.
  16269. */
  16270. static void memsys5Link(int i, int iLogsize){
  16271. int x;
  16272. assert( sqlite3_mutex_held(mem5.mutex) );
  16273. assert( i>=0 && i<mem5.nBlock );
  16274. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16275. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16276. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16277. MEM5LINK(i)->prev = -1;
  16278. if( x>=0 ){
  16279. assert( x<mem5.nBlock );
  16280. MEM5LINK(x)->prev = i;
  16281. }
  16282. mem5.aiFreelist[iLogsize] = i;
  16283. }
  16284. /*
  16285. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16286. ** will already be held (obtained by code in malloc.c) if
  16287. ** sqlite3GlobalConfig.bMemStat is true.
  16288. */
  16289. static void memsys5Enter(void){
  16290. sqlite3_mutex_enter(mem5.mutex);
  16291. }
  16292. static void memsys5Leave(void){
  16293. sqlite3_mutex_leave(mem5.mutex);
  16294. }
  16295. /*
  16296. ** Return the size of an outstanding allocation, in bytes. The
  16297. ** size returned omits the 8-byte header overhead. This only
  16298. ** works for chunks that are currently checked out.
  16299. */
  16300. static int memsys5Size(void *p){
  16301. int iSize = 0;
  16302. if( p ){
  16303. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16304. assert( i>=0 && i<mem5.nBlock );
  16305. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16306. }
  16307. return iSize;
  16308. }
  16309. /*
  16310. ** Find the first entry on the freelist iLogsize. Unlink that
  16311. ** entry and return its index.
  16312. */
  16313. static int memsys5UnlinkFirst(int iLogsize){
  16314. int i;
  16315. int iFirst;
  16316. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16317. i = iFirst = mem5.aiFreelist[iLogsize];
  16318. assert( iFirst>=0 );
  16319. while( i>0 ){
  16320. if( i<iFirst ) iFirst = i;
  16321. i = MEM5LINK(i)->next;
  16322. }
  16323. memsys5Unlink(iFirst, iLogsize);
  16324. return iFirst;
  16325. }
  16326. /*
  16327. ** Return a block of memory of at least nBytes in size.
  16328. ** Return NULL if unable. Return NULL if nBytes==0.
  16329. **
  16330. ** The caller guarantees that nByte positive.
  16331. **
  16332. ** The caller has obtained a mutex prior to invoking this
  16333. ** routine so there is never any chance that two or more
  16334. ** threads can be in this routine at the same time.
  16335. */
  16336. static void *memsys5MallocUnsafe(int nByte){
  16337. int i; /* Index of a mem5.aPool[] slot */
  16338. int iBin; /* Index into mem5.aiFreelist[] */
  16339. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16340. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16341. /* nByte must be a positive */
  16342. assert( nByte>0 );
  16343. /* Keep track of the maximum allocation request. Even unfulfilled
  16344. ** requests are counted */
  16345. if( (u32)nByte>mem5.maxRequest ){
  16346. mem5.maxRequest = nByte;
  16347. }
  16348. /* Abort if the requested allocation size is larger than the largest
  16349. ** power of two that we can represent using 32-bit signed integers.
  16350. */
  16351. if( nByte > 0x40000000 ){
  16352. return 0;
  16353. }
  16354. /* Round nByte up to the next valid power of two */
  16355. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16356. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16357. ** block. If not, then split a block of the next larger power of
  16358. ** two in order to create a new free block of size iLogsize.
  16359. */
  16360. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16361. if( iBin>LOGMAX ){
  16362. testcase( sqlite3GlobalConfig.xLog!=0 );
  16363. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16364. return 0;
  16365. }
  16366. i = memsys5UnlinkFirst(iBin);
  16367. while( iBin>iLogsize ){
  16368. int newSize;
  16369. iBin--;
  16370. newSize = 1 << iBin;
  16371. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16372. memsys5Link(i+newSize, iBin);
  16373. }
  16374. mem5.aCtrl[i] = iLogsize;
  16375. /* Update allocator performance statistics. */
  16376. mem5.nAlloc++;
  16377. mem5.totalAlloc += iFullSz;
  16378. mem5.totalExcess += iFullSz - nByte;
  16379. mem5.currentCount++;
  16380. mem5.currentOut += iFullSz;
  16381. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16382. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16383. /* Return a pointer to the allocated memory. */
  16384. return (void*)&mem5.zPool[i*mem5.szAtom];
  16385. }
  16386. /*
  16387. ** Free an outstanding memory allocation.
  16388. */
  16389. static void memsys5FreeUnsafe(void *pOld){
  16390. u32 size, iLogsize;
  16391. int iBlock;
  16392. /* Set iBlock to the index of the block pointed to by pOld in
  16393. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16394. */
  16395. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16396. /* Check that the pointer pOld points to a valid, non-free block. */
  16397. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16398. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16399. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16400. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16401. size = 1<<iLogsize;
  16402. assert( iBlock+size-1<(u32)mem5.nBlock );
  16403. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16404. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16405. assert( mem5.currentCount>0 );
  16406. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16407. mem5.currentCount--;
  16408. mem5.currentOut -= size*mem5.szAtom;
  16409. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16410. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16411. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16412. while( ALWAYS(iLogsize<LOGMAX) ){
  16413. int iBuddy;
  16414. if( (iBlock>>iLogsize) & 1 ){
  16415. iBuddy = iBlock - size;
  16416. }else{
  16417. iBuddy = iBlock + size;
  16418. }
  16419. assert( iBuddy>=0 );
  16420. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16421. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16422. memsys5Unlink(iBuddy, iLogsize);
  16423. iLogsize++;
  16424. if( iBuddy<iBlock ){
  16425. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16426. mem5.aCtrl[iBlock] = 0;
  16427. iBlock = iBuddy;
  16428. }else{
  16429. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16430. mem5.aCtrl[iBuddy] = 0;
  16431. }
  16432. size *= 2;
  16433. }
  16434. memsys5Link(iBlock, iLogsize);
  16435. }
  16436. /*
  16437. ** Allocate nBytes of memory
  16438. */
  16439. static void *memsys5Malloc(int nBytes){
  16440. sqlite3_int64 *p = 0;
  16441. if( nBytes>0 ){
  16442. memsys5Enter();
  16443. p = memsys5MallocUnsafe(nBytes);
  16444. memsys5Leave();
  16445. }
  16446. return (void*)p;
  16447. }
  16448. /*
  16449. ** Free memory.
  16450. **
  16451. ** The outer layer memory allocator prevents this routine from
  16452. ** being called with pPrior==0.
  16453. */
  16454. static void memsys5Free(void *pPrior){
  16455. assert( pPrior!=0 );
  16456. memsys5Enter();
  16457. memsys5FreeUnsafe(pPrior);
  16458. memsys5Leave();
  16459. }
  16460. /*
  16461. ** Change the size of an existing memory allocation.
  16462. **
  16463. ** The outer layer memory allocator prevents this routine from
  16464. ** being called with pPrior==0.
  16465. **
  16466. ** nBytes is always a value obtained from a prior call to
  16467. ** memsys5Round(). Hence nBytes is always a non-negative power
  16468. ** of two. If nBytes==0 that means that an oversize allocation
  16469. ** (an allocation larger than 0x40000000) was requested and this
  16470. ** routine should return 0 without freeing pPrior.
  16471. */
  16472. static void *memsys5Realloc(void *pPrior, int nBytes){
  16473. int nOld;
  16474. void *p;
  16475. assert( pPrior!=0 );
  16476. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16477. assert( nBytes>=0 );
  16478. if( nBytes==0 ){
  16479. return 0;
  16480. }
  16481. nOld = memsys5Size(pPrior);
  16482. if( nBytes<=nOld ){
  16483. return pPrior;
  16484. }
  16485. memsys5Enter();
  16486. p = memsys5MallocUnsafe(nBytes);
  16487. if( p ){
  16488. memcpy(p, pPrior, nOld);
  16489. memsys5FreeUnsafe(pPrior);
  16490. }
  16491. memsys5Leave();
  16492. return p;
  16493. }
  16494. /*
  16495. ** Round up a request size to the next valid allocation size. If
  16496. ** the allocation is too large to be handled by this allocation system,
  16497. ** return 0.
  16498. **
  16499. ** All allocations must be a power of two and must be expressed by a
  16500. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16501. ** or 1073741824 bytes.
  16502. */
  16503. static int memsys5Roundup(int n){
  16504. int iFullSz;
  16505. if( n > 0x40000000 ) return 0;
  16506. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16507. return iFullSz;
  16508. }
  16509. /*
  16510. ** Return the ceiling of the logarithm base 2 of iValue.
  16511. **
  16512. ** Examples: memsys5Log(1) -> 0
  16513. ** memsys5Log(2) -> 1
  16514. ** memsys5Log(4) -> 2
  16515. ** memsys5Log(5) -> 3
  16516. ** memsys5Log(8) -> 3
  16517. ** memsys5Log(9) -> 4
  16518. */
  16519. static int memsys5Log(int iValue){
  16520. int iLog;
  16521. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16522. return iLog;
  16523. }
  16524. /*
  16525. ** Initialize the memory allocator.
  16526. **
  16527. ** This routine is not threadsafe. The caller must be holding a mutex
  16528. ** to prevent multiple threads from entering at the same time.
  16529. */
  16530. static int memsys5Init(void *NotUsed){
  16531. int ii; /* Loop counter */
  16532. int nByte; /* Number of bytes of memory available to this allocator */
  16533. u8 *zByte; /* Memory usable by this allocator */
  16534. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16535. int iOffset; /* An offset into mem5.aCtrl[] */
  16536. UNUSED_PARAMETER(NotUsed);
  16537. /* For the purposes of this routine, disable the mutex */
  16538. mem5.mutex = 0;
  16539. /* The size of a Mem5Link object must be a power of two. Verify that
  16540. ** this is case.
  16541. */
  16542. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16543. nByte = sqlite3GlobalConfig.nHeap;
  16544. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16545. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16546. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16547. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16548. mem5.szAtom = (1<<nMinLog);
  16549. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16550. mem5.szAtom = mem5.szAtom << 1;
  16551. }
  16552. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16553. mem5.zPool = zByte;
  16554. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16555. for(ii=0; ii<=LOGMAX; ii++){
  16556. mem5.aiFreelist[ii] = -1;
  16557. }
  16558. iOffset = 0;
  16559. for(ii=LOGMAX; ii>=0; ii--){
  16560. int nAlloc = (1<<ii);
  16561. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16562. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16563. memsys5Link(iOffset, ii);
  16564. iOffset += nAlloc;
  16565. }
  16566. assert((iOffset+nAlloc)>mem5.nBlock);
  16567. }
  16568. /* If a mutex is required for normal operation, allocate one */
  16569. if( sqlite3GlobalConfig.bMemstat==0 ){
  16570. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16571. }
  16572. return SQLITE_OK;
  16573. }
  16574. /*
  16575. ** Deinitialize this module.
  16576. */
  16577. static void memsys5Shutdown(void *NotUsed){
  16578. UNUSED_PARAMETER(NotUsed);
  16579. mem5.mutex = 0;
  16580. return;
  16581. }
  16582. #ifdef SQLITE_TEST
  16583. /*
  16584. ** Open the file indicated and write a log of all unfreed memory
  16585. ** allocations into that log.
  16586. */
  16587. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16588. FILE *out;
  16589. int i, j, n;
  16590. int nMinLog;
  16591. if( zFilename==0 || zFilename[0]==0 ){
  16592. out = stdout;
  16593. }else{
  16594. out = fopen(zFilename, "w");
  16595. if( out==0 ){
  16596. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16597. zFilename);
  16598. return;
  16599. }
  16600. }
  16601. memsys5Enter();
  16602. nMinLog = memsys5Log(mem5.szAtom);
  16603. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16604. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16605. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16606. }
  16607. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16608. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16609. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16610. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16611. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16612. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16613. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16614. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16615. memsys5Leave();
  16616. if( out==stdout ){
  16617. fflush(stdout);
  16618. }else{
  16619. fclose(out);
  16620. }
  16621. }
  16622. #endif
  16623. /*
  16624. ** This routine is the only routine in this file with external
  16625. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16626. ** struct populated with the memsys5 methods.
  16627. */
  16628. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16629. static const sqlite3_mem_methods memsys5Methods = {
  16630. memsys5Malloc,
  16631. memsys5Free,
  16632. memsys5Realloc,
  16633. memsys5Size,
  16634. memsys5Roundup,
  16635. memsys5Init,
  16636. memsys5Shutdown,
  16637. 0
  16638. };
  16639. return &memsys5Methods;
  16640. }
  16641. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16642. /************** End of mem5.c ************************************************/
  16643. /************** Begin file mutex.c *******************************************/
  16644. /*
  16645. ** 2007 August 14
  16646. **
  16647. ** The author disclaims copyright to this source code. In place of
  16648. ** a legal notice, here is a blessing:
  16649. **
  16650. ** May you do good and not evil.
  16651. ** May you find forgiveness for yourself and forgive others.
  16652. ** May you share freely, never taking more than you give.
  16653. **
  16654. *************************************************************************
  16655. ** This file contains the C functions that implement mutexes.
  16656. **
  16657. ** This file contains code that is common across all mutex implementations.
  16658. */
  16659. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16660. /*
  16661. ** For debugging purposes, record when the mutex subsystem is initialized
  16662. ** and uninitialized so that we can assert() if there is an attempt to
  16663. ** allocate a mutex while the system is uninitialized.
  16664. */
  16665. static SQLITE_WSD int mutexIsInit = 0;
  16666. #endif /* SQLITE_DEBUG */
  16667. #ifndef SQLITE_MUTEX_OMIT
  16668. /*
  16669. ** Initialize the mutex system.
  16670. */
  16671. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16672. int rc = SQLITE_OK;
  16673. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16674. /* If the xMutexAlloc method has not been set, then the user did not
  16675. ** install a mutex implementation via sqlite3_config() prior to
  16676. ** sqlite3_initialize() being called. This block copies pointers to
  16677. ** the default implementation into the sqlite3GlobalConfig structure.
  16678. */
  16679. sqlite3_mutex_methods const *pFrom;
  16680. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16681. if( sqlite3GlobalConfig.bCoreMutex ){
  16682. pFrom = sqlite3DefaultMutex();
  16683. }else{
  16684. pFrom = sqlite3NoopMutex();
  16685. }
  16686. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16687. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16688. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16689. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16690. }
  16691. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16692. #ifdef SQLITE_DEBUG
  16693. GLOBAL(int, mutexIsInit) = 1;
  16694. #endif
  16695. return rc;
  16696. }
  16697. /*
  16698. ** Shutdown the mutex system. This call frees resources allocated by
  16699. ** sqlite3MutexInit().
  16700. */
  16701. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16702. int rc = SQLITE_OK;
  16703. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16704. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16705. }
  16706. #ifdef SQLITE_DEBUG
  16707. GLOBAL(int, mutexIsInit) = 0;
  16708. #endif
  16709. return rc;
  16710. }
  16711. /*
  16712. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16713. */
  16714. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16715. #ifndef SQLITE_OMIT_AUTOINIT
  16716. if( sqlite3_initialize() ) return 0;
  16717. #endif
  16718. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16719. }
  16720. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16721. if( !sqlite3GlobalConfig.bCoreMutex ){
  16722. return 0;
  16723. }
  16724. assert( GLOBAL(int, mutexIsInit) );
  16725. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16726. }
  16727. /*
  16728. ** Free a dynamic mutex.
  16729. */
  16730. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16731. if( p ){
  16732. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16733. }
  16734. }
  16735. /*
  16736. ** Obtain the mutex p. If some other thread already has the mutex, block
  16737. ** until it can be obtained.
  16738. */
  16739. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16740. if( p ){
  16741. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16742. }
  16743. }
  16744. /*
  16745. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  16746. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  16747. */
  16748. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  16749. int rc = SQLITE_OK;
  16750. if( p ){
  16751. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  16752. }
  16753. return rc;
  16754. }
  16755. /*
  16756. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  16757. ** entered by the same thread. The behavior is undefined if the mutex
  16758. ** is not currently entered. If a NULL pointer is passed as an argument
  16759. ** this function is a no-op.
  16760. */
  16761. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  16762. if( p ){
  16763. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  16764. }
  16765. }
  16766. #ifndef NDEBUG
  16767. /*
  16768. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16769. ** intended for use inside assert() statements.
  16770. */
  16771. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  16772. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  16773. }
  16774. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  16775. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  16776. }
  16777. #endif
  16778. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  16779. /************** End of mutex.c ***********************************************/
  16780. /************** Begin file mutex_noop.c **************************************/
  16781. /*
  16782. ** 2008 October 07
  16783. **
  16784. ** The author disclaims copyright to this source code. In place of
  16785. ** a legal notice, here is a blessing:
  16786. **
  16787. ** May you do good and not evil.
  16788. ** May you find forgiveness for yourself and forgive others.
  16789. ** May you share freely, never taking more than you give.
  16790. **
  16791. *************************************************************************
  16792. ** This file contains the C functions that implement mutexes.
  16793. **
  16794. ** This implementation in this file does not provide any mutual
  16795. ** exclusion and is thus suitable for use only in applications
  16796. ** that use SQLite in a single thread. The routines defined
  16797. ** here are place-holders. Applications can substitute working
  16798. ** mutex routines at start-time using the
  16799. **
  16800. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  16801. **
  16802. ** interface.
  16803. **
  16804. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  16805. ** that does error checking on mutexes to make sure they are being
  16806. ** called correctly.
  16807. */
  16808. #ifndef SQLITE_MUTEX_OMIT
  16809. #ifndef SQLITE_DEBUG
  16810. /*
  16811. ** Stub routines for all mutex methods.
  16812. **
  16813. ** This routines provide no mutual exclusion or error checking.
  16814. */
  16815. static int noopMutexInit(void){ return SQLITE_OK; }
  16816. static int noopMutexEnd(void){ return SQLITE_OK; }
  16817. static sqlite3_mutex *noopMutexAlloc(int id){
  16818. UNUSED_PARAMETER(id);
  16819. return (sqlite3_mutex*)8;
  16820. }
  16821. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16822. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16823. static int noopMutexTry(sqlite3_mutex *p){
  16824. UNUSED_PARAMETER(p);
  16825. return SQLITE_OK;
  16826. }
  16827. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16828. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  16829. static const sqlite3_mutex_methods sMutex = {
  16830. noopMutexInit,
  16831. noopMutexEnd,
  16832. noopMutexAlloc,
  16833. noopMutexFree,
  16834. noopMutexEnter,
  16835. noopMutexTry,
  16836. noopMutexLeave,
  16837. 0,
  16838. 0,
  16839. };
  16840. return &sMutex;
  16841. }
  16842. #endif /* !SQLITE_DEBUG */
  16843. #ifdef SQLITE_DEBUG
  16844. /*
  16845. ** In this implementation, error checking is provided for testing
  16846. ** and debugging purposes. The mutexes still do not provide any
  16847. ** mutual exclusion.
  16848. */
  16849. /*
  16850. ** The mutex object
  16851. */
  16852. typedef struct sqlite3_debug_mutex {
  16853. int id; /* The mutex type */
  16854. int cnt; /* Number of entries without a matching leave */
  16855. } sqlite3_debug_mutex;
  16856. /*
  16857. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16858. ** intended for use inside assert() statements.
  16859. */
  16860. static int debugMutexHeld(sqlite3_mutex *pX){
  16861. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16862. return p==0 || p->cnt>0;
  16863. }
  16864. static int debugMutexNotheld(sqlite3_mutex *pX){
  16865. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16866. return p==0 || p->cnt==0;
  16867. }
  16868. /*
  16869. ** Initialize and deinitialize the mutex subsystem.
  16870. */
  16871. static int debugMutexInit(void){ return SQLITE_OK; }
  16872. static int debugMutexEnd(void){ return SQLITE_OK; }
  16873. /*
  16874. ** The sqlite3_mutex_alloc() routine allocates a new
  16875. ** mutex and returns a pointer to it. If it returns NULL
  16876. ** that means that a mutex could not be allocated.
  16877. */
  16878. static sqlite3_mutex *debugMutexAlloc(int id){
  16879. static sqlite3_debug_mutex aStatic[6];
  16880. sqlite3_debug_mutex *pNew = 0;
  16881. switch( id ){
  16882. case SQLITE_MUTEX_FAST:
  16883. case SQLITE_MUTEX_RECURSIVE: {
  16884. pNew = sqlite3Malloc(sizeof(*pNew));
  16885. if( pNew ){
  16886. pNew->id = id;
  16887. pNew->cnt = 0;
  16888. }
  16889. break;
  16890. }
  16891. default: {
  16892. assert( id-2 >= 0 );
  16893. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  16894. pNew = &aStatic[id-2];
  16895. pNew->id = id;
  16896. break;
  16897. }
  16898. }
  16899. return (sqlite3_mutex*)pNew;
  16900. }
  16901. /*
  16902. ** This routine deallocates a previously allocated mutex.
  16903. */
  16904. static void debugMutexFree(sqlite3_mutex *pX){
  16905. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16906. assert( p->cnt==0 );
  16907. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16908. sqlite3_free(p);
  16909. }
  16910. /*
  16911. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16912. ** to enter a mutex. If another thread is already within the mutex,
  16913. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16914. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16915. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16916. ** be entered multiple times by the same thread. In such cases the,
  16917. ** mutex must be exited an equal number of times before another thread
  16918. ** can enter. If the same thread tries to enter any other kind of mutex
  16919. ** more than once, the behavior is undefined.
  16920. */
  16921. static void debugMutexEnter(sqlite3_mutex *pX){
  16922. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16923. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16924. p->cnt++;
  16925. }
  16926. static int debugMutexTry(sqlite3_mutex *pX){
  16927. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16928. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16929. p->cnt++;
  16930. return SQLITE_OK;
  16931. }
  16932. /*
  16933. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16934. ** previously entered by the same thread. The behavior
  16935. ** is undefined if the mutex is not currently entered or
  16936. ** is not currently allocated. SQLite will never do either.
  16937. */
  16938. static void debugMutexLeave(sqlite3_mutex *pX){
  16939. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16940. assert( debugMutexHeld(pX) );
  16941. p->cnt--;
  16942. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16943. }
  16944. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  16945. static const sqlite3_mutex_methods sMutex = {
  16946. debugMutexInit,
  16947. debugMutexEnd,
  16948. debugMutexAlloc,
  16949. debugMutexFree,
  16950. debugMutexEnter,
  16951. debugMutexTry,
  16952. debugMutexLeave,
  16953. debugMutexHeld,
  16954. debugMutexNotheld
  16955. };
  16956. return &sMutex;
  16957. }
  16958. #endif /* SQLITE_DEBUG */
  16959. /*
  16960. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  16961. ** is used regardless of the run-time threadsafety setting.
  16962. */
  16963. #ifdef SQLITE_MUTEX_NOOP
  16964. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16965. return sqlite3NoopMutex();
  16966. }
  16967. #endif /* defined(SQLITE_MUTEX_NOOP) */
  16968. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  16969. /************** End of mutex_noop.c ******************************************/
  16970. /************** Begin file mutex_unix.c **************************************/
  16971. /*
  16972. ** 2007 August 28
  16973. **
  16974. ** The author disclaims copyright to this source code. In place of
  16975. ** a legal notice, here is a blessing:
  16976. **
  16977. ** May you do good and not evil.
  16978. ** May you find forgiveness for yourself and forgive others.
  16979. ** May you share freely, never taking more than you give.
  16980. **
  16981. *************************************************************************
  16982. ** This file contains the C functions that implement mutexes for pthreads
  16983. */
  16984. /*
  16985. ** The code in this file is only used if we are compiling threadsafe
  16986. ** under unix with pthreads.
  16987. **
  16988. ** Note that this implementation requires a version of pthreads that
  16989. ** supports recursive mutexes.
  16990. */
  16991. #ifdef SQLITE_MUTEX_PTHREADS
  16992. #include <pthread.h>
  16993. /*
  16994. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  16995. ** are necessary under two condidtions: (1) Debug builds and (2) using
  16996. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  16997. */
  16998. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  16999. # define SQLITE_MUTEX_NREF 1
  17000. #else
  17001. # define SQLITE_MUTEX_NREF 0
  17002. #endif
  17003. /*
  17004. ** Each recursive mutex is an instance of the following structure.
  17005. */
  17006. struct sqlite3_mutex {
  17007. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17008. #if SQLITE_MUTEX_NREF
  17009. int id; /* Mutex type */
  17010. volatile int nRef; /* Number of entrances */
  17011. volatile pthread_t owner; /* Thread that is within this mutex */
  17012. int trace; /* True to trace changes */
  17013. #endif
  17014. };
  17015. #if SQLITE_MUTEX_NREF
  17016. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17017. #else
  17018. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  17019. #endif
  17020. /*
  17021. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17022. ** intended for use only inside assert() statements. On some platforms,
  17023. ** there might be race conditions that can cause these routines to
  17024. ** deliver incorrect results. In particular, if pthread_equal() is
  17025. ** not an atomic operation, then these routines might delivery
  17026. ** incorrect results. On most platforms, pthread_equal() is a
  17027. ** comparison of two integers and is therefore atomic. But we are
  17028. ** told that HPUX is not such a platform. If so, then these routines
  17029. ** will not always work correctly on HPUX.
  17030. **
  17031. ** On those platforms where pthread_equal() is not atomic, SQLite
  17032. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17033. ** make sure no assert() statements are evaluated and hence these
  17034. ** routines are never called.
  17035. */
  17036. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17037. static int pthreadMutexHeld(sqlite3_mutex *p){
  17038. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  17039. }
  17040. static int pthreadMutexNotheld(sqlite3_mutex *p){
  17041. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  17042. }
  17043. #endif
  17044. /*
  17045. ** Initialize and deinitialize the mutex subsystem.
  17046. */
  17047. static int pthreadMutexInit(void){ return SQLITE_OK; }
  17048. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  17049. /*
  17050. ** The sqlite3_mutex_alloc() routine allocates a new
  17051. ** mutex and returns a pointer to it. If it returns NULL
  17052. ** that means that a mutex could not be allocated. SQLite
  17053. ** will unwind its stack and return an error. The argument
  17054. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17055. **
  17056. ** <ul>
  17057. ** <li> SQLITE_MUTEX_FAST
  17058. ** <li> SQLITE_MUTEX_RECURSIVE
  17059. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17060. ** <li> SQLITE_MUTEX_STATIC_MEM
  17061. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17062. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17063. ** <li> SQLITE_MUTEX_STATIC_LRU
  17064. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17065. ** </ul>
  17066. **
  17067. ** The first two constants cause sqlite3_mutex_alloc() to create
  17068. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17069. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17070. ** The mutex implementation does not need to make a distinction
  17071. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17072. ** not want to. But SQLite will only request a recursive mutex in
  17073. ** cases where it really needs one. If a faster non-recursive mutex
  17074. ** implementation is available on the host platform, the mutex subsystem
  17075. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17076. **
  17077. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17078. ** a pointer to a static preexisting mutex. Six static mutexes are
  17079. ** used by the current version of SQLite. Future versions of SQLite
  17080. ** may add additional static mutexes. Static mutexes are for internal
  17081. ** use by SQLite only. Applications that use SQLite mutexes should
  17082. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17083. ** SQLITE_MUTEX_RECURSIVE.
  17084. **
  17085. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17086. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17087. ** returns a different mutex on every call. But for the static
  17088. ** mutex types, the same mutex is returned on every call that has
  17089. ** the same type number.
  17090. */
  17091. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17092. static sqlite3_mutex staticMutexes[] = {
  17093. SQLITE3_MUTEX_INITIALIZER,
  17094. SQLITE3_MUTEX_INITIALIZER,
  17095. SQLITE3_MUTEX_INITIALIZER,
  17096. SQLITE3_MUTEX_INITIALIZER,
  17097. SQLITE3_MUTEX_INITIALIZER,
  17098. SQLITE3_MUTEX_INITIALIZER
  17099. };
  17100. sqlite3_mutex *p;
  17101. switch( iType ){
  17102. case SQLITE_MUTEX_RECURSIVE: {
  17103. p = sqlite3MallocZero( sizeof(*p) );
  17104. if( p ){
  17105. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17106. /* If recursive mutexes are not available, we will have to
  17107. ** build our own. See below. */
  17108. pthread_mutex_init(&p->mutex, 0);
  17109. #else
  17110. /* Use a recursive mutex if it is available */
  17111. pthread_mutexattr_t recursiveAttr;
  17112. pthread_mutexattr_init(&recursiveAttr);
  17113. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17114. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17115. pthread_mutexattr_destroy(&recursiveAttr);
  17116. #endif
  17117. #if SQLITE_MUTEX_NREF
  17118. p->id = iType;
  17119. #endif
  17120. }
  17121. break;
  17122. }
  17123. case SQLITE_MUTEX_FAST: {
  17124. p = sqlite3MallocZero( sizeof(*p) );
  17125. if( p ){
  17126. #if SQLITE_MUTEX_NREF
  17127. p->id = iType;
  17128. #endif
  17129. pthread_mutex_init(&p->mutex, 0);
  17130. }
  17131. break;
  17132. }
  17133. default: {
  17134. assert( iType-2 >= 0 );
  17135. assert( iType-2 < ArraySize(staticMutexes) );
  17136. p = &staticMutexes[iType-2];
  17137. #if SQLITE_MUTEX_NREF
  17138. p->id = iType;
  17139. #endif
  17140. break;
  17141. }
  17142. }
  17143. return p;
  17144. }
  17145. /*
  17146. ** This routine deallocates a previously
  17147. ** allocated mutex. SQLite is careful to deallocate every
  17148. ** mutex that it allocates.
  17149. */
  17150. static void pthreadMutexFree(sqlite3_mutex *p){
  17151. assert( p->nRef==0 );
  17152. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17153. pthread_mutex_destroy(&p->mutex);
  17154. sqlite3_free(p);
  17155. }
  17156. /*
  17157. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17158. ** to enter a mutex. If another thread is already within the mutex,
  17159. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17160. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17161. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17162. ** be entered multiple times by the same thread. In such cases the,
  17163. ** mutex must be exited an equal number of times before another thread
  17164. ** can enter. If the same thread tries to enter any other kind of mutex
  17165. ** more than once, the behavior is undefined.
  17166. */
  17167. static void pthreadMutexEnter(sqlite3_mutex *p){
  17168. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17169. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17170. /* If recursive mutexes are not available, then we have to grow
  17171. ** our own. This implementation assumes that pthread_equal()
  17172. ** is atomic - that it cannot be deceived into thinking self
  17173. ** and p->owner are equal if p->owner changes between two values
  17174. ** that are not equal to self while the comparison is taking place.
  17175. ** This implementation also assumes a coherent cache - that
  17176. ** separate processes cannot read different values from the same
  17177. ** address at the same time. If either of these two conditions
  17178. ** are not met, then the mutexes will fail and problems will result.
  17179. */
  17180. {
  17181. pthread_t self = pthread_self();
  17182. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17183. p->nRef++;
  17184. }else{
  17185. pthread_mutex_lock(&p->mutex);
  17186. assert( p->nRef==0 );
  17187. p->owner = self;
  17188. p->nRef = 1;
  17189. }
  17190. }
  17191. #else
  17192. /* Use the built-in recursive mutexes if they are available.
  17193. */
  17194. pthread_mutex_lock(&p->mutex);
  17195. #if SQLITE_MUTEX_NREF
  17196. assert( p->nRef>0 || p->owner==0 );
  17197. p->owner = pthread_self();
  17198. p->nRef++;
  17199. #endif
  17200. #endif
  17201. #ifdef SQLITE_DEBUG
  17202. if( p->trace ){
  17203. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17204. }
  17205. #endif
  17206. }
  17207. static int pthreadMutexTry(sqlite3_mutex *p){
  17208. int rc;
  17209. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17210. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17211. /* If recursive mutexes are not available, then we have to grow
  17212. ** our own. This implementation assumes that pthread_equal()
  17213. ** is atomic - that it cannot be deceived into thinking self
  17214. ** and p->owner are equal if p->owner changes between two values
  17215. ** that are not equal to self while the comparison is taking place.
  17216. ** This implementation also assumes a coherent cache - that
  17217. ** separate processes cannot read different values from the same
  17218. ** address at the same time. If either of these two conditions
  17219. ** are not met, then the mutexes will fail and problems will result.
  17220. */
  17221. {
  17222. pthread_t self = pthread_self();
  17223. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17224. p->nRef++;
  17225. rc = SQLITE_OK;
  17226. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17227. assert( p->nRef==0 );
  17228. p->owner = self;
  17229. p->nRef = 1;
  17230. rc = SQLITE_OK;
  17231. }else{
  17232. rc = SQLITE_BUSY;
  17233. }
  17234. }
  17235. #else
  17236. /* Use the built-in recursive mutexes if they are available.
  17237. */
  17238. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17239. #if SQLITE_MUTEX_NREF
  17240. p->owner = pthread_self();
  17241. p->nRef++;
  17242. #endif
  17243. rc = SQLITE_OK;
  17244. }else{
  17245. rc = SQLITE_BUSY;
  17246. }
  17247. #endif
  17248. #ifdef SQLITE_DEBUG
  17249. if( rc==SQLITE_OK && p->trace ){
  17250. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17251. }
  17252. #endif
  17253. return rc;
  17254. }
  17255. /*
  17256. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17257. ** previously entered by the same thread. The behavior
  17258. ** is undefined if the mutex is not currently entered or
  17259. ** is not currently allocated. SQLite will never do either.
  17260. */
  17261. static void pthreadMutexLeave(sqlite3_mutex *p){
  17262. assert( pthreadMutexHeld(p) );
  17263. #if SQLITE_MUTEX_NREF
  17264. p->nRef--;
  17265. if( p->nRef==0 ) p->owner = 0;
  17266. #endif
  17267. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17268. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17269. if( p->nRef==0 ){
  17270. pthread_mutex_unlock(&p->mutex);
  17271. }
  17272. #else
  17273. pthread_mutex_unlock(&p->mutex);
  17274. #endif
  17275. #ifdef SQLITE_DEBUG
  17276. if( p->trace ){
  17277. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17278. }
  17279. #endif
  17280. }
  17281. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17282. static const sqlite3_mutex_methods sMutex = {
  17283. pthreadMutexInit,
  17284. pthreadMutexEnd,
  17285. pthreadMutexAlloc,
  17286. pthreadMutexFree,
  17287. pthreadMutexEnter,
  17288. pthreadMutexTry,
  17289. pthreadMutexLeave,
  17290. #ifdef SQLITE_DEBUG
  17291. pthreadMutexHeld,
  17292. pthreadMutexNotheld
  17293. #else
  17294. 0,
  17295. 0
  17296. #endif
  17297. };
  17298. return &sMutex;
  17299. }
  17300. #endif /* SQLITE_MUTEX_PTHREADS */
  17301. /************** End of mutex_unix.c ******************************************/
  17302. /************** Begin file mutex_w32.c ***************************************/
  17303. /*
  17304. ** 2007 August 14
  17305. **
  17306. ** The author disclaims copyright to this source code. In place of
  17307. ** a legal notice, here is a blessing:
  17308. **
  17309. ** May you do good and not evil.
  17310. ** May you find forgiveness for yourself and forgive others.
  17311. ** May you share freely, never taking more than you give.
  17312. **
  17313. *************************************************************************
  17314. ** This file contains the C functions that implement mutexes for win32
  17315. */
  17316. /*
  17317. ** The code in this file is only used if we are compiling multithreaded
  17318. ** on a win32 system.
  17319. */
  17320. #ifdef SQLITE_MUTEX_W32
  17321. /*
  17322. ** Each recursive mutex is an instance of the following structure.
  17323. */
  17324. struct sqlite3_mutex {
  17325. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17326. int id; /* Mutex type */
  17327. #ifdef SQLITE_DEBUG
  17328. volatile int nRef; /* Number of enterances */
  17329. volatile DWORD owner; /* Thread holding this mutex */
  17330. int trace; /* True to trace changes */
  17331. #endif
  17332. };
  17333. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17334. #ifdef SQLITE_DEBUG
  17335. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17336. #else
  17337. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17338. #endif
  17339. /*
  17340. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17341. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17342. **
  17343. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17344. ** the LockFileEx() API. But we can still statically link against that
  17345. ** API as long as we don't call it win running Win95/98/ME. A call to
  17346. ** this routine is used to determine if the host is Win95/98/ME or
  17347. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17348. ** the LockFileEx() API.
  17349. **
  17350. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17351. ** which is only available if your application was compiled with
  17352. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17353. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17354. ** this out as well.
  17355. */
  17356. #if 0
  17357. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  17358. # define mutexIsNT() (1)
  17359. #else
  17360. static int mutexIsNT(void){
  17361. static int osType = 0;
  17362. if( osType==0 ){
  17363. OSVERSIONINFO sInfo;
  17364. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17365. GetVersionEx(&sInfo);
  17366. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17367. }
  17368. return osType==2;
  17369. }
  17370. #endif /* SQLITE_OS_WINCE */
  17371. #endif
  17372. #ifdef SQLITE_DEBUG
  17373. /*
  17374. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17375. ** intended for use only inside assert() statements.
  17376. */
  17377. static int winMutexHeld(sqlite3_mutex *p){
  17378. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17379. }
  17380. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17381. return p->nRef==0 || p->owner!=tid;
  17382. }
  17383. static int winMutexNotheld(sqlite3_mutex *p){
  17384. DWORD tid = GetCurrentThreadId();
  17385. return winMutexNotheld2(p, tid);
  17386. }
  17387. #endif
  17388. /*
  17389. ** Initialize and deinitialize the mutex subsystem.
  17390. */
  17391. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17392. SQLITE3_MUTEX_INITIALIZER,
  17393. SQLITE3_MUTEX_INITIALIZER,
  17394. SQLITE3_MUTEX_INITIALIZER,
  17395. SQLITE3_MUTEX_INITIALIZER,
  17396. SQLITE3_MUTEX_INITIALIZER,
  17397. SQLITE3_MUTEX_INITIALIZER
  17398. };
  17399. static int winMutex_isInit = 0;
  17400. /* As winMutexInit() and winMutexEnd() are called as part
  17401. ** of the sqlite3_initialize and sqlite3_shutdown()
  17402. ** processing, the "interlocked" magic is probably not
  17403. ** strictly necessary.
  17404. */
  17405. static long winMutex_lock = 0;
  17406. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  17407. static int winMutexInit(void){
  17408. /* The first to increment to 1 does actual initialization */
  17409. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17410. int i;
  17411. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17412. #if SQLITE_OS_WINRT
  17413. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  17414. #else
  17415. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17416. #endif
  17417. }
  17418. winMutex_isInit = 1;
  17419. }else{
  17420. /* Someone else is in the process of initing the static mutexes */
  17421. while( !winMutex_isInit ){
  17422. sqlite3_win32_sleep(1);
  17423. }
  17424. }
  17425. return SQLITE_OK;
  17426. }
  17427. static int winMutexEnd(void){
  17428. /* The first to decrement to 0 does actual shutdown
  17429. ** (which should be the last to shutdown.) */
  17430. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17431. if( winMutex_isInit==1 ){
  17432. int i;
  17433. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17434. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17435. }
  17436. winMutex_isInit = 0;
  17437. }
  17438. }
  17439. return SQLITE_OK;
  17440. }
  17441. /*
  17442. ** The sqlite3_mutex_alloc() routine allocates a new
  17443. ** mutex and returns a pointer to it. If it returns NULL
  17444. ** that means that a mutex could not be allocated. SQLite
  17445. ** will unwind its stack and return an error. The argument
  17446. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17447. **
  17448. ** <ul>
  17449. ** <li> SQLITE_MUTEX_FAST
  17450. ** <li> SQLITE_MUTEX_RECURSIVE
  17451. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17452. ** <li> SQLITE_MUTEX_STATIC_MEM
  17453. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17454. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17455. ** <li> SQLITE_MUTEX_STATIC_LRU
  17456. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17457. ** </ul>
  17458. **
  17459. ** The first two constants cause sqlite3_mutex_alloc() to create
  17460. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17461. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17462. ** The mutex implementation does not need to make a distinction
  17463. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17464. ** not want to. But SQLite will only request a recursive mutex in
  17465. ** cases where it really needs one. If a faster non-recursive mutex
  17466. ** implementation is available on the host platform, the mutex subsystem
  17467. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17468. **
  17469. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17470. ** a pointer to a static preexisting mutex. Six static mutexes are
  17471. ** used by the current version of SQLite. Future versions of SQLite
  17472. ** may add additional static mutexes. Static mutexes are for internal
  17473. ** use by SQLite only. Applications that use SQLite mutexes should
  17474. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17475. ** SQLITE_MUTEX_RECURSIVE.
  17476. **
  17477. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17478. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17479. ** returns a different mutex on every call. But for the static
  17480. ** mutex types, the same mutex is returned on every call that has
  17481. ** the same type number.
  17482. */
  17483. static sqlite3_mutex *winMutexAlloc(int iType){
  17484. sqlite3_mutex *p;
  17485. switch( iType ){
  17486. case SQLITE_MUTEX_FAST:
  17487. case SQLITE_MUTEX_RECURSIVE: {
  17488. p = sqlite3MallocZero( sizeof(*p) );
  17489. if( p ){
  17490. #ifdef SQLITE_DEBUG
  17491. p->id = iType;
  17492. #endif
  17493. #if SQLITE_OS_WINRT
  17494. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  17495. #else
  17496. InitializeCriticalSection(&p->mutex);
  17497. #endif
  17498. }
  17499. break;
  17500. }
  17501. default: {
  17502. assert( winMutex_isInit==1 );
  17503. assert( iType-2 >= 0 );
  17504. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17505. p = &winMutex_staticMutexes[iType-2];
  17506. #ifdef SQLITE_DEBUG
  17507. p->id = iType;
  17508. #endif
  17509. break;
  17510. }
  17511. }
  17512. return p;
  17513. }
  17514. /*
  17515. ** This routine deallocates a previously
  17516. ** allocated mutex. SQLite is careful to deallocate every
  17517. ** mutex that it allocates.
  17518. */
  17519. static void winMutexFree(sqlite3_mutex *p){
  17520. assert( p );
  17521. assert( p->nRef==0 && p->owner==0 );
  17522. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17523. DeleteCriticalSection(&p->mutex);
  17524. sqlite3_free(p);
  17525. }
  17526. /*
  17527. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17528. ** to enter a mutex. If another thread is already within the mutex,
  17529. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17530. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17531. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17532. ** be entered multiple times by the same thread. In such cases the,
  17533. ** mutex must be exited an equal number of times before another thread
  17534. ** can enter. If the same thread tries to enter any other kind of mutex
  17535. ** more than once, the behavior is undefined.
  17536. */
  17537. static void winMutexEnter(sqlite3_mutex *p){
  17538. #ifdef SQLITE_DEBUG
  17539. DWORD tid = GetCurrentThreadId();
  17540. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17541. #endif
  17542. EnterCriticalSection(&p->mutex);
  17543. #ifdef SQLITE_DEBUG
  17544. assert( p->nRef>0 || p->owner==0 );
  17545. p->owner = tid;
  17546. p->nRef++;
  17547. if( p->trace ){
  17548. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17549. }
  17550. #endif
  17551. }
  17552. static int winMutexTry(sqlite3_mutex *p){
  17553. #ifndef NDEBUG
  17554. DWORD tid = GetCurrentThreadId();
  17555. #endif
  17556. int rc = SQLITE_BUSY;
  17557. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17558. /*
  17559. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17560. ** is used it is merely an optimization. So it is OK for it to always
  17561. ** fail.
  17562. **
  17563. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17564. ** And some windows compilers complain if you try to use it without
  17565. ** first doing some #defines that prevent SQLite from building on Win98.
  17566. ** For that reason, we will omit this optimization for now. See
  17567. ** ticket #2685.
  17568. */
  17569. #if 0
  17570. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17571. p->owner = tid;
  17572. p->nRef++;
  17573. rc = SQLITE_OK;
  17574. }
  17575. #else
  17576. UNUSED_PARAMETER(p);
  17577. #endif
  17578. #ifdef SQLITE_DEBUG
  17579. if( rc==SQLITE_OK && p->trace ){
  17580. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17581. }
  17582. #endif
  17583. return rc;
  17584. }
  17585. /*
  17586. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17587. ** previously entered by the same thread. The behavior
  17588. ** is undefined if the mutex is not currently entered or
  17589. ** is not currently allocated. SQLite will never do either.
  17590. */
  17591. static void winMutexLeave(sqlite3_mutex *p){
  17592. #ifndef NDEBUG
  17593. DWORD tid = GetCurrentThreadId();
  17594. assert( p->nRef>0 );
  17595. assert( p->owner==tid );
  17596. p->nRef--;
  17597. if( p->nRef==0 ) p->owner = 0;
  17598. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17599. #endif
  17600. LeaveCriticalSection(&p->mutex);
  17601. #ifdef SQLITE_DEBUG
  17602. if( p->trace ){
  17603. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17604. }
  17605. #endif
  17606. }
  17607. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17608. static const sqlite3_mutex_methods sMutex = {
  17609. winMutexInit,
  17610. winMutexEnd,
  17611. winMutexAlloc,
  17612. winMutexFree,
  17613. winMutexEnter,
  17614. winMutexTry,
  17615. winMutexLeave,
  17616. #ifdef SQLITE_DEBUG
  17617. winMutexHeld,
  17618. winMutexNotheld
  17619. #else
  17620. 0,
  17621. 0
  17622. #endif
  17623. };
  17624. return &sMutex;
  17625. }
  17626. #endif /* SQLITE_MUTEX_W32 */
  17627. /************** End of mutex_w32.c *******************************************/
  17628. /************** Begin file malloc.c ******************************************/
  17629. /*
  17630. ** 2001 September 15
  17631. **
  17632. ** The author disclaims copyright to this source code. In place of
  17633. ** a legal notice, here is a blessing:
  17634. **
  17635. ** May you do good and not evil.
  17636. ** May you find forgiveness for yourself and forgive others.
  17637. ** May you share freely, never taking more than you give.
  17638. **
  17639. *************************************************************************
  17640. **
  17641. ** Memory allocation functions used throughout sqlite.
  17642. */
  17643. /* #include <stdarg.h> */
  17644. /*
  17645. ** Attempt to release up to n bytes of non-essential memory currently
  17646. ** held by SQLite. An example of non-essential memory is memory used to
  17647. ** cache database pages that are not currently in use.
  17648. */
  17649. SQLITE_API int sqlite3_release_memory(int n){
  17650. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17651. return sqlite3PcacheReleaseMemory(n);
  17652. #else
  17653. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  17654. ** is a no-op returning zero if SQLite is not compiled with
  17655. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  17656. UNUSED_PARAMETER(n);
  17657. return 0;
  17658. #endif
  17659. }
  17660. /*
  17661. ** An instance of the following object records the location of
  17662. ** each unused scratch buffer.
  17663. */
  17664. typedef struct ScratchFreeslot {
  17665. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  17666. } ScratchFreeslot;
  17667. /*
  17668. ** State information local to the memory allocation subsystem.
  17669. */
  17670. static SQLITE_WSD struct Mem0Global {
  17671. sqlite3_mutex *mutex; /* Mutex to serialize access */
  17672. /*
  17673. ** The alarm callback and its arguments. The mem0.mutex lock will
  17674. ** be held while the callback is running. Recursive calls into
  17675. ** the memory subsystem are allowed, but no new callbacks will be
  17676. ** issued.
  17677. */
  17678. sqlite3_int64 alarmThreshold;
  17679. void (*alarmCallback)(void*, sqlite3_int64,int);
  17680. void *alarmArg;
  17681. /*
  17682. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  17683. ** (so that a range test can be used to determine if an allocation
  17684. ** being freed came from pScratch) and a pointer to the list of
  17685. ** unused scratch allocations.
  17686. */
  17687. void *pScratchEnd;
  17688. ScratchFreeslot *pScratchFree;
  17689. u32 nScratchFree;
  17690. /*
  17691. ** True if heap is nearly "full" where "full" is defined by the
  17692. ** sqlite3_soft_heap_limit() setting.
  17693. */
  17694. int nearlyFull;
  17695. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  17696. #define mem0 GLOBAL(struct Mem0Global, mem0)
  17697. /*
  17698. ** This routine runs when the memory allocator sees that the
  17699. ** total memory allocation is about to exceed the soft heap
  17700. ** limit.
  17701. */
  17702. static void softHeapLimitEnforcer(
  17703. void *NotUsed,
  17704. sqlite3_int64 NotUsed2,
  17705. int allocSize
  17706. ){
  17707. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  17708. sqlite3_release_memory(allocSize);
  17709. }
  17710. /*
  17711. ** Change the alarm callback
  17712. */
  17713. static int sqlite3MemoryAlarm(
  17714. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17715. void *pArg,
  17716. sqlite3_int64 iThreshold
  17717. ){
  17718. int nUsed;
  17719. sqlite3_mutex_enter(mem0.mutex);
  17720. mem0.alarmCallback = xCallback;
  17721. mem0.alarmArg = pArg;
  17722. mem0.alarmThreshold = iThreshold;
  17723. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17724. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  17725. sqlite3_mutex_leave(mem0.mutex);
  17726. return SQLITE_OK;
  17727. }
  17728. #ifndef SQLITE_OMIT_DEPRECATED
  17729. /*
  17730. ** Deprecated external interface. Internal/core SQLite code
  17731. ** should call sqlite3MemoryAlarm.
  17732. */
  17733. SQLITE_API int sqlite3_memory_alarm(
  17734. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17735. void *pArg,
  17736. sqlite3_int64 iThreshold
  17737. ){
  17738. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  17739. }
  17740. #endif
  17741. /*
  17742. ** Set the soft heap-size limit for the library. Passing a zero or
  17743. ** negative value indicates no limit.
  17744. */
  17745. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  17746. sqlite3_int64 priorLimit;
  17747. sqlite3_int64 excess;
  17748. #ifndef SQLITE_OMIT_AUTOINIT
  17749. int rc = sqlite3_initialize();
  17750. if( rc ) return -1;
  17751. #endif
  17752. sqlite3_mutex_enter(mem0.mutex);
  17753. priorLimit = mem0.alarmThreshold;
  17754. sqlite3_mutex_leave(mem0.mutex);
  17755. if( n<0 ) return priorLimit;
  17756. if( n>0 ){
  17757. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  17758. }else{
  17759. sqlite3MemoryAlarm(0, 0, 0);
  17760. }
  17761. excess = sqlite3_memory_used() - n;
  17762. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  17763. return priorLimit;
  17764. }
  17765. SQLITE_API void sqlite3_soft_heap_limit(int n){
  17766. if( n<0 ) n = 0;
  17767. sqlite3_soft_heap_limit64(n);
  17768. }
  17769. /*
  17770. ** Initialize the memory allocation subsystem.
  17771. */
  17772. SQLITE_PRIVATE int sqlite3MallocInit(void){
  17773. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  17774. sqlite3MemSetDefault();
  17775. }
  17776. memset(&mem0, 0, sizeof(mem0));
  17777. if( sqlite3GlobalConfig.bCoreMutex ){
  17778. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17779. }
  17780. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  17781. && sqlite3GlobalConfig.nScratch>0 ){
  17782. int i, n, sz;
  17783. ScratchFreeslot *pSlot;
  17784. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  17785. sqlite3GlobalConfig.szScratch = sz;
  17786. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  17787. n = sqlite3GlobalConfig.nScratch;
  17788. mem0.pScratchFree = pSlot;
  17789. mem0.nScratchFree = n;
  17790. for(i=0; i<n-1; i++){
  17791. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  17792. pSlot = pSlot->pNext;
  17793. }
  17794. pSlot->pNext = 0;
  17795. mem0.pScratchEnd = (void*)&pSlot[1];
  17796. }else{
  17797. mem0.pScratchEnd = 0;
  17798. sqlite3GlobalConfig.pScratch = 0;
  17799. sqlite3GlobalConfig.szScratch = 0;
  17800. sqlite3GlobalConfig.nScratch = 0;
  17801. }
  17802. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  17803. || sqlite3GlobalConfig.nPage<1 ){
  17804. sqlite3GlobalConfig.pPage = 0;
  17805. sqlite3GlobalConfig.szPage = 0;
  17806. sqlite3GlobalConfig.nPage = 0;
  17807. }
  17808. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  17809. }
  17810. /*
  17811. ** Return true if the heap is currently under memory pressure - in other
  17812. ** words if the amount of heap used is close to the limit set by
  17813. ** sqlite3_soft_heap_limit().
  17814. */
  17815. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  17816. return mem0.nearlyFull;
  17817. }
  17818. /*
  17819. ** Deinitialize the memory allocation subsystem.
  17820. */
  17821. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  17822. if( sqlite3GlobalConfig.m.xShutdown ){
  17823. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  17824. }
  17825. memset(&mem0, 0, sizeof(mem0));
  17826. }
  17827. /*
  17828. ** Return the amount of memory currently checked out.
  17829. */
  17830. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  17831. int n, mx;
  17832. sqlite3_int64 res;
  17833. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  17834. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  17835. return res;
  17836. }
  17837. /*
  17838. ** Return the maximum amount of memory that has ever been
  17839. ** checked out since either the beginning of this process
  17840. ** or since the most recent reset.
  17841. */
  17842. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  17843. int n, mx;
  17844. sqlite3_int64 res;
  17845. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  17846. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  17847. return res;
  17848. }
  17849. /*
  17850. ** Trigger the alarm
  17851. */
  17852. static void sqlite3MallocAlarm(int nByte){
  17853. void (*xCallback)(void*,sqlite3_int64,int);
  17854. sqlite3_int64 nowUsed;
  17855. void *pArg;
  17856. if( mem0.alarmCallback==0 ) return;
  17857. xCallback = mem0.alarmCallback;
  17858. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17859. pArg = mem0.alarmArg;
  17860. mem0.alarmCallback = 0;
  17861. sqlite3_mutex_leave(mem0.mutex);
  17862. xCallback(pArg, nowUsed, nByte);
  17863. sqlite3_mutex_enter(mem0.mutex);
  17864. mem0.alarmCallback = xCallback;
  17865. mem0.alarmArg = pArg;
  17866. }
  17867. /*
  17868. ** Do a memory allocation with statistics and alarms. Assume the
  17869. ** lock is already held.
  17870. */
  17871. static int mallocWithAlarm(int n, void **pp){
  17872. int nFull;
  17873. void *p;
  17874. assert( sqlite3_mutex_held(mem0.mutex) );
  17875. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  17876. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  17877. if( mem0.alarmCallback!=0 ){
  17878. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17879. if( nUsed >= mem0.alarmThreshold - nFull ){
  17880. mem0.nearlyFull = 1;
  17881. sqlite3MallocAlarm(nFull);
  17882. }else{
  17883. mem0.nearlyFull = 0;
  17884. }
  17885. }
  17886. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17887. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17888. if( p==0 && mem0.alarmCallback ){
  17889. sqlite3MallocAlarm(nFull);
  17890. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17891. }
  17892. #endif
  17893. if( p ){
  17894. nFull = sqlite3MallocSize(p);
  17895. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  17896. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  17897. }
  17898. *pp = p;
  17899. return nFull;
  17900. }
  17901. /*
  17902. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  17903. ** assumes the memory subsystem has already been initialized.
  17904. */
  17905. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  17906. void *p;
  17907. if( n<=0 /* IMP: R-65312-04917 */
  17908. || n>=0x7fffff00
  17909. ){
  17910. /* A memory allocation of a number of bytes which is near the maximum
  17911. ** signed integer value might cause an integer overflow inside of the
  17912. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  17913. ** 255 bytes of overhead. SQLite itself will never use anything near
  17914. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  17915. p = 0;
  17916. }else if( sqlite3GlobalConfig.bMemstat ){
  17917. sqlite3_mutex_enter(mem0.mutex);
  17918. mallocWithAlarm(n, &p);
  17919. sqlite3_mutex_leave(mem0.mutex);
  17920. }else{
  17921. p = sqlite3GlobalConfig.m.xMalloc(n);
  17922. }
  17923. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  17924. return p;
  17925. }
  17926. /*
  17927. ** This version of the memory allocation is for use by the application.
  17928. ** First make sure the memory subsystem is initialized, then do the
  17929. ** allocation.
  17930. */
  17931. SQLITE_API void *sqlite3_malloc(int n){
  17932. #ifndef SQLITE_OMIT_AUTOINIT
  17933. if( sqlite3_initialize() ) return 0;
  17934. #endif
  17935. return sqlite3Malloc(n);
  17936. }
  17937. /*
  17938. ** Each thread may only have a single outstanding allocation from
  17939. ** xScratchMalloc(). We verify this constraint in the single-threaded
  17940. ** case by setting scratchAllocOut to 1 when an allocation
  17941. ** is outstanding clearing it when the allocation is freed.
  17942. */
  17943. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17944. static int scratchAllocOut = 0;
  17945. #endif
  17946. /*
  17947. ** Allocate memory that is to be used and released right away.
  17948. ** This routine is similar to alloca() in that it is not intended
  17949. ** for situations where the memory might be held long-term. This
  17950. ** routine is intended to get memory to old large transient data
  17951. ** structures that would not normally fit on the stack of an
  17952. ** embedded processor.
  17953. */
  17954. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  17955. void *p;
  17956. assert( n>0 );
  17957. sqlite3_mutex_enter(mem0.mutex);
  17958. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  17959. p = mem0.pScratchFree;
  17960. mem0.pScratchFree = mem0.pScratchFree->pNext;
  17961. mem0.nScratchFree--;
  17962. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  17963. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17964. sqlite3_mutex_leave(mem0.mutex);
  17965. }else{
  17966. if( sqlite3GlobalConfig.bMemstat ){
  17967. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17968. n = mallocWithAlarm(n, &p);
  17969. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  17970. sqlite3_mutex_leave(mem0.mutex);
  17971. }else{
  17972. sqlite3_mutex_leave(mem0.mutex);
  17973. p = sqlite3GlobalConfig.m.xMalloc(n);
  17974. }
  17975. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  17976. }
  17977. assert( sqlite3_mutex_notheld(mem0.mutex) );
  17978. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17979. /* Verify that no more than two scratch allocations per thread
  17980. ** are outstanding at one time. (This is only checked in the
  17981. ** single-threaded case since checking in the multi-threaded case
  17982. ** would be much more complicated.) */
  17983. assert( scratchAllocOut<=1 );
  17984. if( p ) scratchAllocOut++;
  17985. #endif
  17986. return p;
  17987. }
  17988. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  17989. if( p ){
  17990. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17991. /* Verify that no more than two scratch allocation per thread
  17992. ** is outstanding at one time. (This is only checked in the
  17993. ** single-threaded case since checking in the multi-threaded case
  17994. ** would be much more complicated.) */
  17995. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  17996. scratchAllocOut--;
  17997. #endif
  17998. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  17999. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  18000. ScratchFreeslot *pSlot;
  18001. pSlot = (ScratchFreeslot*)p;
  18002. sqlite3_mutex_enter(mem0.mutex);
  18003. pSlot->pNext = mem0.pScratchFree;
  18004. mem0.pScratchFree = pSlot;
  18005. mem0.nScratchFree++;
  18006. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  18007. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  18008. sqlite3_mutex_leave(mem0.mutex);
  18009. }else{
  18010. /* Release memory back to the heap */
  18011. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  18012. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  18013. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18014. if( sqlite3GlobalConfig.bMemstat ){
  18015. int iSize = sqlite3MallocSize(p);
  18016. sqlite3_mutex_enter(mem0.mutex);
  18017. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  18018. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  18019. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18020. sqlite3GlobalConfig.m.xFree(p);
  18021. sqlite3_mutex_leave(mem0.mutex);
  18022. }else{
  18023. sqlite3GlobalConfig.m.xFree(p);
  18024. }
  18025. }
  18026. }
  18027. }
  18028. /*
  18029. ** TRUE if p is a lookaside memory allocation from db
  18030. */
  18031. #ifndef SQLITE_OMIT_LOOKASIDE
  18032. static int isLookaside(sqlite3 *db, void *p){
  18033. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18034. }
  18035. #else
  18036. #define isLookaside(A,B) 0
  18037. #endif
  18038. /*
  18039. ** Return the size of a memory allocation previously obtained from
  18040. ** sqlite3Malloc() or sqlite3_malloc().
  18041. */
  18042. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18043. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18044. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18045. return sqlite3GlobalConfig.m.xSize(p);
  18046. }
  18047. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18048. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18049. if( db && isLookaside(db, p) ){
  18050. return db->lookaside.sz;
  18051. }else{
  18052. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18053. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18054. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18055. return sqlite3GlobalConfig.m.xSize(p);
  18056. }
  18057. }
  18058. /*
  18059. ** Free memory previously obtained from sqlite3Malloc().
  18060. */
  18061. SQLITE_API void sqlite3_free(void *p){
  18062. if( p==0 ) return; /* IMP: R-49053-54554 */
  18063. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18064. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18065. if( sqlite3GlobalConfig.bMemstat ){
  18066. sqlite3_mutex_enter(mem0.mutex);
  18067. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18068. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18069. sqlite3GlobalConfig.m.xFree(p);
  18070. sqlite3_mutex_leave(mem0.mutex);
  18071. }else{
  18072. sqlite3GlobalConfig.m.xFree(p);
  18073. }
  18074. }
  18075. /*
  18076. ** Free memory that might be associated with a particular database
  18077. ** connection.
  18078. */
  18079. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18080. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18081. if( db ){
  18082. if( db->pnBytesFreed ){
  18083. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18084. return;
  18085. }
  18086. if( isLookaside(db, p) ){
  18087. LookasideSlot *pBuf = (LookasideSlot*)p;
  18088. #if SQLITE_DEBUG
  18089. /* Trash all content in the buffer being freed */
  18090. memset(p, 0xaa, db->lookaside.sz);
  18091. #endif
  18092. pBuf->pNext = db->lookaside.pFree;
  18093. db->lookaside.pFree = pBuf;
  18094. db->lookaside.nOut--;
  18095. return;
  18096. }
  18097. }
  18098. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18099. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18100. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18101. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18102. sqlite3_free(p);
  18103. }
  18104. /*
  18105. ** Change the size of an existing memory allocation
  18106. */
  18107. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18108. int nOld, nNew, nDiff;
  18109. void *pNew;
  18110. if( pOld==0 ){
  18111. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18112. }
  18113. if( nBytes<=0 ){
  18114. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18115. return 0;
  18116. }
  18117. if( nBytes>=0x7fffff00 ){
  18118. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18119. return 0;
  18120. }
  18121. nOld = sqlite3MallocSize(pOld);
  18122. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18123. ** argument to xRealloc is always a value returned by a prior call to
  18124. ** xRoundup. */
  18125. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18126. if( nOld==nNew ){
  18127. pNew = pOld;
  18128. }else if( sqlite3GlobalConfig.bMemstat ){
  18129. sqlite3_mutex_enter(mem0.mutex);
  18130. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18131. nDiff = nNew - nOld;
  18132. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18133. mem0.alarmThreshold-nDiff ){
  18134. sqlite3MallocAlarm(nDiff);
  18135. }
  18136. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18137. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18138. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18139. if( pNew==0 && mem0.alarmCallback ){
  18140. sqlite3MallocAlarm(nBytes);
  18141. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18142. }
  18143. if( pNew ){
  18144. nNew = sqlite3MallocSize(pNew);
  18145. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18146. }
  18147. sqlite3_mutex_leave(mem0.mutex);
  18148. }else{
  18149. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18150. }
  18151. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18152. return pNew;
  18153. }
  18154. /*
  18155. ** The public interface to sqlite3Realloc. Make sure that the memory
  18156. ** subsystem is initialized prior to invoking sqliteRealloc.
  18157. */
  18158. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18159. #ifndef SQLITE_OMIT_AUTOINIT
  18160. if( sqlite3_initialize() ) return 0;
  18161. #endif
  18162. return sqlite3Realloc(pOld, n);
  18163. }
  18164. /*
  18165. ** Allocate and zero memory.
  18166. */
  18167. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18168. void *p = sqlite3Malloc(n);
  18169. if( p ){
  18170. memset(p, 0, n);
  18171. }
  18172. return p;
  18173. }
  18174. /*
  18175. ** Allocate and zero memory. If the allocation fails, make
  18176. ** the mallocFailed flag in the connection pointer.
  18177. */
  18178. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18179. void *p = sqlite3DbMallocRaw(db, n);
  18180. if( p ){
  18181. memset(p, 0, n);
  18182. }
  18183. return p;
  18184. }
  18185. /*
  18186. ** Allocate and zero memory. If the allocation fails, make
  18187. ** the mallocFailed flag in the connection pointer.
  18188. **
  18189. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18190. ** failure on the same database connection) then always return 0.
  18191. ** Hence for a particular database connection, once malloc starts
  18192. ** failing, it fails consistently until mallocFailed is reset.
  18193. ** This is an important assumption. There are many places in the
  18194. ** code that do things like this:
  18195. **
  18196. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18197. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18198. ** if( b ) a[10] = 9;
  18199. **
  18200. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18201. ** that all prior mallocs (ex: "a") worked too.
  18202. */
  18203. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18204. void *p;
  18205. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18206. assert( db==0 || db->pnBytesFreed==0 );
  18207. #ifndef SQLITE_OMIT_LOOKASIDE
  18208. if( db ){
  18209. LookasideSlot *pBuf;
  18210. if( db->mallocFailed ){
  18211. return 0;
  18212. }
  18213. if( db->lookaside.bEnabled ){
  18214. if( n>db->lookaside.sz ){
  18215. db->lookaside.anStat[1]++;
  18216. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18217. db->lookaside.anStat[2]++;
  18218. }else{
  18219. db->lookaside.pFree = pBuf->pNext;
  18220. db->lookaside.nOut++;
  18221. db->lookaside.anStat[0]++;
  18222. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18223. db->lookaside.mxOut = db->lookaside.nOut;
  18224. }
  18225. return (void*)pBuf;
  18226. }
  18227. }
  18228. }
  18229. #else
  18230. if( db && db->mallocFailed ){
  18231. return 0;
  18232. }
  18233. #endif
  18234. p = sqlite3Malloc(n);
  18235. if( !p && db ){
  18236. db->mallocFailed = 1;
  18237. }
  18238. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18239. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18240. return p;
  18241. }
  18242. /*
  18243. ** Resize the block of memory pointed to by p to n bytes. If the
  18244. ** resize fails, set the mallocFailed flag in the connection object.
  18245. */
  18246. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18247. void *pNew = 0;
  18248. assert( db!=0 );
  18249. assert( sqlite3_mutex_held(db->mutex) );
  18250. if( db->mallocFailed==0 ){
  18251. if( p==0 ){
  18252. return sqlite3DbMallocRaw(db, n);
  18253. }
  18254. if( isLookaside(db, p) ){
  18255. if( n<=db->lookaside.sz ){
  18256. return p;
  18257. }
  18258. pNew = sqlite3DbMallocRaw(db, n);
  18259. if( pNew ){
  18260. memcpy(pNew, p, db->lookaside.sz);
  18261. sqlite3DbFree(db, p);
  18262. }
  18263. }else{
  18264. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18265. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18266. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18267. pNew = sqlite3_realloc(p, n);
  18268. if( !pNew ){
  18269. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18270. db->mallocFailed = 1;
  18271. }
  18272. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18273. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18274. }
  18275. }
  18276. return pNew;
  18277. }
  18278. /*
  18279. ** Attempt to reallocate p. If the reallocation fails, then free p
  18280. ** and set the mallocFailed flag in the database connection.
  18281. */
  18282. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18283. void *pNew;
  18284. pNew = sqlite3DbRealloc(db, p, n);
  18285. if( !pNew ){
  18286. sqlite3DbFree(db, p);
  18287. }
  18288. return pNew;
  18289. }
  18290. /*
  18291. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18292. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18293. ** is because when memory debugging is turned on, these two functions are
  18294. ** called via macros that record the current file and line number in the
  18295. ** ThreadData structure.
  18296. */
  18297. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18298. char *zNew;
  18299. size_t n;
  18300. if( z==0 ){
  18301. return 0;
  18302. }
  18303. n = sqlite3Strlen30(z) + 1;
  18304. assert( (n&0x7fffffff)==n );
  18305. zNew = sqlite3DbMallocRaw(db, (int)n);
  18306. if( zNew ){
  18307. memcpy(zNew, z, n);
  18308. }
  18309. return zNew;
  18310. }
  18311. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18312. char *zNew;
  18313. if( z==0 ){
  18314. return 0;
  18315. }
  18316. assert( (n&0x7fffffff)==n );
  18317. zNew = sqlite3DbMallocRaw(db, n+1);
  18318. if( zNew ){
  18319. memcpy(zNew, z, n);
  18320. zNew[n] = 0;
  18321. }
  18322. return zNew;
  18323. }
  18324. /*
  18325. ** Create a string from the zFromat argument and the va_list that follows.
  18326. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18327. ** point to that string.
  18328. */
  18329. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18330. va_list ap;
  18331. char *z;
  18332. va_start(ap, zFormat);
  18333. z = sqlite3VMPrintf(db, zFormat, ap);
  18334. va_end(ap);
  18335. sqlite3DbFree(db, *pz);
  18336. *pz = z;
  18337. }
  18338. /*
  18339. ** This function must be called before exiting any API function (i.e.
  18340. ** returning control to the user) that has called sqlite3_malloc or
  18341. ** sqlite3_realloc.
  18342. **
  18343. ** The returned value is normally a copy of the second argument to this
  18344. ** function. However, if a malloc() failure has occurred since the previous
  18345. ** invocation SQLITE_NOMEM is returned instead.
  18346. **
  18347. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18348. ** then the connection error-code (the value returned by sqlite3_errcode())
  18349. ** is set to SQLITE_NOMEM.
  18350. */
  18351. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18352. /* If the db handle is not NULL, then we must hold the connection handle
  18353. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18354. ** is unsafe, as is the call to sqlite3Error().
  18355. */
  18356. assert( !db || sqlite3_mutex_held(db->mutex) );
  18357. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18358. sqlite3Error(db, SQLITE_NOMEM, 0);
  18359. db->mallocFailed = 0;
  18360. rc = SQLITE_NOMEM;
  18361. }
  18362. return rc & (db ? db->errMask : 0xff);
  18363. }
  18364. /************** End of malloc.c **********************************************/
  18365. /************** Begin file printf.c ******************************************/
  18366. /*
  18367. ** The "printf" code that follows dates from the 1980's. It is in
  18368. ** the public domain. The original comments are included here for
  18369. ** completeness. They are very out-of-date but might be useful as
  18370. ** an historical reference. Most of the "enhancements" have been backed
  18371. ** out so that the functionality is now the same as standard printf().
  18372. **
  18373. **************************************************************************
  18374. **
  18375. ** This file contains code for a set of "printf"-like routines. These
  18376. ** routines format strings much like the printf() from the standard C
  18377. ** library, though the implementation here has enhancements to support
  18378. ** SQLlite.
  18379. */
  18380. /*
  18381. ** Conversion types fall into various categories as defined by the
  18382. ** following enumeration.
  18383. */
  18384. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18385. #define etFLOAT 2 /* Floating point. %f */
  18386. #define etEXP 3 /* Exponentional notation. %e and %E */
  18387. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18388. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18389. #define etSTRING 6 /* Strings. %s */
  18390. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18391. #define etPERCENT 8 /* Percent symbol. %% */
  18392. #define etCHARX 9 /* Characters. %c */
  18393. /* The rest are extensions, not normally found in printf() */
  18394. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18395. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18396. NULL pointers replaced by SQL NULL. %Q */
  18397. #define etTOKEN 12 /* a pointer to a Token structure */
  18398. #define etSRCLIST 13 /* a pointer to a SrcList */
  18399. #define etPOINTER 14 /* The %p conversion */
  18400. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18401. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18402. #define etINVALID 0 /* Any unrecognized conversion type */
  18403. /*
  18404. ** An "etByte" is an 8-bit unsigned value.
  18405. */
  18406. typedef unsigned char etByte;
  18407. /*
  18408. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18409. ** by an instance of the following structure
  18410. */
  18411. typedef struct et_info { /* Information about each format field */
  18412. char fmttype; /* The format field code letter */
  18413. etByte base; /* The base for radix conversion */
  18414. etByte flags; /* One or more of FLAG_ constants below */
  18415. etByte type; /* Conversion paradigm */
  18416. etByte charset; /* Offset into aDigits[] of the digits string */
  18417. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18418. } et_info;
  18419. /*
  18420. ** Allowed values for et_info.flags
  18421. */
  18422. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  18423. #define FLAG_INTERN 2 /* True if for internal use only */
  18424. #define FLAG_STRING 4 /* Allow infinity precision */
  18425. /*
  18426. ** The following table is searched linearly, so it is good to put the
  18427. ** most frequently used conversion types first.
  18428. */
  18429. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  18430. static const char aPrefix[] = "-x0\000X0";
  18431. static const et_info fmtinfo[] = {
  18432. { 'd', 10, 1, etRADIX, 0, 0 },
  18433. { 's', 0, 4, etSTRING, 0, 0 },
  18434. { 'g', 0, 1, etGENERIC, 30, 0 },
  18435. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  18436. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  18437. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  18438. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  18439. { 'c', 0, 0, etCHARX, 0, 0 },
  18440. { 'o', 8, 0, etRADIX, 0, 2 },
  18441. { 'u', 10, 0, etRADIX, 0, 0 },
  18442. { 'x', 16, 0, etRADIX, 16, 1 },
  18443. { 'X', 16, 0, etRADIX, 0, 4 },
  18444. #ifndef SQLITE_OMIT_FLOATING_POINT
  18445. { 'f', 0, 1, etFLOAT, 0, 0 },
  18446. { 'e', 0, 1, etEXP, 30, 0 },
  18447. { 'E', 0, 1, etEXP, 14, 0 },
  18448. { 'G', 0, 1, etGENERIC, 14, 0 },
  18449. #endif
  18450. { 'i', 10, 1, etRADIX, 0, 0 },
  18451. { 'n', 0, 0, etSIZE, 0, 0 },
  18452. { '%', 0, 0, etPERCENT, 0, 0 },
  18453. { 'p', 16, 0, etPOINTER, 0, 1 },
  18454. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  18455. ** use only */
  18456. { 'T', 0, 2, etTOKEN, 0, 0 },
  18457. { 'S', 0, 2, etSRCLIST, 0, 0 },
  18458. { 'r', 10, 3, etORDINAL, 0, 0 },
  18459. };
  18460. /*
  18461. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  18462. ** conversions will work.
  18463. */
  18464. #ifndef SQLITE_OMIT_FLOATING_POINT
  18465. /*
  18466. ** "*val" is a double such that 0.1 <= *val < 10.0
  18467. ** Return the ascii code for the leading digit of *val, then
  18468. ** multiply "*val" by 10.0 to renormalize.
  18469. **
  18470. ** Example:
  18471. ** input: *val = 3.14159
  18472. ** output: *val = 1.4159 function return = '3'
  18473. **
  18474. ** The counter *cnt is incremented each time. After counter exceeds
  18475. ** 16 (the number of significant digits in a 64-bit float) '0' is
  18476. ** always returned.
  18477. */
  18478. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  18479. int digit;
  18480. LONGDOUBLE_TYPE d;
  18481. if( (*cnt)<=0 ) return '0';
  18482. (*cnt)--;
  18483. digit = (int)*val;
  18484. d = digit;
  18485. digit += '0';
  18486. *val = (*val - d)*10.0;
  18487. return (char)digit;
  18488. }
  18489. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18490. /*
  18491. ** Append N space characters to the given string buffer.
  18492. */
  18493. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  18494. static const char zSpaces[] = " ";
  18495. while( N>=(int)sizeof(zSpaces)-1 ){
  18496. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  18497. N -= sizeof(zSpaces)-1;
  18498. }
  18499. if( N>0 ){
  18500. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  18501. }
  18502. }
  18503. /*
  18504. ** On machines with a small stack size, you can redefine the
  18505. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  18506. */
  18507. #ifndef SQLITE_PRINT_BUF_SIZE
  18508. # define SQLITE_PRINT_BUF_SIZE 70
  18509. #endif
  18510. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  18511. /*
  18512. ** Render a string given by "fmt" into the StrAccum object.
  18513. */
  18514. SQLITE_PRIVATE void sqlite3VXPrintf(
  18515. StrAccum *pAccum, /* Accumulate results here */
  18516. int useExtended, /* Allow extended %-conversions */
  18517. const char *fmt, /* Format string */
  18518. va_list ap /* arguments */
  18519. ){
  18520. int c; /* Next character in the format string */
  18521. char *bufpt; /* Pointer to the conversion buffer */
  18522. int precision; /* Precision of the current field */
  18523. int length; /* Length of the field */
  18524. int idx; /* A general purpose loop counter */
  18525. int width; /* Width of the current field */
  18526. etByte flag_leftjustify; /* True if "-" flag is present */
  18527. etByte flag_plussign; /* True if "+" flag is present */
  18528. etByte flag_blanksign; /* True if " " flag is present */
  18529. etByte flag_alternateform; /* True if "#" flag is present */
  18530. etByte flag_altform2; /* True if "!" flag is present */
  18531. etByte flag_zeropad; /* True if field width constant starts with zero */
  18532. etByte flag_long; /* True if "l" flag is present */
  18533. etByte flag_longlong; /* True if the "ll" flag is present */
  18534. etByte done; /* Loop termination flag */
  18535. etByte xtype = 0; /* Conversion paradigm */
  18536. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  18537. sqlite_uint64 longvalue; /* Value for integer types */
  18538. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  18539. const et_info *infop; /* Pointer to the appropriate info structure */
  18540. char *zOut; /* Rendering buffer */
  18541. int nOut; /* Size of the rendering buffer */
  18542. char *zExtra; /* Malloced memory used by some conversion */
  18543. #ifndef SQLITE_OMIT_FLOATING_POINT
  18544. int exp, e2; /* exponent of real numbers */
  18545. int nsd; /* Number of significant digits returned */
  18546. double rounder; /* Used for rounding floating point values */
  18547. etByte flag_dp; /* True if decimal point should be shown */
  18548. etByte flag_rtz; /* True if trailing zeros should be removed */
  18549. #endif
  18550. char buf[etBUFSIZE]; /* Conversion buffer */
  18551. bufpt = 0;
  18552. for(; (c=(*fmt))!=0; ++fmt){
  18553. if( c!='%' ){
  18554. int amt;
  18555. bufpt = (char *)fmt;
  18556. amt = 1;
  18557. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  18558. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  18559. if( c==0 ) break;
  18560. }
  18561. if( (c=(*++fmt))==0 ){
  18562. sqlite3StrAccumAppend(pAccum, "%", 1);
  18563. break;
  18564. }
  18565. /* Find out what flags are present */
  18566. flag_leftjustify = flag_plussign = flag_blanksign =
  18567. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  18568. done = 0;
  18569. do{
  18570. switch( c ){
  18571. case '-': flag_leftjustify = 1; break;
  18572. case '+': flag_plussign = 1; break;
  18573. case ' ': flag_blanksign = 1; break;
  18574. case '#': flag_alternateform = 1; break;
  18575. case '!': flag_altform2 = 1; break;
  18576. case '0': flag_zeropad = 1; break;
  18577. default: done = 1; break;
  18578. }
  18579. }while( !done && (c=(*++fmt))!=0 );
  18580. /* Get the field width */
  18581. width = 0;
  18582. if( c=='*' ){
  18583. width = va_arg(ap,int);
  18584. if( width<0 ){
  18585. flag_leftjustify = 1;
  18586. width = -width;
  18587. }
  18588. c = *++fmt;
  18589. }else{
  18590. while( c>='0' && c<='9' ){
  18591. width = width*10 + c - '0';
  18592. c = *++fmt;
  18593. }
  18594. }
  18595. /* Get the precision */
  18596. if( c=='.' ){
  18597. precision = 0;
  18598. c = *++fmt;
  18599. if( c=='*' ){
  18600. precision = va_arg(ap,int);
  18601. if( precision<0 ) precision = -precision;
  18602. c = *++fmt;
  18603. }else{
  18604. while( c>='0' && c<='9' ){
  18605. precision = precision*10 + c - '0';
  18606. c = *++fmt;
  18607. }
  18608. }
  18609. }else{
  18610. precision = -1;
  18611. }
  18612. /* Get the conversion type modifier */
  18613. if( c=='l' ){
  18614. flag_long = 1;
  18615. c = *++fmt;
  18616. if( c=='l' ){
  18617. flag_longlong = 1;
  18618. c = *++fmt;
  18619. }else{
  18620. flag_longlong = 0;
  18621. }
  18622. }else{
  18623. flag_long = flag_longlong = 0;
  18624. }
  18625. /* Fetch the info entry for the field */
  18626. infop = &fmtinfo[0];
  18627. xtype = etINVALID;
  18628. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  18629. if( c==fmtinfo[idx].fmttype ){
  18630. infop = &fmtinfo[idx];
  18631. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  18632. xtype = infop->type;
  18633. }else{
  18634. return;
  18635. }
  18636. break;
  18637. }
  18638. }
  18639. zExtra = 0;
  18640. /*
  18641. ** At this point, variables are initialized as follows:
  18642. **
  18643. ** flag_alternateform TRUE if a '#' is present.
  18644. ** flag_altform2 TRUE if a '!' is present.
  18645. ** flag_plussign TRUE if a '+' is present.
  18646. ** flag_leftjustify TRUE if a '-' is present or if the
  18647. ** field width was negative.
  18648. ** flag_zeropad TRUE if the width began with 0.
  18649. ** flag_long TRUE if the letter 'l' (ell) prefixed
  18650. ** the conversion character.
  18651. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  18652. ** the conversion character.
  18653. ** flag_blanksign TRUE if a ' ' is present.
  18654. ** width The specified field width. This is
  18655. ** always non-negative. Zero is the default.
  18656. ** precision The specified precision. The default
  18657. ** is -1.
  18658. ** xtype The class of the conversion.
  18659. ** infop Pointer to the appropriate info struct.
  18660. */
  18661. switch( xtype ){
  18662. case etPOINTER:
  18663. flag_longlong = sizeof(char*)==sizeof(i64);
  18664. flag_long = sizeof(char*)==sizeof(long int);
  18665. /* Fall through into the next case */
  18666. case etORDINAL:
  18667. case etRADIX:
  18668. if( infop->flags & FLAG_SIGNED ){
  18669. i64 v;
  18670. if( flag_longlong ){
  18671. v = va_arg(ap,i64);
  18672. }else if( flag_long ){
  18673. v = va_arg(ap,long int);
  18674. }else{
  18675. v = va_arg(ap,int);
  18676. }
  18677. if( v<0 ){
  18678. if( v==SMALLEST_INT64 ){
  18679. longvalue = ((u64)1)<<63;
  18680. }else{
  18681. longvalue = -v;
  18682. }
  18683. prefix = '-';
  18684. }else{
  18685. longvalue = v;
  18686. if( flag_plussign ) prefix = '+';
  18687. else if( flag_blanksign ) prefix = ' ';
  18688. else prefix = 0;
  18689. }
  18690. }else{
  18691. if( flag_longlong ){
  18692. longvalue = va_arg(ap,u64);
  18693. }else if( flag_long ){
  18694. longvalue = va_arg(ap,unsigned long int);
  18695. }else{
  18696. longvalue = va_arg(ap,unsigned int);
  18697. }
  18698. prefix = 0;
  18699. }
  18700. if( longvalue==0 ) flag_alternateform = 0;
  18701. if( flag_zeropad && precision<width-(prefix!=0) ){
  18702. precision = width-(prefix!=0);
  18703. }
  18704. if( precision<etBUFSIZE-10 ){
  18705. nOut = etBUFSIZE;
  18706. zOut = buf;
  18707. }else{
  18708. nOut = precision + 10;
  18709. zOut = zExtra = sqlite3Malloc( nOut );
  18710. if( zOut==0 ){
  18711. pAccum->mallocFailed = 1;
  18712. return;
  18713. }
  18714. }
  18715. bufpt = &zOut[nOut-1];
  18716. if( xtype==etORDINAL ){
  18717. static const char zOrd[] = "thstndrd";
  18718. int x = (int)(longvalue % 10);
  18719. if( x>=4 || (longvalue/10)%10==1 ){
  18720. x = 0;
  18721. }
  18722. *(--bufpt) = zOrd[x*2+1];
  18723. *(--bufpt) = zOrd[x*2];
  18724. }
  18725. {
  18726. register const char *cset; /* Use registers for speed */
  18727. register int base;
  18728. cset = &aDigits[infop->charset];
  18729. base = infop->base;
  18730. do{ /* Convert to ascii */
  18731. *(--bufpt) = cset[longvalue%base];
  18732. longvalue = longvalue/base;
  18733. }while( longvalue>0 );
  18734. }
  18735. length = (int)(&zOut[nOut-1]-bufpt);
  18736. for(idx=precision-length; idx>0; idx--){
  18737. *(--bufpt) = '0'; /* Zero pad */
  18738. }
  18739. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  18740. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  18741. const char *pre;
  18742. char x;
  18743. pre = &aPrefix[infop->prefix];
  18744. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  18745. }
  18746. length = (int)(&zOut[nOut-1]-bufpt);
  18747. break;
  18748. case etFLOAT:
  18749. case etEXP:
  18750. case etGENERIC:
  18751. realvalue = va_arg(ap,double);
  18752. #ifdef SQLITE_OMIT_FLOATING_POINT
  18753. length = 0;
  18754. #else
  18755. if( precision<0 ) precision = 6; /* Set default precision */
  18756. if( realvalue<0.0 ){
  18757. realvalue = -realvalue;
  18758. prefix = '-';
  18759. }else{
  18760. if( flag_plussign ) prefix = '+';
  18761. else if( flag_blanksign ) prefix = ' ';
  18762. else prefix = 0;
  18763. }
  18764. if( xtype==etGENERIC && precision>0 ) precision--;
  18765. #if 0
  18766. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  18767. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  18768. #else
  18769. /* It makes more sense to use 0.5 */
  18770. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  18771. #endif
  18772. if( xtype==etFLOAT ) realvalue += rounder;
  18773. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  18774. exp = 0;
  18775. if( sqlite3IsNaN((double)realvalue) ){
  18776. bufpt = "NaN";
  18777. length = 3;
  18778. break;
  18779. }
  18780. if( realvalue>0.0 ){
  18781. LONGDOUBLE_TYPE scale = 1.0;
  18782. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  18783. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  18784. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  18785. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  18786. realvalue /= scale;
  18787. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  18788. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  18789. if( exp>350 ){
  18790. if( prefix=='-' ){
  18791. bufpt = "-Inf";
  18792. }else if( prefix=='+' ){
  18793. bufpt = "+Inf";
  18794. }else{
  18795. bufpt = "Inf";
  18796. }
  18797. length = sqlite3Strlen30(bufpt);
  18798. break;
  18799. }
  18800. }
  18801. bufpt = buf;
  18802. /*
  18803. ** If the field type is etGENERIC, then convert to either etEXP
  18804. ** or etFLOAT, as appropriate.
  18805. */
  18806. if( xtype!=etFLOAT ){
  18807. realvalue += rounder;
  18808. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  18809. }
  18810. if( xtype==etGENERIC ){
  18811. flag_rtz = !flag_alternateform;
  18812. if( exp<-4 || exp>precision ){
  18813. xtype = etEXP;
  18814. }else{
  18815. precision = precision - exp;
  18816. xtype = etFLOAT;
  18817. }
  18818. }else{
  18819. flag_rtz = flag_altform2;
  18820. }
  18821. if( xtype==etEXP ){
  18822. e2 = 0;
  18823. }else{
  18824. e2 = exp;
  18825. }
  18826. if( e2+precision+width > etBUFSIZE - 15 ){
  18827. bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
  18828. if( bufpt==0 ){
  18829. pAccum->mallocFailed = 1;
  18830. return;
  18831. }
  18832. }
  18833. zOut = bufpt;
  18834. nsd = 16 + flag_altform2*10;
  18835. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  18836. /* The sign in front of the number */
  18837. if( prefix ){
  18838. *(bufpt++) = prefix;
  18839. }
  18840. /* Digits prior to the decimal point */
  18841. if( e2<0 ){
  18842. *(bufpt++) = '0';
  18843. }else{
  18844. for(; e2>=0; e2--){
  18845. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18846. }
  18847. }
  18848. /* The decimal point */
  18849. if( flag_dp ){
  18850. *(bufpt++) = '.';
  18851. }
  18852. /* "0" digits after the decimal point but before the first
  18853. ** significant digit of the number */
  18854. for(e2++; e2<0; precision--, e2++){
  18855. assert( precision>0 );
  18856. *(bufpt++) = '0';
  18857. }
  18858. /* Significant digits after the decimal point */
  18859. while( (precision--)>0 ){
  18860. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18861. }
  18862. /* Remove trailing zeros and the "." if no digits follow the "." */
  18863. if( flag_rtz && flag_dp ){
  18864. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  18865. assert( bufpt>zOut );
  18866. if( bufpt[-1]=='.' ){
  18867. if( flag_altform2 ){
  18868. *(bufpt++) = '0';
  18869. }else{
  18870. *(--bufpt) = 0;
  18871. }
  18872. }
  18873. }
  18874. /* Add the "eNNN" suffix */
  18875. if( xtype==etEXP ){
  18876. *(bufpt++) = aDigits[infop->charset];
  18877. if( exp<0 ){
  18878. *(bufpt++) = '-'; exp = -exp;
  18879. }else{
  18880. *(bufpt++) = '+';
  18881. }
  18882. if( exp>=100 ){
  18883. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  18884. exp %= 100;
  18885. }
  18886. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  18887. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  18888. }
  18889. *bufpt = 0;
  18890. /* The converted number is in buf[] and zero terminated. Output it.
  18891. ** Note that the number is in the usual order, not reversed as with
  18892. ** integer conversions. */
  18893. length = (int)(bufpt-zOut);
  18894. bufpt = zOut;
  18895. /* Special case: Add leading zeros if the flag_zeropad flag is
  18896. ** set and we are not left justified */
  18897. if( flag_zeropad && !flag_leftjustify && length < width){
  18898. int i;
  18899. int nPad = width - length;
  18900. for(i=width; i>=nPad; i--){
  18901. bufpt[i] = bufpt[i-nPad];
  18902. }
  18903. i = prefix!=0;
  18904. while( nPad-- ) bufpt[i++] = '0';
  18905. length = width;
  18906. }
  18907. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  18908. break;
  18909. case etSIZE:
  18910. *(va_arg(ap,int*)) = pAccum->nChar;
  18911. length = width = 0;
  18912. break;
  18913. case etPERCENT:
  18914. buf[0] = '%';
  18915. bufpt = buf;
  18916. length = 1;
  18917. break;
  18918. case etCHARX:
  18919. c = va_arg(ap,int);
  18920. buf[0] = (char)c;
  18921. if( precision>=0 ){
  18922. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  18923. length = precision;
  18924. }else{
  18925. length =1;
  18926. }
  18927. bufpt = buf;
  18928. break;
  18929. case etSTRING:
  18930. case etDYNSTRING:
  18931. bufpt = va_arg(ap,char*);
  18932. if( bufpt==0 ){
  18933. bufpt = "";
  18934. }else if( xtype==etDYNSTRING ){
  18935. zExtra = bufpt;
  18936. }
  18937. if( precision>=0 ){
  18938. for(length=0; length<precision && bufpt[length]; length++){}
  18939. }else{
  18940. length = sqlite3Strlen30(bufpt);
  18941. }
  18942. break;
  18943. case etSQLESCAPE:
  18944. case etSQLESCAPE2:
  18945. case etSQLESCAPE3: {
  18946. int i, j, k, n, isnull;
  18947. int needQuote;
  18948. char ch;
  18949. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  18950. char *escarg = va_arg(ap,char*);
  18951. isnull = escarg==0;
  18952. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  18953. k = precision;
  18954. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  18955. if( ch==q ) n++;
  18956. }
  18957. needQuote = !isnull && xtype==etSQLESCAPE2;
  18958. n += i + 1 + needQuote*2;
  18959. if( n>etBUFSIZE ){
  18960. bufpt = zExtra = sqlite3Malloc( n );
  18961. if( bufpt==0 ){
  18962. pAccum->mallocFailed = 1;
  18963. return;
  18964. }
  18965. }else{
  18966. bufpt = buf;
  18967. }
  18968. j = 0;
  18969. if( needQuote ) bufpt[j++] = q;
  18970. k = i;
  18971. for(i=0; i<k; i++){
  18972. bufpt[j++] = ch = escarg[i];
  18973. if( ch==q ) bufpt[j++] = ch;
  18974. }
  18975. if( needQuote ) bufpt[j++] = q;
  18976. bufpt[j] = 0;
  18977. length = j;
  18978. /* The precision in %q and %Q means how many input characters to
  18979. ** consume, not the length of the output...
  18980. ** if( precision>=0 && precision<length ) length = precision; */
  18981. break;
  18982. }
  18983. case etTOKEN: {
  18984. Token *pToken = va_arg(ap, Token*);
  18985. if( pToken ){
  18986. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  18987. }
  18988. length = width = 0;
  18989. break;
  18990. }
  18991. case etSRCLIST: {
  18992. SrcList *pSrc = va_arg(ap, SrcList*);
  18993. int k = va_arg(ap, int);
  18994. struct SrcList_item *pItem = &pSrc->a[k];
  18995. assert( k>=0 && k<pSrc->nSrc );
  18996. if( pItem->zDatabase ){
  18997. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  18998. sqlite3StrAccumAppend(pAccum, ".", 1);
  18999. }
  19000. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  19001. length = width = 0;
  19002. break;
  19003. }
  19004. default: {
  19005. assert( xtype==etINVALID );
  19006. return;
  19007. }
  19008. }/* End switch over the format type */
  19009. /*
  19010. ** The text of the conversion is pointed to by "bufpt" and is
  19011. ** "length" characters long. The field width is "width". Do
  19012. ** the output.
  19013. */
  19014. if( !flag_leftjustify ){
  19015. register int nspace;
  19016. nspace = width-length;
  19017. if( nspace>0 ){
  19018. sqlite3AppendSpace(pAccum, nspace);
  19019. }
  19020. }
  19021. if( length>0 ){
  19022. sqlite3StrAccumAppend(pAccum, bufpt, length);
  19023. }
  19024. if( flag_leftjustify ){
  19025. register int nspace;
  19026. nspace = width-length;
  19027. if( nspace>0 ){
  19028. sqlite3AppendSpace(pAccum, nspace);
  19029. }
  19030. }
  19031. sqlite3_free(zExtra);
  19032. }/* End for loop over the format string */
  19033. } /* End of function */
  19034. /*
  19035. ** Append N bytes of text from z to the StrAccum object.
  19036. */
  19037. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19038. assert( z!=0 || N==0 );
  19039. if( p->tooBig | p->mallocFailed ){
  19040. testcase(p->tooBig);
  19041. testcase(p->mallocFailed);
  19042. return;
  19043. }
  19044. assert( p->zText!=0 || p->nChar==0 );
  19045. if( N<0 ){
  19046. N = sqlite3Strlen30(z);
  19047. }
  19048. if( N==0 || NEVER(z==0) ){
  19049. return;
  19050. }
  19051. if( p->nChar+N >= p->nAlloc ){
  19052. char *zNew;
  19053. if( !p->useMalloc ){
  19054. p->tooBig = 1;
  19055. N = p->nAlloc - p->nChar - 1;
  19056. if( N<=0 ){
  19057. return;
  19058. }
  19059. }else{
  19060. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19061. i64 szNew = p->nChar;
  19062. szNew += N + 1;
  19063. if( szNew > p->mxAlloc ){
  19064. sqlite3StrAccumReset(p);
  19065. p->tooBig = 1;
  19066. return;
  19067. }else{
  19068. p->nAlloc = (int)szNew;
  19069. }
  19070. if( p->useMalloc==1 ){
  19071. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19072. }else{
  19073. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19074. }
  19075. if( zNew ){
  19076. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19077. p->zText = zNew;
  19078. }else{
  19079. p->mallocFailed = 1;
  19080. sqlite3StrAccumReset(p);
  19081. return;
  19082. }
  19083. }
  19084. }
  19085. assert( p->zText );
  19086. memcpy(&p->zText[p->nChar], z, N);
  19087. p->nChar += N;
  19088. }
  19089. /*
  19090. ** Finish off a string by making sure it is zero-terminated.
  19091. ** Return a pointer to the resulting string. Return a NULL
  19092. ** pointer if any kind of error was encountered.
  19093. */
  19094. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19095. if( p->zText ){
  19096. p->zText[p->nChar] = 0;
  19097. if( p->useMalloc && p->zText==p->zBase ){
  19098. if( p->useMalloc==1 ){
  19099. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19100. }else{
  19101. p->zText = sqlite3_malloc(p->nChar+1);
  19102. }
  19103. if( p->zText ){
  19104. memcpy(p->zText, p->zBase, p->nChar+1);
  19105. }else{
  19106. p->mallocFailed = 1;
  19107. }
  19108. }
  19109. }
  19110. return p->zText;
  19111. }
  19112. /*
  19113. ** Reset an StrAccum string. Reclaim all malloced memory.
  19114. */
  19115. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19116. if( p->zText!=p->zBase ){
  19117. if( p->useMalloc==1 ){
  19118. sqlite3DbFree(p->db, p->zText);
  19119. }else{
  19120. sqlite3_free(p->zText);
  19121. }
  19122. }
  19123. p->zText = 0;
  19124. }
  19125. /*
  19126. ** Initialize a string accumulator
  19127. */
  19128. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19129. p->zText = p->zBase = zBase;
  19130. p->db = 0;
  19131. p->nChar = 0;
  19132. p->nAlloc = n;
  19133. p->mxAlloc = mx;
  19134. p->useMalloc = 1;
  19135. p->tooBig = 0;
  19136. p->mallocFailed = 0;
  19137. }
  19138. /*
  19139. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19140. ** %-conversion extensions.
  19141. */
  19142. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19143. char *z;
  19144. char zBase[SQLITE_PRINT_BUF_SIZE];
  19145. StrAccum acc;
  19146. assert( db!=0 );
  19147. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19148. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19149. acc.db = db;
  19150. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19151. z = sqlite3StrAccumFinish(&acc);
  19152. if( acc.mallocFailed ){
  19153. db->mallocFailed = 1;
  19154. }
  19155. return z;
  19156. }
  19157. /*
  19158. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19159. ** %-conversion extensions.
  19160. */
  19161. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19162. va_list ap;
  19163. char *z;
  19164. va_start(ap, zFormat);
  19165. z = sqlite3VMPrintf(db, zFormat, ap);
  19166. va_end(ap);
  19167. return z;
  19168. }
  19169. /*
  19170. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19171. ** the string and before returnning. This routine is intended to be used
  19172. ** to modify an existing string. For example:
  19173. **
  19174. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19175. **
  19176. */
  19177. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19178. va_list ap;
  19179. char *z;
  19180. va_start(ap, zFormat);
  19181. z = sqlite3VMPrintf(db, zFormat, ap);
  19182. va_end(ap);
  19183. sqlite3DbFree(db, zStr);
  19184. return z;
  19185. }
  19186. /*
  19187. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19188. ** %-conversion extensions.
  19189. */
  19190. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19191. char *z;
  19192. char zBase[SQLITE_PRINT_BUF_SIZE];
  19193. StrAccum acc;
  19194. #ifndef SQLITE_OMIT_AUTOINIT
  19195. if( sqlite3_initialize() ) return 0;
  19196. #endif
  19197. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19198. acc.useMalloc = 2;
  19199. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19200. z = sqlite3StrAccumFinish(&acc);
  19201. return z;
  19202. }
  19203. /*
  19204. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19205. ** %-conversion extensions.
  19206. */
  19207. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19208. va_list ap;
  19209. char *z;
  19210. #ifndef SQLITE_OMIT_AUTOINIT
  19211. if( sqlite3_initialize() ) return 0;
  19212. #endif
  19213. va_start(ap, zFormat);
  19214. z = sqlite3_vmprintf(zFormat, ap);
  19215. va_end(ap);
  19216. return z;
  19217. }
  19218. /*
  19219. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19220. ** current locale settings. This is important for SQLite because we
  19221. ** are not able to use a "," as the decimal point in place of "." as
  19222. ** specified by some locales.
  19223. **
  19224. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19225. ** from the snprintf() standard. Unfortunately, it is too late to change
  19226. ** this without breaking compatibility, so we just have to live with the
  19227. ** mistake.
  19228. **
  19229. ** sqlite3_vsnprintf() is the varargs version.
  19230. */
  19231. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19232. StrAccum acc;
  19233. if( n<=0 ) return zBuf;
  19234. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19235. acc.useMalloc = 0;
  19236. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19237. return sqlite3StrAccumFinish(&acc);
  19238. }
  19239. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19240. char *z;
  19241. va_list ap;
  19242. va_start(ap,zFormat);
  19243. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19244. va_end(ap);
  19245. return z;
  19246. }
  19247. /*
  19248. ** This is the routine that actually formats the sqlite3_log() message.
  19249. ** We house it in a separate routine from sqlite3_log() to avoid using
  19250. ** stack space on small-stack systems when logging is disabled.
  19251. **
  19252. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19253. ** allocate memory because it might be called while the memory allocator
  19254. ** mutex is held.
  19255. */
  19256. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19257. StrAccum acc; /* String accumulator */
  19258. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19259. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19260. acc.useMalloc = 0;
  19261. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19262. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19263. sqlite3StrAccumFinish(&acc));
  19264. }
  19265. /*
  19266. ** Format and write a message to the log if logging is enabled.
  19267. */
  19268. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19269. va_list ap; /* Vararg list */
  19270. if( sqlite3GlobalConfig.xLog ){
  19271. va_start(ap, zFormat);
  19272. renderLogMsg(iErrCode, zFormat, ap);
  19273. va_end(ap);
  19274. }
  19275. }
  19276. #if defined(SQLITE_DEBUG)
  19277. /*
  19278. ** A version of printf() that understands %lld. Used for debugging.
  19279. ** The printf() built into some versions of windows does not understand %lld
  19280. ** and segfaults if you give it a long long int.
  19281. */
  19282. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19283. va_list ap;
  19284. StrAccum acc;
  19285. char zBuf[500];
  19286. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19287. acc.useMalloc = 0;
  19288. va_start(ap,zFormat);
  19289. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19290. va_end(ap);
  19291. sqlite3StrAccumFinish(&acc);
  19292. fprintf(stdout,"%s", zBuf);
  19293. fflush(stdout);
  19294. }
  19295. #endif
  19296. #ifndef SQLITE_OMIT_TRACE
  19297. /*
  19298. ** variable-argument wrapper around sqlite3VXPrintf().
  19299. */
  19300. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19301. va_list ap;
  19302. va_start(ap,zFormat);
  19303. sqlite3VXPrintf(p, 1, zFormat, ap);
  19304. va_end(ap);
  19305. }
  19306. #endif
  19307. /************** End of printf.c **********************************************/
  19308. /************** Begin file random.c ******************************************/
  19309. /*
  19310. ** 2001 September 15
  19311. **
  19312. ** The author disclaims copyright to this source code. In place of
  19313. ** a legal notice, here is a blessing:
  19314. **
  19315. ** May you do good and not evil.
  19316. ** May you find forgiveness for yourself and forgive others.
  19317. ** May you share freely, never taking more than you give.
  19318. **
  19319. *************************************************************************
  19320. ** This file contains code to implement a pseudo-random number
  19321. ** generator (PRNG) for SQLite.
  19322. **
  19323. ** Random numbers are used by some of the database backends in order
  19324. ** to generate random integer keys for tables or random filenames.
  19325. */
  19326. /* All threads share a single random number generator.
  19327. ** This structure is the current state of the generator.
  19328. */
  19329. static SQLITE_WSD struct sqlite3PrngType {
  19330. unsigned char isInit; /* True if initialized */
  19331. unsigned char i, j; /* State variables */
  19332. unsigned char s[256]; /* State variables */
  19333. } sqlite3Prng;
  19334. /*
  19335. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  19336. ** must be held while executing this routine.
  19337. **
  19338. ** Why not just use a library random generator like lrand48() for this?
  19339. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  19340. ** good source of random numbers. The lrand48() library function may
  19341. ** well be good enough. But maybe not. Or maybe lrand48() has some
  19342. ** subtle problems on some systems that could cause problems. It is hard
  19343. ** to know. To minimize the risk of problems due to bad lrand48()
  19344. ** implementations, SQLite uses this random number generator based
  19345. ** on RC4, which we know works very well.
  19346. **
  19347. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  19348. ** randomness any more. But we will leave this code in all the same.
  19349. */
  19350. static u8 randomByte(void){
  19351. unsigned char t;
  19352. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19353. ** state vector. If writable static data is unsupported on the target,
  19354. ** we have to locate the state vector at run-time. In the more common
  19355. ** case where writable static data is supported, wsdPrng can refer directly
  19356. ** to the "sqlite3Prng" state vector declared above.
  19357. */
  19358. #ifdef SQLITE_OMIT_WSD
  19359. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19360. # define wsdPrng p[0]
  19361. #else
  19362. # define wsdPrng sqlite3Prng
  19363. #endif
  19364. /* Initialize the state of the random number generator once,
  19365. ** the first time this routine is called. The seed value does
  19366. ** not need to contain a lot of randomness since we are not
  19367. ** trying to do secure encryption or anything like that...
  19368. **
  19369. ** Nothing in this file or anywhere else in SQLite does any kind of
  19370. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19371. ** number generator) not as an encryption device.
  19372. */
  19373. if( !wsdPrng.isInit ){
  19374. int i;
  19375. char k[256];
  19376. wsdPrng.j = 0;
  19377. wsdPrng.i = 0;
  19378. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19379. for(i=0; i<256; i++){
  19380. wsdPrng.s[i] = (u8)i;
  19381. }
  19382. for(i=0; i<256; i++){
  19383. wsdPrng.j += wsdPrng.s[i] + k[i];
  19384. t = wsdPrng.s[wsdPrng.j];
  19385. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19386. wsdPrng.s[i] = t;
  19387. }
  19388. wsdPrng.isInit = 1;
  19389. }
  19390. /* Generate and return single random byte
  19391. */
  19392. wsdPrng.i++;
  19393. t = wsdPrng.s[wsdPrng.i];
  19394. wsdPrng.j += t;
  19395. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19396. wsdPrng.s[wsdPrng.j] = t;
  19397. t += wsdPrng.s[wsdPrng.i];
  19398. return wsdPrng.s[t];
  19399. }
  19400. /*
  19401. ** Return N random bytes.
  19402. */
  19403. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19404. unsigned char *zBuf = pBuf;
  19405. #if SQLITE_THREADSAFE
  19406. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19407. #endif
  19408. sqlite3_mutex_enter(mutex);
  19409. while( N-- ){
  19410. *(zBuf++) = randomByte();
  19411. }
  19412. sqlite3_mutex_leave(mutex);
  19413. }
  19414. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19415. /*
  19416. ** For testing purposes, we sometimes want to preserve the state of
  19417. ** PRNG and restore the PRNG to its saved state at a later time, or
  19418. ** to reset the PRNG to its initial state. These routines accomplish
  19419. ** those tasks.
  19420. **
  19421. ** The sqlite3_test_control() interface calls these routines to
  19422. ** control the PRNG.
  19423. */
  19424. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19425. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19426. memcpy(
  19427. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19428. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19429. sizeof(sqlite3Prng)
  19430. );
  19431. }
  19432. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19433. memcpy(
  19434. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19435. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19436. sizeof(sqlite3Prng)
  19437. );
  19438. }
  19439. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19440. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19441. }
  19442. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19443. /************** End of random.c **********************************************/
  19444. /************** Begin file utf.c *********************************************/
  19445. /*
  19446. ** 2004 April 13
  19447. **
  19448. ** The author disclaims copyright to this source code. In place of
  19449. ** a legal notice, here is a blessing:
  19450. **
  19451. ** May you do good and not evil.
  19452. ** May you find forgiveness for yourself and forgive others.
  19453. ** May you share freely, never taking more than you give.
  19454. **
  19455. *************************************************************************
  19456. ** This file contains routines used to translate between UTF-8,
  19457. ** UTF-16, UTF-16BE, and UTF-16LE.
  19458. **
  19459. ** Notes on UTF-8:
  19460. **
  19461. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  19462. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  19463. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  19464. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  19465. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19466. **
  19467. **
  19468. ** Notes on UTF-16: (with wwww+1==uuuuu)
  19469. **
  19470. ** Word-0 Word-1 Value
  19471. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19472. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  19473. **
  19474. **
  19475. ** BOM or Byte Order Mark:
  19476. ** 0xff 0xfe little-endian utf-16 follows
  19477. ** 0xfe 0xff big-endian utf-16 follows
  19478. **
  19479. */
  19480. /* #include <assert.h> */
  19481. #ifndef SQLITE_AMALGAMATION
  19482. /*
  19483. ** The following constant value is used by the SQLITE_BIGENDIAN and
  19484. ** SQLITE_LITTLEENDIAN macros.
  19485. */
  19486. SQLITE_PRIVATE const int sqlite3one = 1;
  19487. #endif /* SQLITE_AMALGAMATION */
  19488. /*
  19489. ** This lookup table is used to help decode the first byte of
  19490. ** a multi-byte UTF8 character.
  19491. */
  19492. static const unsigned char sqlite3Utf8Trans1[] = {
  19493. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19494. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19495. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  19496. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  19497. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19498. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19499. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19500. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  19501. };
  19502. #define WRITE_UTF8(zOut, c) { \
  19503. if( c<0x00080 ){ \
  19504. *zOut++ = (u8)(c&0xFF); \
  19505. } \
  19506. else if( c<0x00800 ){ \
  19507. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  19508. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19509. } \
  19510. else if( c<0x10000 ){ \
  19511. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  19512. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19513. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19514. }else{ \
  19515. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  19516. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  19517. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19518. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19519. } \
  19520. }
  19521. #define WRITE_UTF16LE(zOut, c) { \
  19522. if( c<=0xFFFF ){ \
  19523. *zOut++ = (u8)(c&0x00FF); \
  19524. *zOut++ = (u8)((c>>8)&0x00FF); \
  19525. }else{ \
  19526. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19527. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19528. *zOut++ = (u8)(c&0x00FF); \
  19529. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19530. } \
  19531. }
  19532. #define WRITE_UTF16BE(zOut, c) { \
  19533. if( c<=0xFFFF ){ \
  19534. *zOut++ = (u8)((c>>8)&0x00FF); \
  19535. *zOut++ = (u8)(c&0x00FF); \
  19536. }else{ \
  19537. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19538. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19539. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19540. *zOut++ = (u8)(c&0x00FF); \
  19541. } \
  19542. }
  19543. #define READ_UTF16LE(zIn, TERM, c){ \
  19544. c = (*zIn++); \
  19545. c += ((*zIn++)<<8); \
  19546. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19547. int c2 = (*zIn++); \
  19548. c2 += ((*zIn++)<<8); \
  19549. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19550. } \
  19551. }
  19552. #define READ_UTF16BE(zIn, TERM, c){ \
  19553. c = ((*zIn++)<<8); \
  19554. c += (*zIn++); \
  19555. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19556. int c2 = ((*zIn++)<<8); \
  19557. c2 += (*zIn++); \
  19558. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19559. } \
  19560. }
  19561. /*
  19562. ** Translate a single UTF-8 character. Return the unicode value.
  19563. **
  19564. ** During translation, assume that the byte that zTerm points
  19565. ** is a 0x00.
  19566. **
  19567. ** Write a pointer to the next unread byte back into *pzNext.
  19568. **
  19569. ** Notes On Invalid UTF-8:
  19570. **
  19571. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  19572. ** be encoded as a multi-byte character. Any multi-byte character that
  19573. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  19574. **
  19575. ** * This routine never allows a UTF16 surrogate value to be encoded.
  19576. ** If a multi-byte character attempts to encode a value between
  19577. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  19578. **
  19579. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  19580. ** byte of a character are interpreted as single-byte characters
  19581. ** and rendered as themselves even though they are technically
  19582. ** invalid characters.
  19583. **
  19584. ** * This routine accepts an infinite number of different UTF8 encodings
  19585. ** for unicode values 0x80 and greater. It do not change over-length
  19586. ** encodings to 0xfffd as some systems recommend.
  19587. */
  19588. #define READ_UTF8(zIn, zTerm, c) \
  19589. c = *(zIn++); \
  19590. if( c>=0xc0 ){ \
  19591. c = sqlite3Utf8Trans1[c-0xc0]; \
  19592. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  19593. c = (c<<6) + (0x3f & *(zIn++)); \
  19594. } \
  19595. if( c<0x80 \
  19596. || (c&0xFFFFF800)==0xD800 \
  19597. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  19598. }
  19599. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  19600. const unsigned char **pz /* Pointer to string from which to read char */
  19601. ){
  19602. unsigned int c;
  19603. /* Same as READ_UTF8() above but without the zTerm parameter.
  19604. ** For this routine, we assume the UTF8 string is always zero-terminated.
  19605. */
  19606. c = *((*pz)++);
  19607. if( c>=0xc0 ){
  19608. c = sqlite3Utf8Trans1[c-0xc0];
  19609. while( (*(*pz) & 0xc0)==0x80 ){
  19610. c = (c<<6) + (0x3f & *((*pz)++));
  19611. }
  19612. if( c<0x80
  19613. || (c&0xFFFFF800)==0xD800
  19614. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  19615. }
  19616. return c;
  19617. }
  19618. /*
  19619. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  19620. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  19621. */
  19622. /* #define TRANSLATE_TRACE 1 */
  19623. #ifndef SQLITE_OMIT_UTF16
  19624. /*
  19625. ** This routine transforms the internal text encoding used by pMem to
  19626. ** desiredEnc. It is an error if the string is already of the desired
  19627. ** encoding, or if *pMem does not contain a string value.
  19628. */
  19629. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  19630. int len; /* Maximum length of output string in bytes */
  19631. unsigned char *zOut; /* Output buffer */
  19632. unsigned char *zIn; /* Input iterator */
  19633. unsigned char *zTerm; /* End of input */
  19634. unsigned char *z; /* Output iterator */
  19635. unsigned int c;
  19636. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  19637. assert( pMem->flags&MEM_Str );
  19638. assert( pMem->enc!=desiredEnc );
  19639. assert( pMem->enc!=0 );
  19640. assert( pMem->n>=0 );
  19641. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19642. {
  19643. char zBuf[100];
  19644. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19645. fprintf(stderr, "INPUT: %s\n", zBuf);
  19646. }
  19647. #endif
  19648. /* If the translation is between UTF-16 little and big endian, then
  19649. ** all that is required is to swap the byte order. This case is handled
  19650. ** differently from the others.
  19651. */
  19652. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  19653. u8 temp;
  19654. int rc;
  19655. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19656. if( rc!=SQLITE_OK ){
  19657. assert( rc==SQLITE_NOMEM );
  19658. return SQLITE_NOMEM;
  19659. }
  19660. zIn = (u8*)pMem->z;
  19661. zTerm = &zIn[pMem->n&~1];
  19662. while( zIn<zTerm ){
  19663. temp = *zIn;
  19664. *zIn = *(zIn+1);
  19665. zIn++;
  19666. *zIn++ = temp;
  19667. }
  19668. pMem->enc = desiredEnc;
  19669. goto translate_out;
  19670. }
  19671. /* Set len to the maximum number of bytes required in the output buffer. */
  19672. if( desiredEnc==SQLITE_UTF8 ){
  19673. /* When converting from UTF-16, the maximum growth results from
  19674. ** translating a 2-byte character to a 4-byte UTF-8 character.
  19675. ** A single byte is required for the output string
  19676. ** nul-terminator.
  19677. */
  19678. pMem->n &= ~1;
  19679. len = pMem->n * 2 + 1;
  19680. }else{
  19681. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  19682. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  19683. ** character. Two bytes are required in the output buffer for the
  19684. ** nul-terminator.
  19685. */
  19686. len = pMem->n * 2 + 2;
  19687. }
  19688. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  19689. ** byte past the end.
  19690. **
  19691. ** Variable zOut is set to point at the output buffer, space obtained
  19692. ** from sqlite3_malloc().
  19693. */
  19694. zIn = (u8*)pMem->z;
  19695. zTerm = &zIn[pMem->n];
  19696. zOut = sqlite3DbMallocRaw(pMem->db, len);
  19697. if( !zOut ){
  19698. return SQLITE_NOMEM;
  19699. }
  19700. z = zOut;
  19701. if( pMem->enc==SQLITE_UTF8 ){
  19702. if( desiredEnc==SQLITE_UTF16LE ){
  19703. /* UTF-8 -> UTF-16 Little-endian */
  19704. while( zIn<zTerm ){
  19705. READ_UTF8(zIn, zTerm, c);
  19706. WRITE_UTF16LE(z, c);
  19707. }
  19708. }else{
  19709. assert( desiredEnc==SQLITE_UTF16BE );
  19710. /* UTF-8 -> UTF-16 Big-endian */
  19711. while( zIn<zTerm ){
  19712. READ_UTF8(zIn, zTerm, c);
  19713. WRITE_UTF16BE(z, c);
  19714. }
  19715. }
  19716. pMem->n = (int)(z - zOut);
  19717. *z++ = 0;
  19718. }else{
  19719. assert( desiredEnc==SQLITE_UTF8 );
  19720. if( pMem->enc==SQLITE_UTF16LE ){
  19721. /* UTF-16 Little-endian -> UTF-8 */
  19722. while( zIn<zTerm ){
  19723. READ_UTF16LE(zIn, zIn<zTerm, c);
  19724. WRITE_UTF8(z, c);
  19725. }
  19726. }else{
  19727. /* UTF-16 Big-endian -> UTF-8 */
  19728. while( zIn<zTerm ){
  19729. READ_UTF16BE(zIn, zIn<zTerm, c);
  19730. WRITE_UTF8(z, c);
  19731. }
  19732. }
  19733. pMem->n = (int)(z - zOut);
  19734. }
  19735. *z = 0;
  19736. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  19737. sqlite3VdbeMemRelease(pMem);
  19738. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  19739. pMem->enc = desiredEnc;
  19740. pMem->flags |= (MEM_Term|MEM_Dyn);
  19741. pMem->z = (char*)zOut;
  19742. pMem->zMalloc = pMem->z;
  19743. translate_out:
  19744. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19745. {
  19746. char zBuf[100];
  19747. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19748. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  19749. }
  19750. #endif
  19751. return SQLITE_OK;
  19752. }
  19753. /*
  19754. ** This routine checks for a byte-order mark at the beginning of the
  19755. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  19756. ** the encoding of the Mem adjusted. This routine does not do any
  19757. ** byte-swapping, it just sets Mem.enc appropriately.
  19758. **
  19759. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  19760. ** changed by this function.
  19761. */
  19762. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  19763. int rc = SQLITE_OK;
  19764. u8 bom = 0;
  19765. assert( pMem->n>=0 );
  19766. if( pMem->n>1 ){
  19767. u8 b1 = *(u8 *)pMem->z;
  19768. u8 b2 = *(((u8 *)pMem->z) + 1);
  19769. if( b1==0xFE && b2==0xFF ){
  19770. bom = SQLITE_UTF16BE;
  19771. }
  19772. if( b1==0xFF && b2==0xFE ){
  19773. bom = SQLITE_UTF16LE;
  19774. }
  19775. }
  19776. if( bom ){
  19777. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19778. if( rc==SQLITE_OK ){
  19779. pMem->n -= 2;
  19780. memmove(pMem->z, &pMem->z[2], pMem->n);
  19781. pMem->z[pMem->n] = '\0';
  19782. pMem->z[pMem->n+1] = '\0';
  19783. pMem->flags |= MEM_Term;
  19784. pMem->enc = bom;
  19785. }
  19786. }
  19787. return rc;
  19788. }
  19789. #endif /* SQLITE_OMIT_UTF16 */
  19790. /*
  19791. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  19792. ** return the number of unicode characters in pZ up to (but not including)
  19793. ** the first 0x00 byte. If nByte is not less than zero, return the
  19794. ** number of unicode characters in the first nByte of pZ (or up to
  19795. ** the first 0x00, whichever comes first).
  19796. */
  19797. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  19798. int r = 0;
  19799. const u8 *z = (const u8*)zIn;
  19800. const u8 *zTerm;
  19801. if( nByte>=0 ){
  19802. zTerm = &z[nByte];
  19803. }else{
  19804. zTerm = (const u8*)(-1);
  19805. }
  19806. assert( z<=zTerm );
  19807. while( *z!=0 && z<zTerm ){
  19808. SQLITE_SKIP_UTF8(z);
  19809. r++;
  19810. }
  19811. return r;
  19812. }
  19813. /* This test function is not currently used by the automated test-suite.
  19814. ** Hence it is only available in debug builds.
  19815. */
  19816. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  19817. /*
  19818. ** Translate UTF-8 to UTF-8.
  19819. **
  19820. ** This has the effect of making sure that the string is well-formed
  19821. ** UTF-8. Miscoded characters are removed.
  19822. **
  19823. ** The translation is done in-place and aborted if the output
  19824. ** overruns the input.
  19825. */
  19826. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  19827. unsigned char *zOut = zIn;
  19828. unsigned char *zStart = zIn;
  19829. u32 c;
  19830. while( zIn[0] && zOut<=zIn ){
  19831. c = sqlite3Utf8Read((const u8**)&zIn);
  19832. if( c!=0xfffd ){
  19833. WRITE_UTF8(zOut, c);
  19834. }
  19835. }
  19836. *zOut = 0;
  19837. return (int)(zOut - zStart);
  19838. }
  19839. #endif
  19840. #ifndef SQLITE_OMIT_UTF16
  19841. /*
  19842. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  19843. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  19844. ** be freed by the calling function.
  19845. **
  19846. ** NULL is returned if there is an allocation error.
  19847. */
  19848. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  19849. Mem m;
  19850. memset(&m, 0, sizeof(m));
  19851. m.db = db;
  19852. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  19853. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  19854. if( db->mallocFailed ){
  19855. sqlite3VdbeMemRelease(&m);
  19856. m.z = 0;
  19857. }
  19858. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  19859. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  19860. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  19861. assert( m.z || db->mallocFailed );
  19862. return m.z;
  19863. }
  19864. /*
  19865. ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
  19866. ** enc. A pointer to the new string is returned, and the value of *pnOut
  19867. ** is set to the length of the returned string in bytes. The call should
  19868. ** arrange to call sqlite3DbFree() on the returned pointer when it is
  19869. ** no longer required.
  19870. **
  19871. ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
  19872. ** flag set.
  19873. */
  19874. #ifdef SQLITE_ENABLE_STAT3
  19875. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
  19876. Mem m;
  19877. memset(&m, 0, sizeof(m));
  19878. m.db = db;
  19879. sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
  19880. if( sqlite3VdbeMemTranslate(&m, enc) ){
  19881. assert( db->mallocFailed );
  19882. return 0;
  19883. }
  19884. assert( m.z==m.zMalloc );
  19885. *pnOut = m.n;
  19886. return m.z;
  19887. }
  19888. #endif
  19889. /*
  19890. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  19891. ** Return the number of bytes in the first nChar unicode characters
  19892. ** in pZ. nChar must be non-negative.
  19893. */
  19894. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  19895. int c;
  19896. unsigned char const *z = zIn;
  19897. int n = 0;
  19898. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  19899. while( n<nChar ){
  19900. READ_UTF16BE(z, 1, c);
  19901. n++;
  19902. }
  19903. }else{
  19904. while( n<nChar ){
  19905. READ_UTF16LE(z, 1, c);
  19906. n++;
  19907. }
  19908. }
  19909. return (int)(z-(unsigned char const *)zIn);
  19910. }
  19911. #if defined(SQLITE_TEST)
  19912. /*
  19913. ** This routine is called from the TCL test function "translate_selftest".
  19914. ** It checks that the primitives for serializing and deserializing
  19915. ** characters in each encoding are inverses of each other.
  19916. */
  19917. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  19918. unsigned int i, t;
  19919. unsigned char zBuf[20];
  19920. unsigned char *z;
  19921. int n;
  19922. unsigned int c;
  19923. for(i=0; i<0x00110000; i++){
  19924. z = zBuf;
  19925. WRITE_UTF8(z, i);
  19926. n = (int)(z-zBuf);
  19927. assert( n>0 && n<=4 );
  19928. z[0] = 0;
  19929. z = zBuf;
  19930. c = sqlite3Utf8Read((const u8**)&z);
  19931. t = i;
  19932. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  19933. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  19934. assert( c==t );
  19935. assert( (z-zBuf)==n );
  19936. }
  19937. for(i=0; i<0x00110000; i++){
  19938. if( i>=0xD800 && i<0xE000 ) continue;
  19939. z = zBuf;
  19940. WRITE_UTF16LE(z, i);
  19941. n = (int)(z-zBuf);
  19942. assert( n>0 && n<=4 );
  19943. z[0] = 0;
  19944. z = zBuf;
  19945. READ_UTF16LE(z, 1, c);
  19946. assert( c==i );
  19947. assert( (z-zBuf)==n );
  19948. }
  19949. for(i=0; i<0x00110000; i++){
  19950. if( i>=0xD800 && i<0xE000 ) continue;
  19951. z = zBuf;
  19952. WRITE_UTF16BE(z, i);
  19953. n = (int)(z-zBuf);
  19954. assert( n>0 && n<=4 );
  19955. z[0] = 0;
  19956. z = zBuf;
  19957. READ_UTF16BE(z, 1, c);
  19958. assert( c==i );
  19959. assert( (z-zBuf)==n );
  19960. }
  19961. }
  19962. #endif /* SQLITE_TEST */
  19963. #endif /* SQLITE_OMIT_UTF16 */
  19964. /************** End of utf.c *************************************************/
  19965. /************** Begin file util.c ********************************************/
  19966. /*
  19967. ** 2001 September 15
  19968. **
  19969. ** The author disclaims copyright to this source code. In place of
  19970. ** a legal notice, here is a blessing:
  19971. **
  19972. ** May you do good and not evil.
  19973. ** May you find forgiveness for yourself and forgive others.
  19974. ** May you share freely, never taking more than you give.
  19975. **
  19976. *************************************************************************
  19977. ** Utility functions used throughout sqlite.
  19978. **
  19979. ** This file contains functions for allocating memory, comparing
  19980. ** strings, and stuff like that.
  19981. **
  19982. */
  19983. /* #include <stdarg.h> */
  19984. #ifdef SQLITE_HAVE_ISNAN
  19985. # include <math.h>
  19986. #endif
  19987. /*
  19988. ** Routine needed to support the testcase() macro.
  19989. */
  19990. #ifdef SQLITE_COVERAGE_TEST
  19991. SQLITE_PRIVATE void sqlite3Coverage(int x){
  19992. static unsigned dummy = 0;
  19993. dummy += (unsigned)x;
  19994. }
  19995. #endif
  19996. #ifndef SQLITE_OMIT_FLOATING_POINT
  19997. /*
  19998. ** Return true if the floating point value is Not a Number (NaN).
  19999. **
  20000. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  20001. ** Otherwise, we have our own implementation that works on most systems.
  20002. */
  20003. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  20004. int rc; /* The value return */
  20005. #if !defined(SQLITE_HAVE_ISNAN)
  20006. /*
  20007. ** Systems that support the isnan() library function should probably
  20008. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  20009. ** found that many systems do not have a working isnan() function so
  20010. ** this implementation is provided as an alternative.
  20011. **
  20012. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  20013. ** On the other hand, the use of -ffast-math comes with the following
  20014. ** warning:
  20015. **
  20016. ** This option [-ffast-math] should never be turned on by any
  20017. ** -O option since it can result in incorrect output for programs
  20018. ** which depend on an exact implementation of IEEE or ISO
  20019. ** rules/specifications for math functions.
  20020. **
  20021. ** Under MSVC, this NaN test may fail if compiled with a floating-
  20022. ** point precision mode other than /fp:precise. From the MSDN
  20023. ** documentation:
  20024. **
  20025. ** The compiler [with /fp:precise] will properly handle comparisons
  20026. ** involving NaN. For example, x != x evaluates to true if x is NaN
  20027. ** ...
  20028. */
  20029. #ifdef __FAST_MATH__
  20030. # error SQLite will not work correctly with the -ffast-math option of GCC.
  20031. #endif
  20032. volatile double y = x;
  20033. volatile double z = y;
  20034. rc = (y!=z);
  20035. #else /* if defined(SQLITE_HAVE_ISNAN) */
  20036. rc = isnan(x);
  20037. #endif /* SQLITE_HAVE_ISNAN */
  20038. testcase( rc );
  20039. return rc;
  20040. }
  20041. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20042. /*
  20043. ** Compute a string length that is limited to what can be stored in
  20044. ** lower 30 bits of a 32-bit signed integer.
  20045. **
  20046. ** The value returned will never be negative. Nor will it ever be greater
  20047. ** than the actual length of the string. For very long strings (greater
  20048. ** than 1GiB) the value returned might be less than the true string length.
  20049. */
  20050. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  20051. const char *z2 = z;
  20052. if( z==0 ) return 0;
  20053. while( *z2 ){ z2++; }
  20054. return 0x3fffffff & (int)(z2 - z);
  20055. }
  20056. /*
  20057. ** Set the most recent error code and error string for the sqlite
  20058. ** handle "db". The error code is set to "err_code".
  20059. **
  20060. ** If it is not NULL, string zFormat specifies the format of the
  20061. ** error string in the style of the printf functions: The following
  20062. ** format characters are allowed:
  20063. **
  20064. ** %s Insert a string
  20065. ** %z A string that should be freed after use
  20066. ** %d Insert an integer
  20067. ** %T Insert a token
  20068. ** %S Insert the first element of a SrcList
  20069. **
  20070. ** zFormat and any string tokens that follow it are assumed to be
  20071. ** encoded in UTF-8.
  20072. **
  20073. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20074. ** should be called with err_code set to SQLITE_OK and zFormat set
  20075. ** to NULL.
  20076. */
  20077. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20078. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20079. db->errCode = err_code;
  20080. if( zFormat ){
  20081. char *z;
  20082. va_list ap;
  20083. va_start(ap, zFormat);
  20084. z = sqlite3VMPrintf(db, zFormat, ap);
  20085. va_end(ap);
  20086. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20087. }else{
  20088. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20089. }
  20090. }
  20091. }
  20092. /*
  20093. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20094. ** The following formatting characters are allowed:
  20095. **
  20096. ** %s Insert a string
  20097. ** %z A string that should be freed after use
  20098. ** %d Insert an integer
  20099. ** %T Insert a token
  20100. ** %S Insert the first element of a SrcList
  20101. **
  20102. ** This function should be used to report any error that occurs whilst
  20103. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20104. ** last thing the sqlite3_prepare() function does is copy the error
  20105. ** stored by this function into the database handle using sqlite3Error().
  20106. ** Function sqlite3Error() should be used during statement execution
  20107. ** (sqlite3_step() etc.).
  20108. */
  20109. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20110. char *zMsg;
  20111. va_list ap;
  20112. sqlite3 *db = pParse->db;
  20113. va_start(ap, zFormat);
  20114. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20115. va_end(ap);
  20116. if( db->suppressErr ){
  20117. sqlite3DbFree(db, zMsg);
  20118. }else{
  20119. pParse->nErr++;
  20120. sqlite3DbFree(db, pParse->zErrMsg);
  20121. pParse->zErrMsg = zMsg;
  20122. pParse->rc = SQLITE_ERROR;
  20123. }
  20124. }
  20125. /*
  20126. ** Convert an SQL-style quoted string into a normal string by removing
  20127. ** the quote characters. The conversion is done in-place. If the
  20128. ** input does not begin with a quote character, then this routine
  20129. ** is a no-op.
  20130. **
  20131. ** The input string must be zero-terminated. A new zero-terminator
  20132. ** is added to the dequoted string.
  20133. **
  20134. ** The return value is -1 if no dequoting occurs or the length of the
  20135. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20136. ** occur.
  20137. **
  20138. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20139. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20140. ** "a-b-c".
  20141. */
  20142. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20143. char quote;
  20144. int i, j;
  20145. if( z==0 ) return -1;
  20146. quote = z[0];
  20147. switch( quote ){
  20148. case '\'': break;
  20149. case '"': break;
  20150. case '`': break; /* For MySQL compatibility */
  20151. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20152. default: return -1;
  20153. }
  20154. for(i=1, j=0; ALWAYS(z[i]); i++){
  20155. if( z[i]==quote ){
  20156. if( z[i+1]==quote ){
  20157. z[j++] = quote;
  20158. i++;
  20159. }else{
  20160. break;
  20161. }
  20162. }else{
  20163. z[j++] = z[i];
  20164. }
  20165. }
  20166. z[j] = 0;
  20167. return j;
  20168. }
  20169. /* Convenient short-hand */
  20170. #define UpperToLower sqlite3UpperToLower
  20171. /*
  20172. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20173. ** there is no consistency, we will define our own.
  20174. **
  20175. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20176. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20177. ** the contents of two buffers containing UTF-8 strings in a
  20178. ** case-independent fashion, using the same definition of "case
  20179. ** independence" that SQLite uses internally when comparing identifiers.
  20180. */
  20181. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20182. register unsigned char *a, *b;
  20183. a = (unsigned char *)zLeft;
  20184. b = (unsigned char *)zRight;
  20185. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20186. return UpperToLower[*a] - UpperToLower[*b];
  20187. }
  20188. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20189. register unsigned char *a, *b;
  20190. a = (unsigned char *)zLeft;
  20191. b = (unsigned char *)zRight;
  20192. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20193. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20194. }
  20195. /*
  20196. ** The string z[] is an text representation of a real number.
  20197. ** Convert this string to a double and write it into *pResult.
  20198. **
  20199. ** The string z[] is length bytes in length (bytes, not characters) and
  20200. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20201. **
  20202. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20203. ** if the string is empty or contains extraneous text. Valid numbers
  20204. ** are in one of these formats:
  20205. **
  20206. ** [+-]digits[E[+-]digits]
  20207. ** [+-]digits.[digits][E[+-]digits]
  20208. ** [+-].digits[E[+-]digits]
  20209. **
  20210. ** Leading and trailing whitespace is ignored for the purpose of determining
  20211. ** validity.
  20212. **
  20213. ** If some prefix of the input string is a valid number, this routine
  20214. ** returns FALSE but it still converts the prefix and writes the result
  20215. ** into *pResult.
  20216. */
  20217. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20218. #ifndef SQLITE_OMIT_FLOATING_POINT
  20219. int incr = (enc==SQLITE_UTF8?1:2);
  20220. const char *zEnd = z + length;
  20221. /* sign * significand * (10 ^ (esign * exponent)) */
  20222. int sign = 1; /* sign of significand */
  20223. i64 s = 0; /* significand */
  20224. int d = 0; /* adjust exponent for shifting decimal point */
  20225. int esign = 1; /* sign of exponent */
  20226. int e = 0; /* exponent */
  20227. int eValid = 1; /* True exponent is either not used or is well-formed */
  20228. double result;
  20229. int nDigits = 0;
  20230. *pResult = 0.0; /* Default return value, in case of an error */
  20231. if( enc==SQLITE_UTF16BE ) z++;
  20232. /* skip leading spaces */
  20233. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20234. if( z>=zEnd ) return 0;
  20235. /* get sign of significand */
  20236. if( *z=='-' ){
  20237. sign = -1;
  20238. z+=incr;
  20239. }else if( *z=='+' ){
  20240. z+=incr;
  20241. }
  20242. /* skip leading zeroes */
  20243. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20244. /* copy max significant digits to significand */
  20245. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20246. s = s*10 + (*z - '0');
  20247. z+=incr, nDigits++;
  20248. }
  20249. /* skip non-significant significand digits
  20250. ** (increase exponent by d to shift decimal left) */
  20251. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20252. if( z>=zEnd ) goto do_atof_calc;
  20253. /* if decimal point is present */
  20254. if( *z=='.' ){
  20255. z+=incr;
  20256. /* copy digits from after decimal to significand
  20257. ** (decrease exponent by d to shift decimal right) */
  20258. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20259. s = s*10 + (*z - '0');
  20260. z+=incr, nDigits++, d--;
  20261. }
  20262. /* skip non-significant digits */
  20263. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20264. }
  20265. if( z>=zEnd ) goto do_atof_calc;
  20266. /* if exponent is present */
  20267. if( *z=='e' || *z=='E' ){
  20268. z+=incr;
  20269. eValid = 0;
  20270. if( z>=zEnd ) goto do_atof_calc;
  20271. /* get sign of exponent */
  20272. if( *z=='-' ){
  20273. esign = -1;
  20274. z+=incr;
  20275. }else if( *z=='+' ){
  20276. z+=incr;
  20277. }
  20278. /* copy digits to exponent */
  20279. while( z<zEnd && sqlite3Isdigit(*z) ){
  20280. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20281. z+=incr;
  20282. eValid = 1;
  20283. }
  20284. }
  20285. /* skip trailing spaces */
  20286. if( nDigits && eValid ){
  20287. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20288. }
  20289. do_atof_calc:
  20290. /* adjust exponent by d, and update sign */
  20291. e = (e*esign) + d;
  20292. if( e<0 ) {
  20293. esign = -1;
  20294. e *= -1;
  20295. } else {
  20296. esign = 1;
  20297. }
  20298. /* if 0 significand */
  20299. if( !s ) {
  20300. /* In the IEEE 754 standard, zero is signed.
  20301. ** Add the sign if we've seen at least one digit */
  20302. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20303. } else {
  20304. /* attempt to reduce exponent */
  20305. if( esign>0 ){
  20306. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20307. }else{
  20308. while( !(s%10) && e>0 ) e--,s/=10;
  20309. }
  20310. /* adjust the sign of significand */
  20311. s = sign<0 ? -s : s;
  20312. /* if exponent, scale significand as appropriate
  20313. ** and store in result. */
  20314. if( e ){
  20315. LONGDOUBLE_TYPE scale = 1.0;
  20316. /* attempt to handle extremely small/large numbers better */
  20317. if( e>307 && e<342 ){
  20318. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20319. if( esign<0 ){
  20320. result = s / scale;
  20321. result /= 1.0e+308;
  20322. }else{
  20323. result = s * scale;
  20324. result *= 1.0e+308;
  20325. }
  20326. }else if( e>=342 ){
  20327. if( esign<0 ){
  20328. result = 0.0*s;
  20329. }else{
  20330. result = 1e308*1e308*s; /* Infinity */
  20331. }
  20332. }else{
  20333. /* 1.0e+22 is the largest power of 10 than can be
  20334. ** represented exactly. */
  20335. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20336. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20337. if( esign<0 ){
  20338. result = s / scale;
  20339. }else{
  20340. result = s * scale;
  20341. }
  20342. }
  20343. } else {
  20344. result = (double)s;
  20345. }
  20346. }
  20347. /* store the result */
  20348. *pResult = result;
  20349. /* return true if number and no extra non-whitespace chracters after */
  20350. return z>=zEnd && nDigits>0 && eValid;
  20351. #else
  20352. return !sqlite3Atoi64(z, pResult, length, enc);
  20353. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20354. }
  20355. /*
  20356. ** Compare the 19-character string zNum against the text representation
  20357. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20358. ** if zNum is less than, equal to, or greater than the string.
  20359. ** Note that zNum must contain exactly 19 characters.
  20360. **
  20361. ** Unlike memcmp() this routine is guaranteed to return the difference
  20362. ** in the values of the last digit if the only difference is in the
  20363. ** last digit. So, for example,
  20364. **
  20365. ** compare2pow63("9223372036854775800", 1)
  20366. **
  20367. ** will return -8.
  20368. */
  20369. static int compare2pow63(const char *zNum, int incr){
  20370. int c = 0;
  20371. int i;
  20372. /* 012345678901234567 */
  20373. const char *pow63 = "922337203685477580";
  20374. for(i=0; c==0 && i<18; i++){
  20375. c = (zNum[i*incr]-pow63[i])*10;
  20376. }
  20377. if( c==0 ){
  20378. c = zNum[18*incr] - '8';
  20379. testcase( c==(-1) );
  20380. testcase( c==0 );
  20381. testcase( c==(+1) );
  20382. }
  20383. return c;
  20384. }
  20385. /*
  20386. ** Convert zNum to a 64-bit signed integer.
  20387. **
  20388. ** If the zNum value is representable as a 64-bit twos-complement
  20389. ** integer, then write that value into *pNum and return 0.
  20390. **
  20391. ** If zNum is exactly 9223372036854665808, return 2. This special
  20392. ** case is broken out because while 9223372036854665808 cannot be a
  20393. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20394. **
  20395. ** If zNum is too big for a 64-bit integer and is not
  20396. ** 9223372036854665808 then return 1.
  20397. **
  20398. ** length is the number of bytes in the string (bytes, not characters).
  20399. ** The string is not necessarily zero-terminated. The encoding is
  20400. ** given by enc.
  20401. */
  20402. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20403. int incr = (enc==SQLITE_UTF8?1:2);
  20404. u64 u = 0;
  20405. int neg = 0; /* assume positive */
  20406. int i;
  20407. int c = 0;
  20408. const char *zStart;
  20409. const char *zEnd = zNum + length;
  20410. if( enc==SQLITE_UTF16BE ) zNum++;
  20411. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20412. if( zNum<zEnd ){
  20413. if( *zNum=='-' ){
  20414. neg = 1;
  20415. zNum+=incr;
  20416. }else if( *zNum=='+' ){
  20417. zNum+=incr;
  20418. }
  20419. }
  20420. zStart = zNum;
  20421. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20422. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20423. u = u*10 + c - '0';
  20424. }
  20425. if( u>LARGEST_INT64 ){
  20426. *pNum = SMALLEST_INT64;
  20427. }else if( neg ){
  20428. *pNum = -(i64)u;
  20429. }else{
  20430. *pNum = (i64)u;
  20431. }
  20432. testcase( i==18 );
  20433. testcase( i==19 );
  20434. testcase( i==20 );
  20435. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
  20436. /* zNum is empty or contains non-numeric text or is longer
  20437. ** than 19 digits (thus guaranteeing that it is too large) */
  20438. return 1;
  20439. }else if( i<19*incr ){
  20440. /* Less than 19 digits, so we know that it fits in 64 bits */
  20441. assert( u<=LARGEST_INT64 );
  20442. return 0;
  20443. }else{
  20444. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20445. c = compare2pow63(zNum, incr);
  20446. if( c<0 ){
  20447. /* zNum is less than 9223372036854775808 so it fits */
  20448. assert( u<=LARGEST_INT64 );
  20449. return 0;
  20450. }else if( c>0 ){
  20451. /* zNum is greater than 9223372036854775808 so it overflows */
  20452. return 1;
  20453. }else{
  20454. /* zNum is exactly 9223372036854775808. Fits if negative. The
  20455. ** special case 2 overflow if positive */
  20456. assert( u-1==LARGEST_INT64 );
  20457. assert( (*pNum)==SMALLEST_INT64 );
  20458. return neg ? 0 : 2;
  20459. }
  20460. }
  20461. }
  20462. /*
  20463. ** If zNum represents an integer that will fit in 32-bits, then set
  20464. ** *pValue to that integer and return true. Otherwise return false.
  20465. **
  20466. ** Any non-numeric characters that following zNum are ignored.
  20467. ** This is different from sqlite3Atoi64() which requires the
  20468. ** input number to be zero-terminated.
  20469. */
  20470. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  20471. sqlite_int64 v = 0;
  20472. int i, c;
  20473. int neg = 0;
  20474. if( zNum[0]=='-' ){
  20475. neg = 1;
  20476. zNum++;
  20477. }else if( zNum[0]=='+' ){
  20478. zNum++;
  20479. }
  20480. while( zNum[0]=='0' ) zNum++;
  20481. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  20482. v = v*10 + c;
  20483. }
  20484. /* The longest decimal representation of a 32 bit integer is 10 digits:
  20485. **
  20486. ** 1234567890
  20487. ** 2^31 -> 2147483648
  20488. */
  20489. testcase( i==10 );
  20490. if( i>10 ){
  20491. return 0;
  20492. }
  20493. testcase( v-neg==2147483647 );
  20494. if( v-neg>2147483647 ){
  20495. return 0;
  20496. }
  20497. if( neg ){
  20498. v = -v;
  20499. }
  20500. *pValue = (int)v;
  20501. return 1;
  20502. }
  20503. /*
  20504. ** Return a 32-bit integer value extracted from a string. If the
  20505. ** string is not an integer, just return 0.
  20506. */
  20507. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  20508. int x = 0;
  20509. if( z ) sqlite3GetInt32(z, &x);
  20510. return x;
  20511. }
  20512. /*
  20513. ** The variable-length integer encoding is as follows:
  20514. **
  20515. ** KEY:
  20516. ** A = 0xxxxxxx 7 bits of data and one flag bit
  20517. ** B = 1xxxxxxx 7 bits of data and one flag bit
  20518. ** C = xxxxxxxx 8 bits of data
  20519. **
  20520. ** 7 bits - A
  20521. ** 14 bits - BA
  20522. ** 21 bits - BBA
  20523. ** 28 bits - BBBA
  20524. ** 35 bits - BBBBA
  20525. ** 42 bits - BBBBBA
  20526. ** 49 bits - BBBBBBA
  20527. ** 56 bits - BBBBBBBA
  20528. ** 64 bits - BBBBBBBBC
  20529. */
  20530. /*
  20531. ** Write a 64-bit variable-length integer to memory starting at p[0].
  20532. ** The length of data write will be between 1 and 9 bytes. The number
  20533. ** of bytes written is returned.
  20534. **
  20535. ** A variable-length integer consists of the lower 7 bits of each byte
  20536. ** for all bytes that have the 8th bit set and one byte with the 8th
  20537. ** bit clear. Except, if we get to the 9th byte, it stores the full
  20538. ** 8 bits and is the last byte.
  20539. */
  20540. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  20541. int i, j, n;
  20542. u8 buf[10];
  20543. if( v & (((u64)0xff000000)<<32) ){
  20544. p[8] = (u8)v;
  20545. v >>= 8;
  20546. for(i=7; i>=0; i--){
  20547. p[i] = (u8)((v & 0x7f) | 0x80);
  20548. v >>= 7;
  20549. }
  20550. return 9;
  20551. }
  20552. n = 0;
  20553. do{
  20554. buf[n++] = (u8)((v & 0x7f) | 0x80);
  20555. v >>= 7;
  20556. }while( v!=0 );
  20557. buf[0] &= 0x7f;
  20558. assert( n<=9 );
  20559. for(i=0, j=n-1; j>=0; j--, i++){
  20560. p[i] = buf[j];
  20561. }
  20562. return n;
  20563. }
  20564. /*
  20565. ** This routine is a faster version of sqlite3PutVarint() that only
  20566. ** works for 32-bit positive integers and which is optimized for
  20567. ** the common case of small integers. A MACRO version, putVarint32,
  20568. ** is provided which inlines the single-byte case. All code should use
  20569. ** the MACRO version as this function assumes the single-byte case has
  20570. ** already been handled.
  20571. */
  20572. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  20573. #ifndef putVarint32
  20574. if( (v & ~0x7f)==0 ){
  20575. p[0] = v;
  20576. return 1;
  20577. }
  20578. #endif
  20579. if( (v & ~0x3fff)==0 ){
  20580. p[0] = (u8)((v>>7) | 0x80);
  20581. p[1] = (u8)(v & 0x7f);
  20582. return 2;
  20583. }
  20584. return sqlite3PutVarint(p, v);
  20585. }
  20586. /*
  20587. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  20588. ** are defined here rather than simply putting the constant expressions
  20589. ** inline in order to work around bugs in the RVT compiler.
  20590. **
  20591. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  20592. **
  20593. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  20594. */
  20595. #define SLOT_2_0 0x001fc07f
  20596. #define SLOT_4_2_0 0xf01fc07f
  20597. /*
  20598. ** Read a 64-bit variable-length integer from memory starting at p[0].
  20599. ** Return the number of bytes read. The value is stored in *v.
  20600. */
  20601. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  20602. u32 a,b,s;
  20603. a = *p;
  20604. /* a: p0 (unmasked) */
  20605. if (!(a&0x80))
  20606. {
  20607. *v = a;
  20608. return 1;
  20609. }
  20610. p++;
  20611. b = *p;
  20612. /* b: p1 (unmasked) */
  20613. if (!(b&0x80))
  20614. {
  20615. a &= 0x7f;
  20616. a = a<<7;
  20617. a |= b;
  20618. *v = a;
  20619. return 2;
  20620. }
  20621. /* Verify that constants are precomputed correctly */
  20622. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  20623. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  20624. p++;
  20625. a = a<<14;
  20626. a |= *p;
  20627. /* a: p0<<14 | p2 (unmasked) */
  20628. if (!(a&0x80))
  20629. {
  20630. a &= SLOT_2_0;
  20631. b &= 0x7f;
  20632. b = b<<7;
  20633. a |= b;
  20634. *v = a;
  20635. return 3;
  20636. }
  20637. /* CSE1 from below */
  20638. a &= SLOT_2_0;
  20639. p++;
  20640. b = b<<14;
  20641. b |= *p;
  20642. /* b: p1<<14 | p3 (unmasked) */
  20643. if (!(b&0x80))
  20644. {
  20645. b &= SLOT_2_0;
  20646. /* moved CSE1 up */
  20647. /* a &= (0x7f<<14)|(0x7f); */
  20648. a = a<<7;
  20649. a |= b;
  20650. *v = a;
  20651. return 4;
  20652. }
  20653. /* a: p0<<14 | p2 (masked) */
  20654. /* b: p1<<14 | p3 (unmasked) */
  20655. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20656. /* moved CSE1 up */
  20657. /* a &= (0x7f<<14)|(0x7f); */
  20658. b &= SLOT_2_0;
  20659. s = a;
  20660. /* s: p0<<14 | p2 (masked) */
  20661. p++;
  20662. a = a<<14;
  20663. a |= *p;
  20664. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20665. if (!(a&0x80))
  20666. {
  20667. /* we can skip these cause they were (effectively) done above in calc'ing s */
  20668. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20669. /* b &= (0x7f<<14)|(0x7f); */
  20670. b = b<<7;
  20671. a |= b;
  20672. s = s>>18;
  20673. *v = ((u64)s)<<32 | a;
  20674. return 5;
  20675. }
  20676. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20677. s = s<<7;
  20678. s |= b;
  20679. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20680. p++;
  20681. b = b<<14;
  20682. b |= *p;
  20683. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  20684. if (!(b&0x80))
  20685. {
  20686. /* we can skip this cause it was (effectively) done above in calc'ing s */
  20687. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20688. a &= SLOT_2_0;
  20689. a = a<<7;
  20690. a |= b;
  20691. s = s>>18;
  20692. *v = ((u64)s)<<32 | a;
  20693. return 6;
  20694. }
  20695. p++;
  20696. a = a<<14;
  20697. a |= *p;
  20698. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  20699. if (!(a&0x80))
  20700. {
  20701. a &= SLOT_4_2_0;
  20702. b &= SLOT_2_0;
  20703. b = b<<7;
  20704. a |= b;
  20705. s = s>>11;
  20706. *v = ((u64)s)<<32 | a;
  20707. return 7;
  20708. }
  20709. /* CSE2 from below */
  20710. a &= SLOT_2_0;
  20711. p++;
  20712. b = b<<14;
  20713. b |= *p;
  20714. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  20715. if (!(b&0x80))
  20716. {
  20717. b &= SLOT_4_2_0;
  20718. /* moved CSE2 up */
  20719. /* a &= (0x7f<<14)|(0x7f); */
  20720. a = a<<7;
  20721. a |= b;
  20722. s = s>>4;
  20723. *v = ((u64)s)<<32 | a;
  20724. return 8;
  20725. }
  20726. p++;
  20727. a = a<<15;
  20728. a |= *p;
  20729. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  20730. /* moved CSE2 up */
  20731. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  20732. b &= SLOT_2_0;
  20733. b = b<<8;
  20734. a |= b;
  20735. s = s<<4;
  20736. b = p[-4];
  20737. b &= 0x7f;
  20738. b = b>>3;
  20739. s |= b;
  20740. *v = ((u64)s)<<32 | a;
  20741. return 9;
  20742. }
  20743. /*
  20744. ** Read a 32-bit variable-length integer from memory starting at p[0].
  20745. ** Return the number of bytes read. The value is stored in *v.
  20746. **
  20747. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  20748. ** integer, then set *v to 0xffffffff.
  20749. **
  20750. ** A MACRO version, getVarint32, is provided which inlines the
  20751. ** single-byte case. All code should use the MACRO version as
  20752. ** this function assumes the single-byte case has already been handled.
  20753. */
  20754. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  20755. u32 a,b;
  20756. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  20757. ** by the getVarin32() macro */
  20758. a = *p;
  20759. /* a: p0 (unmasked) */
  20760. #ifndef getVarint32
  20761. if (!(a&0x80))
  20762. {
  20763. /* Values between 0 and 127 */
  20764. *v = a;
  20765. return 1;
  20766. }
  20767. #endif
  20768. /* The 2-byte case */
  20769. p++;
  20770. b = *p;
  20771. /* b: p1 (unmasked) */
  20772. if (!(b&0x80))
  20773. {
  20774. /* Values between 128 and 16383 */
  20775. a &= 0x7f;
  20776. a = a<<7;
  20777. *v = a | b;
  20778. return 2;
  20779. }
  20780. /* The 3-byte case */
  20781. p++;
  20782. a = a<<14;
  20783. a |= *p;
  20784. /* a: p0<<14 | p2 (unmasked) */
  20785. if (!(a&0x80))
  20786. {
  20787. /* Values between 16384 and 2097151 */
  20788. a &= (0x7f<<14)|(0x7f);
  20789. b &= 0x7f;
  20790. b = b<<7;
  20791. *v = a | b;
  20792. return 3;
  20793. }
  20794. /* A 32-bit varint is used to store size information in btrees.
  20795. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  20796. ** A 3-byte varint is sufficient, for example, to record the size
  20797. ** of a 1048569-byte BLOB or string.
  20798. **
  20799. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  20800. ** rare larger cases can be handled by the slower 64-bit varint
  20801. ** routine.
  20802. */
  20803. #if 1
  20804. {
  20805. u64 v64;
  20806. u8 n;
  20807. p -= 2;
  20808. n = sqlite3GetVarint(p, &v64);
  20809. assert( n>3 && n<=9 );
  20810. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  20811. *v = 0xffffffff;
  20812. }else{
  20813. *v = (u32)v64;
  20814. }
  20815. return n;
  20816. }
  20817. #else
  20818. /* For following code (kept for historical record only) shows an
  20819. ** unrolling for the 3- and 4-byte varint cases. This code is
  20820. ** slightly faster, but it is also larger and much harder to test.
  20821. */
  20822. p++;
  20823. b = b<<14;
  20824. b |= *p;
  20825. /* b: p1<<14 | p3 (unmasked) */
  20826. if (!(b&0x80))
  20827. {
  20828. /* Values between 2097152 and 268435455 */
  20829. b &= (0x7f<<14)|(0x7f);
  20830. a &= (0x7f<<14)|(0x7f);
  20831. a = a<<7;
  20832. *v = a | b;
  20833. return 4;
  20834. }
  20835. p++;
  20836. a = a<<14;
  20837. a |= *p;
  20838. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20839. if (!(a&0x80))
  20840. {
  20841. /* Values between 268435456 and 34359738367 */
  20842. a &= SLOT_4_2_0;
  20843. b &= SLOT_4_2_0;
  20844. b = b<<7;
  20845. *v = a | b;
  20846. return 5;
  20847. }
  20848. /* We can only reach this point when reading a corrupt database
  20849. ** file. In that case we are not in any hurry. Use the (relatively
  20850. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  20851. ** value. */
  20852. {
  20853. u64 v64;
  20854. u8 n;
  20855. p -= 4;
  20856. n = sqlite3GetVarint(p, &v64);
  20857. assert( n>5 && n<=9 );
  20858. *v = (u32)v64;
  20859. return n;
  20860. }
  20861. #endif
  20862. }
  20863. /*
  20864. ** Return the number of bytes that will be needed to store the given
  20865. ** 64-bit integer.
  20866. */
  20867. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  20868. int i = 0;
  20869. do{
  20870. i++;
  20871. v >>= 7;
  20872. }while( v!=0 && ALWAYS(i<9) );
  20873. return i;
  20874. }
  20875. /*
  20876. ** Read or write a four-byte big-endian integer value.
  20877. */
  20878. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  20879. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  20880. }
  20881. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  20882. p[0] = (u8)(v>>24);
  20883. p[1] = (u8)(v>>16);
  20884. p[2] = (u8)(v>>8);
  20885. p[3] = (u8)v;
  20886. }
  20887. /*
  20888. ** Translate a single byte of Hex into an integer.
  20889. ** This routine only works if h really is a valid hexadecimal
  20890. ** character: 0..9a..fA..F
  20891. */
  20892. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  20893. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  20894. #ifdef SQLITE_ASCII
  20895. h += 9*(1&(h>>6));
  20896. #endif
  20897. #ifdef SQLITE_EBCDIC
  20898. h += 9*(1&~(h>>4));
  20899. #endif
  20900. return (u8)(h & 0xf);
  20901. }
  20902. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  20903. /*
  20904. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  20905. ** value. Return a pointer to its binary value. Space to hold the
  20906. ** binary value has been obtained from malloc and must be freed by
  20907. ** the calling routine.
  20908. */
  20909. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  20910. char *zBlob;
  20911. int i;
  20912. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  20913. n--;
  20914. if( zBlob ){
  20915. for(i=0; i<n; i+=2){
  20916. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  20917. }
  20918. zBlob[i/2] = 0;
  20919. }
  20920. return zBlob;
  20921. }
  20922. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  20923. /*
  20924. ** Log an error that is an API call on a connection pointer that should
  20925. ** not have been used. The "type" of connection pointer is given as the
  20926. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  20927. */
  20928. static void logBadConnection(const char *zType){
  20929. sqlite3_log(SQLITE_MISUSE,
  20930. "API call with %s database connection pointer",
  20931. zType
  20932. );
  20933. }
  20934. /*
  20935. ** Check to make sure we have a valid db pointer. This test is not
  20936. ** foolproof but it does provide some measure of protection against
  20937. ** misuse of the interface such as passing in db pointers that are
  20938. ** NULL or which have been previously closed. If this routine returns
  20939. ** 1 it means that the db pointer is valid and 0 if it should not be
  20940. ** dereferenced for any reason. The calling function should invoke
  20941. ** SQLITE_MISUSE immediately.
  20942. **
  20943. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  20944. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  20945. ** open properly and is not fit for general use but which can be
  20946. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  20947. */
  20948. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  20949. u32 magic;
  20950. if( db==0 ){
  20951. logBadConnection("NULL");
  20952. return 0;
  20953. }
  20954. magic = db->magic;
  20955. if( magic!=SQLITE_MAGIC_OPEN ){
  20956. if( sqlite3SafetyCheckSickOrOk(db) ){
  20957. testcase( sqlite3GlobalConfig.xLog!=0 );
  20958. logBadConnection("unopened");
  20959. }
  20960. return 0;
  20961. }else{
  20962. return 1;
  20963. }
  20964. }
  20965. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  20966. u32 magic;
  20967. magic = db->magic;
  20968. if( magic!=SQLITE_MAGIC_SICK &&
  20969. magic!=SQLITE_MAGIC_OPEN &&
  20970. magic!=SQLITE_MAGIC_BUSY ){
  20971. testcase( sqlite3GlobalConfig.xLog!=0 );
  20972. logBadConnection("invalid");
  20973. return 0;
  20974. }else{
  20975. return 1;
  20976. }
  20977. }
  20978. /*
  20979. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  20980. ** the other 64-bit signed integer at *pA and store the result in *pA.
  20981. ** Return 0 on success. Or if the operation would have resulted in an
  20982. ** overflow, leave *pA unchanged and return 1.
  20983. */
  20984. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  20985. i64 iA = *pA;
  20986. testcase( iA==0 ); testcase( iA==1 );
  20987. testcase( iB==-1 ); testcase( iB==0 );
  20988. if( iB>=0 ){
  20989. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  20990. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  20991. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  20992. *pA += iB;
  20993. }else{
  20994. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  20995. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  20996. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  20997. *pA += iB;
  20998. }
  20999. return 0;
  21000. }
  21001. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  21002. testcase( iB==SMALLEST_INT64+1 );
  21003. if( iB==SMALLEST_INT64 ){
  21004. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  21005. if( (*pA)>=0 ) return 1;
  21006. *pA -= iB;
  21007. return 0;
  21008. }else{
  21009. return sqlite3AddInt64(pA, -iB);
  21010. }
  21011. }
  21012. #define TWOPOWER32 (((i64)1)<<32)
  21013. #define TWOPOWER31 (((i64)1)<<31)
  21014. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  21015. i64 iA = *pA;
  21016. i64 iA1, iA0, iB1, iB0, r;
  21017. iA1 = iA/TWOPOWER32;
  21018. iA0 = iA % TWOPOWER32;
  21019. iB1 = iB/TWOPOWER32;
  21020. iB0 = iB % TWOPOWER32;
  21021. if( iA1*iB1 != 0 ) return 1;
  21022. assert( iA1*iB0==0 || iA0*iB1==0 );
  21023. r = iA1*iB0 + iA0*iB1;
  21024. testcase( r==(-TWOPOWER31)-1 );
  21025. testcase( r==(-TWOPOWER31) );
  21026. testcase( r==TWOPOWER31 );
  21027. testcase( r==TWOPOWER31-1 );
  21028. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  21029. r *= TWOPOWER32;
  21030. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  21031. *pA = r;
  21032. return 0;
  21033. }
  21034. /*
  21035. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  21036. ** if the integer has a value of -2147483648, return +2147483647
  21037. */
  21038. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  21039. if( x>=0 ) return x;
  21040. if( x==(int)0x80000000 ) return 0x7fffffff;
  21041. return -x;
  21042. }
  21043. #ifdef SQLITE_ENABLE_8_3_NAMES
  21044. /*
  21045. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  21046. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  21047. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  21048. ** three characters, then shorten the suffix on z[] to be the last three
  21049. ** characters of the original suffix.
  21050. **
  21051. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  21052. ** do the suffix shortening regardless of URI parameter.
  21053. **
  21054. ** Examples:
  21055. **
  21056. ** test.db-journal => test.nal
  21057. ** test.db-wal => test.wal
  21058. ** test.db-shm => test.shm
  21059. ** test.db-mj7f3319fa => test.9fa
  21060. */
  21061. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21062. #if SQLITE_ENABLE_8_3_NAMES<2
  21063. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21064. #endif
  21065. {
  21066. int i, sz;
  21067. sz = sqlite3Strlen30(z);
  21068. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21069. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21070. }
  21071. }
  21072. #endif
  21073. /************** End of util.c ************************************************/
  21074. /************** Begin file hash.c ********************************************/
  21075. /*
  21076. ** 2001 September 22
  21077. **
  21078. ** The author disclaims copyright to this source code. In place of
  21079. ** a legal notice, here is a blessing:
  21080. **
  21081. ** May you do good and not evil.
  21082. ** May you find forgiveness for yourself and forgive others.
  21083. ** May you share freely, never taking more than you give.
  21084. **
  21085. *************************************************************************
  21086. ** This is the implementation of generic hash-tables
  21087. ** used in SQLite.
  21088. */
  21089. /* #include <assert.h> */
  21090. /* Turn bulk memory into a hash table object by initializing the
  21091. ** fields of the Hash structure.
  21092. **
  21093. ** "pNew" is a pointer to the hash table that is to be initialized.
  21094. */
  21095. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21096. assert( pNew!=0 );
  21097. pNew->first = 0;
  21098. pNew->count = 0;
  21099. pNew->htsize = 0;
  21100. pNew->ht = 0;
  21101. }
  21102. /* Remove all entries from a hash table. Reclaim all memory.
  21103. ** Call this routine to delete a hash table or to reset a hash table
  21104. ** to the empty state.
  21105. */
  21106. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21107. HashElem *elem; /* For looping over all elements of the table */
  21108. assert( pH!=0 );
  21109. elem = pH->first;
  21110. pH->first = 0;
  21111. sqlite3_free(pH->ht);
  21112. pH->ht = 0;
  21113. pH->htsize = 0;
  21114. while( elem ){
  21115. HashElem *next_elem = elem->next;
  21116. sqlite3_free(elem);
  21117. elem = next_elem;
  21118. }
  21119. pH->count = 0;
  21120. }
  21121. /*
  21122. ** The hashing function.
  21123. */
  21124. static unsigned int strHash(const char *z, int nKey){
  21125. int h = 0;
  21126. assert( nKey>=0 );
  21127. while( nKey > 0 ){
  21128. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21129. nKey--;
  21130. }
  21131. return h;
  21132. }
  21133. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21134. ** insert pNew into the pEntry hash bucket.
  21135. */
  21136. static void insertElement(
  21137. Hash *pH, /* The complete hash table */
  21138. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21139. HashElem *pNew /* The element to be inserted */
  21140. ){
  21141. HashElem *pHead; /* First element already in pEntry */
  21142. if( pEntry ){
  21143. pHead = pEntry->count ? pEntry->chain : 0;
  21144. pEntry->count++;
  21145. pEntry->chain = pNew;
  21146. }else{
  21147. pHead = 0;
  21148. }
  21149. if( pHead ){
  21150. pNew->next = pHead;
  21151. pNew->prev = pHead->prev;
  21152. if( pHead->prev ){ pHead->prev->next = pNew; }
  21153. else { pH->first = pNew; }
  21154. pHead->prev = pNew;
  21155. }else{
  21156. pNew->next = pH->first;
  21157. if( pH->first ){ pH->first->prev = pNew; }
  21158. pNew->prev = 0;
  21159. pH->first = pNew;
  21160. }
  21161. }
  21162. /* Resize the hash table so that it cantains "new_size" buckets.
  21163. **
  21164. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21165. ** if the new size is the same as the prior size.
  21166. ** Return TRUE if the resize occurs and false if not.
  21167. */
  21168. static int rehash(Hash *pH, unsigned int new_size){
  21169. struct _ht *new_ht; /* The new hash table */
  21170. HashElem *elem, *next_elem; /* For looping over existing elements */
  21171. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21172. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21173. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21174. }
  21175. if( new_size==pH->htsize ) return 0;
  21176. #endif
  21177. /* The inability to allocates space for a larger hash table is
  21178. ** a performance hit but it is not a fatal error. So mark the
  21179. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21180. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21181. ** only zeroes the requested number of bytes whereas this module will
  21182. ** use the actual amount of space allocated for the hash table (which
  21183. ** may be larger than the requested amount).
  21184. */
  21185. sqlite3BeginBenignMalloc();
  21186. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21187. sqlite3EndBenignMalloc();
  21188. if( new_ht==0 ) return 0;
  21189. sqlite3_free(pH->ht);
  21190. pH->ht = new_ht;
  21191. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21192. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21193. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21194. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21195. next_elem = elem->next;
  21196. insertElement(pH, &new_ht[h], elem);
  21197. }
  21198. return 1;
  21199. }
  21200. /* This function (for internal use only) locates an element in an
  21201. ** hash table that matches the given key. The hash for this key has
  21202. ** already been computed and is passed as the 4th parameter.
  21203. */
  21204. static HashElem *findElementGivenHash(
  21205. const Hash *pH, /* The pH to be searched */
  21206. const char *pKey, /* The key we are searching for */
  21207. int nKey, /* Bytes in key (not counting zero terminator) */
  21208. unsigned int h /* The hash for this key. */
  21209. ){
  21210. HashElem *elem; /* Used to loop thru the element list */
  21211. int count; /* Number of elements left to test */
  21212. if( pH->ht ){
  21213. struct _ht *pEntry = &pH->ht[h];
  21214. elem = pEntry->chain;
  21215. count = pEntry->count;
  21216. }else{
  21217. elem = pH->first;
  21218. count = pH->count;
  21219. }
  21220. while( count-- && ALWAYS(elem) ){
  21221. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21222. return elem;
  21223. }
  21224. elem = elem->next;
  21225. }
  21226. return 0;
  21227. }
  21228. /* Remove a single entry from the hash table given a pointer to that
  21229. ** element and a hash on the element's key.
  21230. */
  21231. static void removeElementGivenHash(
  21232. Hash *pH, /* The pH containing "elem" */
  21233. HashElem* elem, /* The element to be removed from the pH */
  21234. unsigned int h /* Hash value for the element */
  21235. ){
  21236. struct _ht *pEntry;
  21237. if( elem->prev ){
  21238. elem->prev->next = elem->next;
  21239. }else{
  21240. pH->first = elem->next;
  21241. }
  21242. if( elem->next ){
  21243. elem->next->prev = elem->prev;
  21244. }
  21245. if( pH->ht ){
  21246. pEntry = &pH->ht[h];
  21247. if( pEntry->chain==elem ){
  21248. pEntry->chain = elem->next;
  21249. }
  21250. pEntry->count--;
  21251. assert( pEntry->count>=0 );
  21252. }
  21253. sqlite3_free( elem );
  21254. pH->count--;
  21255. if( pH->count==0 ){
  21256. assert( pH->first==0 );
  21257. assert( pH->count==0 );
  21258. sqlite3HashClear(pH);
  21259. }
  21260. }
  21261. /* Attempt to locate an element of the hash table pH with a key
  21262. ** that matches pKey,nKey. Return the data for this element if it is
  21263. ** found, or NULL if there is no match.
  21264. */
  21265. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21266. HashElem *elem; /* The element that matches key */
  21267. unsigned int h; /* A hash on key */
  21268. assert( pH!=0 );
  21269. assert( pKey!=0 );
  21270. assert( nKey>=0 );
  21271. if( pH->ht ){
  21272. h = strHash(pKey, nKey) % pH->htsize;
  21273. }else{
  21274. h = 0;
  21275. }
  21276. elem = findElementGivenHash(pH, pKey, nKey, h);
  21277. return elem ? elem->data : 0;
  21278. }
  21279. /* Insert an element into the hash table pH. The key is pKey,nKey
  21280. ** and the data is "data".
  21281. **
  21282. ** If no element exists with a matching key, then a new
  21283. ** element is created and NULL is returned.
  21284. **
  21285. ** If another element already exists with the same key, then the
  21286. ** new data replaces the old data and the old data is returned.
  21287. ** The key is not copied in this instance. If a malloc fails, then
  21288. ** the new data is returned and the hash table is unchanged.
  21289. **
  21290. ** If the "data" parameter to this function is NULL, then the
  21291. ** element corresponding to "key" is removed from the hash table.
  21292. */
  21293. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21294. unsigned int h; /* the hash of the key modulo hash table size */
  21295. HashElem *elem; /* Used to loop thru the element list */
  21296. HashElem *new_elem; /* New element added to the pH */
  21297. assert( pH!=0 );
  21298. assert( pKey!=0 );
  21299. assert( nKey>=0 );
  21300. if( pH->htsize ){
  21301. h = strHash(pKey, nKey) % pH->htsize;
  21302. }else{
  21303. h = 0;
  21304. }
  21305. elem = findElementGivenHash(pH,pKey,nKey,h);
  21306. if( elem ){
  21307. void *old_data = elem->data;
  21308. if( data==0 ){
  21309. removeElementGivenHash(pH,elem,h);
  21310. }else{
  21311. elem->data = data;
  21312. elem->pKey = pKey;
  21313. assert(nKey==elem->nKey);
  21314. }
  21315. return old_data;
  21316. }
  21317. if( data==0 ) return 0;
  21318. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21319. if( new_elem==0 ) return data;
  21320. new_elem->pKey = pKey;
  21321. new_elem->nKey = nKey;
  21322. new_elem->data = data;
  21323. pH->count++;
  21324. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21325. if( rehash(pH, pH->count*2) ){
  21326. assert( pH->htsize>0 );
  21327. h = strHash(pKey, nKey) % pH->htsize;
  21328. }
  21329. }
  21330. if( pH->ht ){
  21331. insertElement(pH, &pH->ht[h], new_elem);
  21332. }else{
  21333. insertElement(pH, 0, new_elem);
  21334. }
  21335. return 0;
  21336. }
  21337. /************** End of hash.c ************************************************/
  21338. /************** Begin file opcodes.c *****************************************/
  21339. /* Automatically generated. Do not edit */
  21340. /* See the mkopcodec.awk script for details. */
  21341. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21342. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21343. static const char *const azName[] = { "?",
  21344. /* 1 */ "Goto",
  21345. /* 2 */ "Gosub",
  21346. /* 3 */ "Return",
  21347. /* 4 */ "Yield",
  21348. /* 5 */ "HaltIfNull",
  21349. /* 6 */ "Halt",
  21350. /* 7 */ "Integer",
  21351. /* 8 */ "Int64",
  21352. /* 9 */ "String",
  21353. /* 10 */ "Null",
  21354. /* 11 */ "Blob",
  21355. /* 12 */ "Variable",
  21356. /* 13 */ "Move",
  21357. /* 14 */ "Copy",
  21358. /* 15 */ "SCopy",
  21359. /* 16 */ "ResultRow",
  21360. /* 17 */ "CollSeq",
  21361. /* 18 */ "Function",
  21362. /* 19 */ "Not",
  21363. /* 20 */ "AddImm",
  21364. /* 21 */ "MustBeInt",
  21365. /* 22 */ "RealAffinity",
  21366. /* 23 */ "Permutation",
  21367. /* 24 */ "Compare",
  21368. /* 25 */ "Jump",
  21369. /* 26 */ "Once",
  21370. /* 27 */ "If",
  21371. /* 28 */ "IfNot",
  21372. /* 29 */ "Column",
  21373. /* 30 */ "Affinity",
  21374. /* 31 */ "MakeRecord",
  21375. /* 32 */ "Count",
  21376. /* 33 */ "Savepoint",
  21377. /* 34 */ "AutoCommit",
  21378. /* 35 */ "Transaction",
  21379. /* 36 */ "ReadCookie",
  21380. /* 37 */ "SetCookie",
  21381. /* 38 */ "VerifyCookie",
  21382. /* 39 */ "OpenRead",
  21383. /* 40 */ "OpenWrite",
  21384. /* 41 */ "OpenAutoindex",
  21385. /* 42 */ "OpenEphemeral",
  21386. /* 43 */ "SorterOpen",
  21387. /* 44 */ "OpenPseudo",
  21388. /* 45 */ "Close",
  21389. /* 46 */ "SeekLt",
  21390. /* 47 */ "SeekLe",
  21391. /* 48 */ "SeekGe",
  21392. /* 49 */ "SeekGt",
  21393. /* 50 */ "Seek",
  21394. /* 51 */ "NotFound",
  21395. /* 52 */ "Found",
  21396. /* 53 */ "IsUnique",
  21397. /* 54 */ "NotExists",
  21398. /* 55 */ "Sequence",
  21399. /* 56 */ "NewRowid",
  21400. /* 57 */ "Insert",
  21401. /* 58 */ "InsertInt",
  21402. /* 59 */ "Delete",
  21403. /* 60 */ "ResetCount",
  21404. /* 61 */ "SorterCompare",
  21405. /* 62 */ "SorterData",
  21406. /* 63 */ "RowKey",
  21407. /* 64 */ "RowData",
  21408. /* 65 */ "Rowid",
  21409. /* 66 */ "NullRow",
  21410. /* 67 */ "Last",
  21411. /* 68 */ "Or",
  21412. /* 69 */ "And",
  21413. /* 70 */ "SorterSort",
  21414. /* 71 */ "Sort",
  21415. /* 72 */ "Rewind",
  21416. /* 73 */ "IsNull",
  21417. /* 74 */ "NotNull",
  21418. /* 75 */ "Ne",
  21419. /* 76 */ "Eq",
  21420. /* 77 */ "Gt",
  21421. /* 78 */ "Le",
  21422. /* 79 */ "Lt",
  21423. /* 80 */ "Ge",
  21424. /* 81 */ "SorterNext",
  21425. /* 82 */ "BitAnd",
  21426. /* 83 */ "BitOr",
  21427. /* 84 */ "ShiftLeft",
  21428. /* 85 */ "ShiftRight",
  21429. /* 86 */ "Add",
  21430. /* 87 */ "Subtract",
  21431. /* 88 */ "Multiply",
  21432. /* 89 */ "Divide",
  21433. /* 90 */ "Remainder",
  21434. /* 91 */ "Concat",
  21435. /* 92 */ "Prev",
  21436. /* 93 */ "BitNot",
  21437. /* 94 */ "String8",
  21438. /* 95 */ "Next",
  21439. /* 96 */ "SorterInsert",
  21440. /* 97 */ "IdxInsert",
  21441. /* 98 */ "IdxDelete",
  21442. /* 99 */ "IdxRowid",
  21443. /* 100 */ "IdxLT",
  21444. /* 101 */ "IdxGE",
  21445. /* 102 */ "Destroy",
  21446. /* 103 */ "Clear",
  21447. /* 104 */ "CreateIndex",
  21448. /* 105 */ "CreateTable",
  21449. /* 106 */ "ParseSchema",
  21450. /* 107 */ "LoadAnalysis",
  21451. /* 108 */ "DropTable",
  21452. /* 109 */ "DropIndex",
  21453. /* 110 */ "DropTrigger",
  21454. /* 111 */ "IntegrityCk",
  21455. /* 112 */ "RowSetAdd",
  21456. /* 113 */ "RowSetRead",
  21457. /* 114 */ "RowSetTest",
  21458. /* 115 */ "Program",
  21459. /* 116 */ "Param",
  21460. /* 117 */ "FkCounter",
  21461. /* 118 */ "FkIfZero",
  21462. /* 119 */ "MemMax",
  21463. /* 120 */ "IfPos",
  21464. /* 121 */ "IfNeg",
  21465. /* 122 */ "IfZero",
  21466. /* 123 */ "AggStep",
  21467. /* 124 */ "AggFinal",
  21468. /* 125 */ "Checkpoint",
  21469. /* 126 */ "JournalMode",
  21470. /* 127 */ "Vacuum",
  21471. /* 128 */ "IncrVacuum",
  21472. /* 129 */ "Expire",
  21473. /* 130 */ "Real",
  21474. /* 131 */ "TableLock",
  21475. /* 132 */ "VBegin",
  21476. /* 133 */ "VCreate",
  21477. /* 134 */ "VDestroy",
  21478. /* 135 */ "VOpen",
  21479. /* 136 */ "VFilter",
  21480. /* 137 */ "VColumn",
  21481. /* 138 */ "VNext",
  21482. /* 139 */ "VRename",
  21483. /* 140 */ "VUpdate",
  21484. /* 141 */ "ToText",
  21485. /* 142 */ "ToBlob",
  21486. /* 143 */ "ToNumeric",
  21487. /* 144 */ "ToInt",
  21488. /* 145 */ "ToReal",
  21489. /* 146 */ "Pagecount",
  21490. /* 147 */ "MaxPgcnt",
  21491. /* 148 */ "Trace",
  21492. /* 149 */ "Noop",
  21493. /* 150 */ "Explain",
  21494. };
  21495. return azName[i];
  21496. }
  21497. #endif
  21498. /************** End of opcodes.c *********************************************/
  21499. /************** Begin file os_unix.c *****************************************/
  21500. /*
  21501. ** 2004 May 22
  21502. **
  21503. ** The author disclaims copyright to this source code. In place of
  21504. ** a legal notice, here is a blessing:
  21505. **
  21506. ** May you do good and not evil.
  21507. ** May you find forgiveness for yourself and forgive others.
  21508. ** May you share freely, never taking more than you give.
  21509. **
  21510. ******************************************************************************
  21511. **
  21512. ** This file contains the VFS implementation for unix-like operating systems
  21513. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  21514. **
  21515. ** There are actually several different VFS implementations in this file.
  21516. ** The differences are in the way that file locking is done. The default
  21517. ** implementation uses Posix Advisory Locks. Alternative implementations
  21518. ** use flock(), dot-files, various proprietary locking schemas, or simply
  21519. ** skip locking all together.
  21520. **
  21521. ** This source file is organized into divisions where the logic for various
  21522. ** subfunctions is contained within the appropriate division. PLEASE
  21523. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  21524. ** in the correct division and should be clearly labeled.
  21525. **
  21526. ** The layout of divisions is as follows:
  21527. **
  21528. ** * General-purpose declarations and utility functions.
  21529. ** * Unique file ID logic used by VxWorks.
  21530. ** * Various locking primitive implementations (all except proxy locking):
  21531. ** + for Posix Advisory Locks
  21532. ** + for no-op locks
  21533. ** + for dot-file locks
  21534. ** + for flock() locking
  21535. ** + for named semaphore locks (VxWorks only)
  21536. ** + for AFP filesystem locks (MacOSX only)
  21537. ** * sqlite3_file methods not associated with locking.
  21538. ** * Definitions of sqlite3_io_methods objects for all locking
  21539. ** methods plus "finder" functions for each locking method.
  21540. ** * sqlite3_vfs method implementations.
  21541. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  21542. ** * Definitions of sqlite3_vfs objects for all locking methods
  21543. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  21544. */
  21545. #if SQLITE_OS_UNIX /* This file is used on unix only */
  21546. /* Use posix_fallocate() if it is available
  21547. */
  21548. #if !defined(HAVE_POSIX_FALLOCATE) \
  21549. && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
  21550. # define HAVE_POSIX_FALLOCATE 1
  21551. #endif
  21552. /*
  21553. ** There are various methods for file locking used for concurrency
  21554. ** control:
  21555. **
  21556. ** 1. POSIX locking (the default),
  21557. ** 2. No locking,
  21558. ** 3. Dot-file locking,
  21559. ** 4. flock() locking,
  21560. ** 5. AFP locking (OSX only),
  21561. ** 6. Named POSIX semaphores (VXWorks only),
  21562. ** 7. proxy locking. (OSX only)
  21563. **
  21564. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  21565. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  21566. ** selection of the appropriate locking style based on the filesystem
  21567. ** where the database is located.
  21568. */
  21569. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  21570. # if defined(__APPLE__)
  21571. # define SQLITE_ENABLE_LOCKING_STYLE 1
  21572. # else
  21573. # define SQLITE_ENABLE_LOCKING_STYLE 0
  21574. # endif
  21575. #endif
  21576. /*
  21577. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  21578. ** vxworks, or 0 otherwise.
  21579. */
  21580. #ifndef OS_VXWORKS
  21581. # if defined(__RTP__) || defined(_WRS_KERNEL)
  21582. # define OS_VXWORKS 1
  21583. # else
  21584. # define OS_VXWORKS 0
  21585. # endif
  21586. #endif
  21587. /*
  21588. ** These #defines should enable >2GB file support on Posix if the
  21589. ** underlying operating system supports it. If the OS lacks
  21590. ** large file support, these should be no-ops.
  21591. **
  21592. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  21593. ** on the compiler command line. This is necessary if you are compiling
  21594. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  21595. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  21596. ** without this option, LFS is enable. But LFS does not exist in the kernel
  21597. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  21598. ** portability you should omit LFS.
  21599. **
  21600. ** The previous paragraph was written in 2005. (This paragraph is written
  21601. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  21602. ** you should probably leave LFS enabled. But some embedded platforms might
  21603. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  21604. */
  21605. #ifndef SQLITE_DISABLE_LFS
  21606. # define _LARGE_FILE 1
  21607. # ifndef _FILE_OFFSET_BITS
  21608. # define _FILE_OFFSET_BITS 64
  21609. # endif
  21610. # define _LARGEFILE_SOURCE 1
  21611. #endif
  21612. /*
  21613. ** standard include files.
  21614. */
  21615. #include <sys/types.h>
  21616. #include <sys/stat.h>
  21617. #include <fcntl.h>
  21618. #include <unistd.h>
  21619. /* #include <time.h> */
  21620. #include <sys/time.h>
  21621. #include <errno.h>
  21622. #ifndef SQLITE_OMIT_WAL
  21623. #include <sys/mman.h>
  21624. #endif
  21625. #if SQLITE_ENABLE_LOCKING_STYLE
  21626. # include <sys/ioctl.h>
  21627. # if OS_VXWORKS
  21628. # include <semaphore.h>
  21629. # include <limits.h>
  21630. # else
  21631. # include <sys/file.h>
  21632. # include <sys/param.h>
  21633. # endif
  21634. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  21635. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  21636. # include <sys/mount.h>
  21637. #endif
  21638. #ifdef HAVE_UTIME
  21639. # include <utime.h>
  21640. #endif
  21641. /*
  21642. ** Allowed values of unixFile.fsFlags
  21643. */
  21644. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  21645. /*
  21646. ** If we are to be thread-safe, include the pthreads header and define
  21647. ** the SQLITE_UNIX_THREADS macro.
  21648. */
  21649. #if SQLITE_THREADSAFE
  21650. /* # include <pthread.h> */
  21651. # define SQLITE_UNIX_THREADS 1
  21652. #endif
  21653. /*
  21654. ** Default permissions when creating a new file
  21655. */
  21656. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  21657. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  21658. #endif
  21659. /*
  21660. ** Default permissions when creating auto proxy dir
  21661. */
  21662. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  21663. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  21664. #endif
  21665. /*
  21666. ** Maximum supported path-length.
  21667. */
  21668. #define MAX_PATHNAME 512
  21669. /*
  21670. ** Only set the lastErrno if the error code is a real error and not
  21671. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  21672. */
  21673. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  21674. /* Forward references */
  21675. typedef struct unixShm unixShm; /* Connection shared memory */
  21676. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  21677. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  21678. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  21679. /*
  21680. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  21681. ** cannot be closed immediately. In these cases, instances of the following
  21682. ** structure are used to store the file descriptor while waiting for an
  21683. ** opportunity to either close or reuse it.
  21684. */
  21685. struct UnixUnusedFd {
  21686. int fd; /* File descriptor to close */
  21687. int flags; /* Flags this file descriptor was opened with */
  21688. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  21689. };
  21690. /*
  21691. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  21692. ** VFS implementations.
  21693. */
  21694. typedef struct unixFile unixFile;
  21695. struct unixFile {
  21696. sqlite3_io_methods const *pMethod; /* Always the first entry */
  21697. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  21698. unixInodeInfo *pInode; /* Info about locks on this inode */
  21699. int h; /* The file descriptor */
  21700. unsigned char eFileLock; /* The type of lock held on this fd */
  21701. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  21702. int lastErrno; /* The unix errno from last I/O error */
  21703. void *lockingContext; /* Locking style specific state */
  21704. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  21705. const char *zPath; /* Name of the file */
  21706. unixShm *pShm; /* Shared memory segment information */
  21707. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  21708. #ifdef __QNXNTO__
  21709. int sectorSize; /* Device sector size */
  21710. int deviceCharacteristics; /* Precomputed device characteristics */
  21711. #endif
  21712. #if SQLITE_ENABLE_LOCKING_STYLE
  21713. int openFlags; /* The flags specified at open() */
  21714. #endif
  21715. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  21716. unsigned fsFlags; /* cached details from statfs() */
  21717. #endif
  21718. #if OS_VXWORKS
  21719. struct vxworksFileId *pId; /* Unique file ID */
  21720. #endif
  21721. #ifdef SQLITE_DEBUG
  21722. /* The next group of variables are used to track whether or not the
  21723. ** transaction counter in bytes 24-27 of database files are updated
  21724. ** whenever any part of the database changes. An assertion fault will
  21725. ** occur if a file is updated without also updating the transaction
  21726. ** counter. This test is made to avoid new problems similar to the
  21727. ** one described by ticket #3584.
  21728. */
  21729. unsigned char transCntrChng; /* True if the transaction counter changed */
  21730. unsigned char dbUpdate; /* True if any part of database file changed */
  21731. unsigned char inNormalWrite; /* True if in a normal write operation */
  21732. #endif
  21733. #ifdef SQLITE_TEST
  21734. /* In test mode, increase the size of this structure a bit so that
  21735. ** it is larger than the struct CrashFile defined in test6.c.
  21736. */
  21737. char aPadding[32];
  21738. #endif
  21739. };
  21740. /*
  21741. ** Allowed values for the unixFile.ctrlFlags bitmask:
  21742. */
  21743. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  21744. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  21745. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  21746. #ifndef SQLITE_DISABLE_DIRSYNC
  21747. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  21748. #else
  21749. # define UNIXFILE_DIRSYNC 0x00
  21750. #endif
  21751. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  21752. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  21753. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  21754. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  21755. /*
  21756. ** Include code that is common to all os_*.c files
  21757. */
  21758. /************** Include os_common.h in the middle of os_unix.c ***************/
  21759. /************** Begin file os_common.h ***************************************/
  21760. /*
  21761. ** 2004 May 22
  21762. **
  21763. ** The author disclaims copyright to this source code. In place of
  21764. ** a legal notice, here is a blessing:
  21765. **
  21766. ** May you do good and not evil.
  21767. ** May you find forgiveness for yourself and forgive others.
  21768. ** May you share freely, never taking more than you give.
  21769. **
  21770. ******************************************************************************
  21771. **
  21772. ** This file contains macros and a little bit of code that is common to
  21773. ** all of the platform-specific files (os_*.c) and is #included into those
  21774. ** files.
  21775. **
  21776. ** This file should be #included by the os_*.c files only. It is not a
  21777. ** general purpose header file.
  21778. */
  21779. #ifndef _OS_COMMON_H_
  21780. #define _OS_COMMON_H_
  21781. /*
  21782. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  21783. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  21784. ** switch. The following code should catch this problem at compile-time.
  21785. */
  21786. #ifdef MEMORY_DEBUG
  21787. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  21788. #endif
  21789. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  21790. # ifndef SQLITE_DEBUG_OS_TRACE
  21791. # define SQLITE_DEBUG_OS_TRACE 0
  21792. # endif
  21793. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  21794. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  21795. #else
  21796. # define OSTRACE(X)
  21797. #endif
  21798. /*
  21799. ** Macros for performance tracing. Normally turned off. Only works
  21800. ** on i486 hardware.
  21801. */
  21802. #ifdef SQLITE_PERFORMANCE_TRACE
  21803. /*
  21804. ** hwtime.h contains inline assembler code for implementing
  21805. ** high-performance timing routines.
  21806. */
  21807. /************** Include hwtime.h in the middle of os_common.h ****************/
  21808. /************** Begin file hwtime.h ******************************************/
  21809. /*
  21810. ** 2008 May 27
  21811. **
  21812. ** The author disclaims copyright to this source code. In place of
  21813. ** a legal notice, here is a blessing:
  21814. **
  21815. ** May you do good and not evil.
  21816. ** May you find forgiveness for yourself and forgive others.
  21817. ** May you share freely, never taking more than you give.
  21818. **
  21819. ******************************************************************************
  21820. **
  21821. ** This file contains inline asm code for retrieving "high-performance"
  21822. ** counters for x86 class CPUs.
  21823. */
  21824. #ifndef _HWTIME_H_
  21825. #define _HWTIME_H_
  21826. /*
  21827. ** The following routine only works on pentium-class (or newer) processors.
  21828. ** It uses the RDTSC opcode to read the cycle count value out of the
  21829. ** processor and returns that value. This can be used for high-res
  21830. ** profiling.
  21831. */
  21832. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  21833. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  21834. #if defined(__GNUC__)
  21835. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21836. unsigned int lo, hi;
  21837. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  21838. return (sqlite_uint64)hi << 32 | lo;
  21839. }
  21840. #elif defined(_MSC_VER)
  21841. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  21842. __asm {
  21843. rdtsc
  21844. ret ; return value at EDX:EAX
  21845. }
  21846. }
  21847. #endif
  21848. #elif (defined(__GNUC__) && defined(__x86_64__))
  21849. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21850. unsigned long val;
  21851. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  21852. return val;
  21853. }
  21854. #elif (defined(__GNUC__) && defined(__ppc__))
  21855. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21856. unsigned long long retval;
  21857. unsigned long junk;
  21858. __asm__ __volatile__ ("\n\
  21859. 1: mftbu %1\n\
  21860. mftb %L0\n\
  21861. mftbu %0\n\
  21862. cmpw %0,%1\n\
  21863. bne 1b"
  21864. : "=r" (retval), "=r" (junk));
  21865. return retval;
  21866. }
  21867. #else
  21868. #error Need implementation of sqlite3Hwtime() for your platform.
  21869. /*
  21870. ** To compile without implementing sqlite3Hwtime() for your platform,
  21871. ** you can remove the above #error and use the following
  21872. ** stub function. You will lose timing support for many
  21873. ** of the debugging and testing utilities, but it should at
  21874. ** least compile and run.
  21875. */
  21876. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  21877. #endif
  21878. #endif /* !defined(_HWTIME_H_) */
  21879. /************** End of hwtime.h **********************************************/
  21880. /************** Continuing where we left off in os_common.h ******************/
  21881. static sqlite_uint64 g_start;
  21882. static sqlite_uint64 g_elapsed;
  21883. #define TIMER_START g_start=sqlite3Hwtime()
  21884. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  21885. #define TIMER_ELAPSED g_elapsed
  21886. #else
  21887. #define TIMER_START
  21888. #define TIMER_END
  21889. #define TIMER_ELAPSED ((sqlite_uint64)0)
  21890. #endif
  21891. /*
  21892. ** If we compile with the SQLITE_TEST macro set, then the following block
  21893. ** of code will give us the ability to simulate a disk I/O error. This
  21894. ** is used for testing the I/O recovery logic.
  21895. */
  21896. #ifdef SQLITE_TEST
  21897. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21898. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21899. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21900. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21901. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21902. SQLITE_API int sqlite3_diskfull_pending = 0;
  21903. SQLITE_API int sqlite3_diskfull = 0;
  21904. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  21905. #define SimulateIOError(CODE) \
  21906. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  21907. || sqlite3_io_error_pending-- == 1 ) \
  21908. { local_ioerr(); CODE; }
  21909. static void local_ioerr(){
  21910. IOTRACE(("IOERR\n"));
  21911. sqlite3_io_error_hit++;
  21912. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  21913. }
  21914. #define SimulateDiskfullError(CODE) \
  21915. if( sqlite3_diskfull_pending ){ \
  21916. if( sqlite3_diskfull_pending == 1 ){ \
  21917. local_ioerr(); \
  21918. sqlite3_diskfull = 1; \
  21919. sqlite3_io_error_hit = 1; \
  21920. CODE; \
  21921. }else{ \
  21922. sqlite3_diskfull_pending--; \
  21923. } \
  21924. }
  21925. #else
  21926. #define SimulateIOErrorBenign(X)
  21927. #define SimulateIOError(A)
  21928. #define SimulateDiskfullError(A)
  21929. #endif
  21930. /*
  21931. ** When testing, keep a count of the number of open files.
  21932. */
  21933. #ifdef SQLITE_TEST
  21934. SQLITE_API int sqlite3_open_file_count = 0;
  21935. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  21936. #else
  21937. #define OpenCounter(X)
  21938. #endif
  21939. #endif /* !defined(_OS_COMMON_H_) */
  21940. /************** End of os_common.h *******************************************/
  21941. /************** Continuing where we left off in os_unix.c ********************/
  21942. /*
  21943. ** Define various macros that are missing from some systems.
  21944. */
  21945. #ifndef O_LARGEFILE
  21946. # define O_LARGEFILE 0
  21947. #endif
  21948. #ifdef SQLITE_DISABLE_LFS
  21949. # undef O_LARGEFILE
  21950. # define O_LARGEFILE 0
  21951. #endif
  21952. #ifndef O_NOFOLLOW
  21953. # define O_NOFOLLOW 0
  21954. #endif
  21955. #ifndef O_BINARY
  21956. # define O_BINARY 0
  21957. #endif
  21958. /*
  21959. ** The threadid macro resolves to the thread-id or to 0. Used for
  21960. ** testing and debugging only.
  21961. */
  21962. #if SQLITE_THREADSAFE
  21963. #define threadid pthread_self()
  21964. #else
  21965. #define threadid 0
  21966. #endif
  21967. /*
  21968. ** Different Unix systems declare open() in different ways. Same use
  21969. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  21970. ** The difference is important when using a pointer to the function.
  21971. **
  21972. ** The safest way to deal with the problem is to always use this wrapper
  21973. ** which always has the same well-defined interface.
  21974. */
  21975. static int posixOpen(const char *zFile, int flags, int mode){
  21976. return open(zFile, flags, mode);
  21977. }
  21978. /*
  21979. ** On some systems, calls to fchown() will trigger a message in a security
  21980. ** log if they come from non-root processes. So avoid calling fchown() if
  21981. ** we are not running as root.
  21982. */
  21983. static int posixFchown(int fd, uid_t uid, gid_t gid){
  21984. return geteuid() ? 0 : fchown(fd,uid,gid);
  21985. }
  21986. /* Forward reference */
  21987. static int openDirectory(const char*, int*);
  21988. /*
  21989. ** Many system calls are accessed through pointer-to-functions so that
  21990. ** they may be overridden at runtime to facilitate fault injection during
  21991. ** testing and sandboxing. The following array holds the names and pointers
  21992. ** to all overrideable system calls.
  21993. */
  21994. static struct unix_syscall {
  21995. const char *zName; /* Name of the sytem call */
  21996. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  21997. sqlite3_syscall_ptr pDefault; /* Default value */
  21998. } aSyscall[] = {
  21999. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  22000. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  22001. { "close", (sqlite3_syscall_ptr)close, 0 },
  22002. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22003. { "access", (sqlite3_syscall_ptr)access, 0 },
  22004. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22005. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22006. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22007. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22008. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22009. /*
  22010. ** The DJGPP compiler environment looks mostly like Unix, but it
  22011. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22012. ** that always succeeds. This means that locking does not occur under
  22013. ** DJGPP. But it is DOS - what did you expect?
  22014. */
  22015. #ifdef __DJGPP__
  22016. { "fstat", 0, 0 },
  22017. #define osFstat(a,b,c) 0
  22018. #else
  22019. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22020. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  22021. #endif
  22022. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  22023. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  22024. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  22025. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  22026. { "read", (sqlite3_syscall_ptr)read, 0 },
  22027. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  22028. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22029. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  22030. #else
  22031. { "pread", (sqlite3_syscall_ptr)0, 0 },
  22032. #endif
  22033. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  22034. #if defined(USE_PREAD64)
  22035. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  22036. #else
  22037. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  22038. #endif
  22039. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  22040. { "write", (sqlite3_syscall_ptr)write, 0 },
  22041. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  22042. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22043. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  22044. #else
  22045. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  22046. #endif
  22047. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  22048. aSyscall[12].pCurrent)
  22049. #if defined(USE_PREAD64)
  22050. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  22051. #else
  22052. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  22053. #endif
  22054. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  22055. aSyscall[13].pCurrent)
  22056. #if SQLITE_ENABLE_LOCKING_STYLE
  22057. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  22058. #else
  22059. { "fchmod", (sqlite3_syscall_ptr)0, 0 },
  22060. #endif
  22061. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  22062. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  22063. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  22064. #else
  22065. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  22066. #endif
  22067. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  22068. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  22069. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  22070. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  22071. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  22072. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  22073. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  22074. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  22075. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  22076. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  22077. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  22078. { "umask", (sqlite3_syscall_ptr)umask, 0 },
  22079. #define osUmask ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
  22080. }; /* End of the overrideable system calls */
  22081. /*
  22082. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22083. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  22084. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22085. ** system call named zName.
  22086. */
  22087. static int unixSetSystemCall(
  22088. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22089. const char *zName, /* Name of system call to override */
  22090. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22091. ){
  22092. unsigned int i;
  22093. int rc = SQLITE_NOTFOUND;
  22094. UNUSED_PARAMETER(pNotUsed);
  22095. if( zName==0 ){
  22096. /* If no zName is given, restore all system calls to their default
  22097. ** settings and return NULL
  22098. */
  22099. rc = SQLITE_OK;
  22100. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22101. if( aSyscall[i].pDefault ){
  22102. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22103. }
  22104. }
  22105. }else{
  22106. /* If zName is specified, operate on only the one system call
  22107. ** specified.
  22108. */
  22109. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22110. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22111. if( aSyscall[i].pDefault==0 ){
  22112. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22113. }
  22114. rc = SQLITE_OK;
  22115. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22116. aSyscall[i].pCurrent = pNewFunc;
  22117. break;
  22118. }
  22119. }
  22120. }
  22121. return rc;
  22122. }
  22123. /*
  22124. ** Return the value of a system call. Return NULL if zName is not a
  22125. ** recognized system call name. NULL is also returned if the system call
  22126. ** is currently undefined.
  22127. */
  22128. static sqlite3_syscall_ptr unixGetSystemCall(
  22129. sqlite3_vfs *pNotUsed,
  22130. const char *zName
  22131. ){
  22132. unsigned int i;
  22133. UNUSED_PARAMETER(pNotUsed);
  22134. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22135. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22136. }
  22137. return 0;
  22138. }
  22139. /*
  22140. ** Return the name of the first system call after zName. If zName==NULL
  22141. ** then return the name of the first system call. Return NULL if zName
  22142. ** is the last system call or if zName is not the name of a valid
  22143. ** system call.
  22144. */
  22145. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  22146. int i = -1;
  22147. UNUSED_PARAMETER(p);
  22148. if( zName ){
  22149. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22150. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22151. }
  22152. }
  22153. for(i++; i<ArraySize(aSyscall); i++){
  22154. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22155. }
  22156. return 0;
  22157. }
  22158. /*
  22159. ** Invoke open(). Do so multiple times, until it either succeeds or
  22160. ** fails for some reason other than EINTR.
  22161. **
  22162. ** If the file creation mode "m" is 0 then set it to the default for
  22163. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22164. ** 0644) as modified by the system umask. If m is not 0, then
  22165. ** make the file creation mode be exactly m ignoring the umask.
  22166. **
  22167. ** The m parameter will be non-zero only when creating -wal, -journal,
  22168. ** and -shm files. We want those files to have *exactly* the same
  22169. ** permissions as their original database, unadulterated by the umask.
  22170. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22171. ** transaction crashes and leaves behind hot journals, then any
  22172. ** process that is able to write to the database will also be able to
  22173. ** recover the hot journals.
  22174. */
  22175. static int robust_open(const char *z, int f, mode_t m){
  22176. int fd;
  22177. mode_t m2;
  22178. mode_t origM = 0;
  22179. if( m==0 ){
  22180. m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
  22181. }else{
  22182. m2 = m;
  22183. origM = osUmask(0);
  22184. }
  22185. do{
  22186. #if defined(O_CLOEXEC)
  22187. fd = osOpen(z,f|O_CLOEXEC,m2);
  22188. #else
  22189. fd = osOpen(z,f,m2);
  22190. #endif
  22191. }while( fd<0 && errno==EINTR );
  22192. if( m ){
  22193. osUmask(origM);
  22194. }
  22195. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  22196. if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22197. #endif
  22198. return fd;
  22199. }
  22200. /*
  22201. ** Helper functions to obtain and relinquish the global mutex. The
  22202. ** global mutex is used to protect the unixInodeInfo and
  22203. ** vxworksFileId objects used by this file, all of which may be
  22204. ** shared by multiple threads.
  22205. **
  22206. ** Function unixMutexHeld() is used to assert() that the global mutex
  22207. ** is held when required. This function is only used as part of assert()
  22208. ** statements. e.g.
  22209. **
  22210. ** unixEnterMutex()
  22211. ** assert( unixMutexHeld() );
  22212. ** unixEnterLeave()
  22213. */
  22214. static void unixEnterMutex(void){
  22215. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22216. }
  22217. static void unixLeaveMutex(void){
  22218. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22219. }
  22220. #ifdef SQLITE_DEBUG
  22221. static int unixMutexHeld(void) {
  22222. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22223. }
  22224. #endif
  22225. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22226. /*
  22227. ** Helper function for printing out trace information from debugging
  22228. ** binaries. This returns the string represetation of the supplied
  22229. ** integer lock-type.
  22230. */
  22231. static const char *azFileLock(int eFileLock){
  22232. switch( eFileLock ){
  22233. case NO_LOCK: return "NONE";
  22234. case SHARED_LOCK: return "SHARED";
  22235. case RESERVED_LOCK: return "RESERVED";
  22236. case PENDING_LOCK: return "PENDING";
  22237. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22238. }
  22239. return "ERROR";
  22240. }
  22241. #endif
  22242. #ifdef SQLITE_LOCK_TRACE
  22243. /*
  22244. ** Print out information about all locking operations.
  22245. **
  22246. ** This routine is used for troubleshooting locks on multithreaded
  22247. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  22248. ** command-line option on the compiler. This code is normally
  22249. ** turned off.
  22250. */
  22251. static int lockTrace(int fd, int op, struct flock *p){
  22252. char *zOpName, *zType;
  22253. int s;
  22254. int savedErrno;
  22255. if( op==F_GETLK ){
  22256. zOpName = "GETLK";
  22257. }else if( op==F_SETLK ){
  22258. zOpName = "SETLK";
  22259. }else{
  22260. s = osFcntl(fd, op, p);
  22261. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  22262. return s;
  22263. }
  22264. if( p->l_type==F_RDLCK ){
  22265. zType = "RDLCK";
  22266. }else if( p->l_type==F_WRLCK ){
  22267. zType = "WRLCK";
  22268. }else if( p->l_type==F_UNLCK ){
  22269. zType = "UNLCK";
  22270. }else{
  22271. assert( 0 );
  22272. }
  22273. assert( p->l_whence==SEEK_SET );
  22274. s = osFcntl(fd, op, p);
  22275. savedErrno = errno;
  22276. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  22277. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  22278. (int)p->l_pid, s);
  22279. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  22280. struct flock l2;
  22281. l2 = *p;
  22282. osFcntl(fd, F_GETLK, &l2);
  22283. if( l2.l_type==F_RDLCK ){
  22284. zType = "RDLCK";
  22285. }else if( l2.l_type==F_WRLCK ){
  22286. zType = "WRLCK";
  22287. }else if( l2.l_type==F_UNLCK ){
  22288. zType = "UNLCK";
  22289. }else{
  22290. assert( 0 );
  22291. }
  22292. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  22293. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  22294. }
  22295. errno = savedErrno;
  22296. return s;
  22297. }
  22298. #undef osFcntl
  22299. #define osFcntl lockTrace
  22300. #endif /* SQLITE_LOCK_TRACE */
  22301. /*
  22302. ** Retry ftruncate() calls that fail due to EINTR
  22303. */
  22304. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22305. int rc;
  22306. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  22307. return rc;
  22308. }
  22309. /*
  22310. ** This routine translates a standard POSIX errno code into something
  22311. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22312. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22313. ** and a variety of "please close the file descriptor NOW" errors into
  22314. ** SQLITE_IOERR
  22315. **
  22316. ** Errors during initialization of locks, or file system support for locks,
  22317. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22318. */
  22319. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22320. switch (posixError) {
  22321. #if 0
  22322. /* At one point this code was not commented out. In theory, this branch
  22323. ** should never be hit, as this function should only be called after
  22324. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22325. ** the value of errno as the first argument. Since a system call has failed,
  22326. ** errno should be non-zero.
  22327. **
  22328. ** Despite this, if errno really is zero, we still don't want to return
  22329. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22330. ** propagated back to the caller. Commenting this branch out means errno==0
  22331. ** will be handled by the "default:" case below.
  22332. */
  22333. case 0:
  22334. return SQLITE_OK;
  22335. #endif
  22336. case EAGAIN:
  22337. case ETIMEDOUT:
  22338. case EBUSY:
  22339. case EINTR:
  22340. case ENOLCK:
  22341. /* random NFS retry error, unless during file system support
  22342. * introspection, in which it actually means what it says */
  22343. return SQLITE_BUSY;
  22344. case EACCES:
  22345. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  22346. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  22347. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  22348. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  22349. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  22350. return SQLITE_BUSY;
  22351. }
  22352. /* else fall through */
  22353. case EPERM:
  22354. return SQLITE_PERM;
  22355. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  22356. ** this module never makes such a call. And the code in SQLite itself
  22357. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  22358. ** this case is also commented out. If the system does set errno to EDEADLK,
  22359. ** the default SQLITE_IOERR_XXX code will be returned. */
  22360. #if 0
  22361. case EDEADLK:
  22362. return SQLITE_IOERR_BLOCKED;
  22363. #endif
  22364. #if EOPNOTSUPP!=ENOTSUP
  22365. case EOPNOTSUPP:
  22366. /* something went terribly awry, unless during file system support
  22367. * introspection, in which it actually means what it says */
  22368. #endif
  22369. #ifdef ENOTSUP
  22370. case ENOTSUP:
  22371. /* invalid fd, unless during file system support introspection, in which
  22372. * it actually means what it says */
  22373. #endif
  22374. case EIO:
  22375. case EBADF:
  22376. case EINVAL:
  22377. case ENOTCONN:
  22378. case ENODEV:
  22379. case ENXIO:
  22380. case ENOENT:
  22381. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  22382. case ESTALE:
  22383. #endif
  22384. case ENOSYS:
  22385. /* these should force the client to close the file and reconnect */
  22386. default:
  22387. return sqliteIOErr;
  22388. }
  22389. }
  22390. /******************************************************************************
  22391. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  22392. **
  22393. ** On most versions of unix, we can get a unique ID for a file by concatenating
  22394. ** the device number and the inode number. But this does not work on VxWorks.
  22395. ** On VxWorks, a unique file id must be based on the canonical filename.
  22396. **
  22397. ** A pointer to an instance of the following structure can be used as a
  22398. ** unique file ID in VxWorks. Each instance of this structure contains
  22399. ** a copy of the canonical filename. There is also a reference count.
  22400. ** The structure is reclaimed when the number of pointers to it drops to
  22401. ** zero.
  22402. **
  22403. ** There are never very many files open at one time and lookups are not
  22404. ** a performance-critical path, so it is sufficient to put these
  22405. ** structures on a linked list.
  22406. */
  22407. struct vxworksFileId {
  22408. struct vxworksFileId *pNext; /* Next in a list of them all */
  22409. int nRef; /* Number of references to this one */
  22410. int nName; /* Length of the zCanonicalName[] string */
  22411. char *zCanonicalName; /* Canonical filename */
  22412. };
  22413. #if OS_VXWORKS
  22414. /*
  22415. ** All unique filenames are held on a linked list headed by this
  22416. ** variable:
  22417. */
  22418. static struct vxworksFileId *vxworksFileList = 0;
  22419. /*
  22420. ** Simplify a filename into its canonical form
  22421. ** by making the following changes:
  22422. **
  22423. ** * removing any trailing and duplicate /
  22424. ** * convert /./ into just /
  22425. ** * convert /A/../ where A is any simple name into just /
  22426. **
  22427. ** Changes are made in-place. Return the new name length.
  22428. **
  22429. ** The original filename is in z[0..n-1]. Return the number of
  22430. ** characters in the simplified name.
  22431. */
  22432. static int vxworksSimplifyName(char *z, int n){
  22433. int i, j;
  22434. while( n>1 && z[n-1]=='/' ){ n--; }
  22435. for(i=j=0; i<n; i++){
  22436. if( z[i]=='/' ){
  22437. if( z[i+1]=='/' ) continue;
  22438. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  22439. i += 1;
  22440. continue;
  22441. }
  22442. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  22443. while( j>0 && z[j-1]!='/' ){ j--; }
  22444. if( j>0 ){ j--; }
  22445. i += 2;
  22446. continue;
  22447. }
  22448. }
  22449. z[j++] = z[i];
  22450. }
  22451. z[j] = 0;
  22452. return j;
  22453. }
  22454. /*
  22455. ** Find a unique file ID for the given absolute pathname. Return
  22456. ** a pointer to the vxworksFileId object. This pointer is the unique
  22457. ** file ID.
  22458. **
  22459. ** The nRef field of the vxworksFileId object is incremented before
  22460. ** the object is returned. A new vxworksFileId object is created
  22461. ** and added to the global list if necessary.
  22462. **
  22463. ** If a memory allocation error occurs, return NULL.
  22464. */
  22465. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  22466. struct vxworksFileId *pNew; /* search key and new file ID */
  22467. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  22468. int n; /* Length of zAbsoluteName string */
  22469. assert( zAbsoluteName[0]=='/' );
  22470. n = (int)strlen(zAbsoluteName);
  22471. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  22472. if( pNew==0 ) return 0;
  22473. pNew->zCanonicalName = (char*)&pNew[1];
  22474. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  22475. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  22476. /* Search for an existing entry that matching the canonical name.
  22477. ** If found, increment the reference count and return a pointer to
  22478. ** the existing file ID.
  22479. */
  22480. unixEnterMutex();
  22481. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  22482. if( pCandidate->nName==n
  22483. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  22484. ){
  22485. sqlite3_free(pNew);
  22486. pCandidate->nRef++;
  22487. unixLeaveMutex();
  22488. return pCandidate;
  22489. }
  22490. }
  22491. /* No match was found. We will make a new file ID */
  22492. pNew->nRef = 1;
  22493. pNew->nName = n;
  22494. pNew->pNext = vxworksFileList;
  22495. vxworksFileList = pNew;
  22496. unixLeaveMutex();
  22497. return pNew;
  22498. }
  22499. /*
  22500. ** Decrement the reference count on a vxworksFileId object. Free
  22501. ** the object when the reference count reaches zero.
  22502. */
  22503. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  22504. unixEnterMutex();
  22505. assert( pId->nRef>0 );
  22506. pId->nRef--;
  22507. if( pId->nRef==0 ){
  22508. struct vxworksFileId **pp;
  22509. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  22510. assert( *pp==pId );
  22511. *pp = pId->pNext;
  22512. sqlite3_free(pId);
  22513. }
  22514. unixLeaveMutex();
  22515. }
  22516. #endif /* OS_VXWORKS */
  22517. /*************** End of Unique File ID Utility Used By VxWorks ****************
  22518. ******************************************************************************/
  22519. /******************************************************************************
  22520. *************************** Posix Advisory Locking ****************************
  22521. **
  22522. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  22523. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  22524. ** sets or clears a lock, that operation overrides any prior locks set
  22525. ** by the same process. It does not explicitly say so, but this implies
  22526. ** that it overrides locks set by the same process using a different
  22527. ** file descriptor. Consider this test case:
  22528. **
  22529. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  22530. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  22531. **
  22532. ** Suppose ./file1 and ./file2 are really the same file (because
  22533. ** one is a hard or symbolic link to the other) then if you set
  22534. ** an exclusive lock on fd1, then try to get an exclusive lock
  22535. ** on fd2, it works. I would have expected the second lock to
  22536. ** fail since there was already a lock on the file due to fd1.
  22537. ** But not so. Since both locks came from the same process, the
  22538. ** second overrides the first, even though they were on different
  22539. ** file descriptors opened on different file names.
  22540. **
  22541. ** This means that we cannot use POSIX locks to synchronize file access
  22542. ** among competing threads of the same process. POSIX locks will work fine
  22543. ** to synchronize access for threads in separate processes, but not
  22544. ** threads within the same process.
  22545. **
  22546. ** To work around the problem, SQLite has to manage file locks internally
  22547. ** on its own. Whenever a new database is opened, we have to find the
  22548. ** specific inode of the database file (the inode is determined by the
  22549. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  22550. ** and check for locks already existing on that inode. When locks are
  22551. ** created or removed, we have to look at our own internal record of the
  22552. ** locks to see if another thread has previously set a lock on that same
  22553. ** inode.
  22554. **
  22555. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  22556. ** For VxWorks, we have to use the alternative unique ID system based on
  22557. ** canonical filename and implemented in the previous division.)
  22558. **
  22559. ** The sqlite3_file structure for POSIX is no longer just an integer file
  22560. ** descriptor. It is now a structure that holds the integer file
  22561. ** descriptor and a pointer to a structure that describes the internal
  22562. ** locks on the corresponding inode. There is one locking structure
  22563. ** per inode, so if the same inode is opened twice, both unixFile structures
  22564. ** point to the same locking structure. The locking structure keeps
  22565. ** a reference count (so we will know when to delete it) and a "cnt"
  22566. ** field that tells us its internal lock status. cnt==0 means the
  22567. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  22568. ** cnt>0 means there are cnt shared locks on the file.
  22569. **
  22570. ** Any attempt to lock or unlock a file first checks the locking
  22571. ** structure. The fcntl() system call is only invoked to set a
  22572. ** POSIX lock if the internal lock structure transitions between
  22573. ** a locked and an unlocked state.
  22574. **
  22575. ** But wait: there are yet more problems with POSIX advisory locks.
  22576. **
  22577. ** If you close a file descriptor that points to a file that has locks,
  22578. ** all locks on that file that are owned by the current process are
  22579. ** released. To work around this problem, each unixInodeInfo object
  22580. ** maintains a count of the number of pending locks on tha inode.
  22581. ** When an attempt is made to close an unixFile, if there are
  22582. ** other unixFile open on the same inode that are holding locks, the call
  22583. ** to close() the file descriptor is deferred until all of the locks clear.
  22584. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  22585. ** be closed and that list is walked (and cleared) when the last lock
  22586. ** clears.
  22587. **
  22588. ** Yet another problem: LinuxThreads do not play well with posix locks.
  22589. **
  22590. ** Many older versions of linux use the LinuxThreads library which is
  22591. ** not posix compliant. Under LinuxThreads, a lock created by thread
  22592. ** A cannot be modified or overridden by a different thread B.
  22593. ** Only thread A can modify the lock. Locking behavior is correct
  22594. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  22595. ** on linux - with NPTL a lock created by thread A can override locks
  22596. ** in thread B. But there is no way to know at compile-time which
  22597. ** threading library is being used. So there is no way to know at
  22598. ** compile-time whether or not thread A can override locks on thread B.
  22599. ** One has to do a run-time check to discover the behavior of the
  22600. ** current process.
  22601. **
  22602. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  22603. ** was dropped beginning with version 3.7.0. SQLite will still work with
  22604. ** LinuxThreads provided that (1) there is no more than one connection
  22605. ** per database file in the same process and (2) database connections
  22606. ** do not move across threads.
  22607. */
  22608. /*
  22609. ** An instance of the following structure serves as the key used
  22610. ** to locate a particular unixInodeInfo object.
  22611. */
  22612. struct unixFileId {
  22613. dev_t dev; /* Device number */
  22614. #if OS_VXWORKS
  22615. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  22616. #else
  22617. ino_t ino; /* Inode number */
  22618. #endif
  22619. };
  22620. /*
  22621. ** An instance of the following structure is allocated for each open
  22622. ** inode. Or, on LinuxThreads, there is one of these structures for
  22623. ** each inode opened by each thread.
  22624. **
  22625. ** A single inode can have multiple file descriptors, so each unixFile
  22626. ** structure contains a pointer to an instance of this object and this
  22627. ** object keeps a count of the number of unixFile pointing to it.
  22628. */
  22629. struct unixInodeInfo {
  22630. struct unixFileId fileId; /* The lookup key */
  22631. int nShared; /* Number of SHARED locks held */
  22632. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  22633. unsigned char bProcessLock; /* An exclusive process lock is held */
  22634. int nRef; /* Number of pointers to this structure */
  22635. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  22636. int nLock; /* Number of outstanding file locks */
  22637. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  22638. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  22639. unixInodeInfo *pPrev; /* .... doubly linked */
  22640. #if SQLITE_ENABLE_LOCKING_STYLE
  22641. unsigned long long sharedByte; /* for AFP simulated shared lock */
  22642. #endif
  22643. #if OS_VXWORKS
  22644. sem_t *pSem; /* Named POSIX semaphore */
  22645. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  22646. #endif
  22647. };
  22648. /*
  22649. ** A lists of all unixInodeInfo objects.
  22650. */
  22651. static unixInodeInfo *inodeList = 0;
  22652. /*
  22653. **
  22654. ** This function - unixLogError_x(), is only ever called via the macro
  22655. ** unixLogError().
  22656. **
  22657. ** It is invoked after an error occurs in an OS function and errno has been
  22658. ** set. It logs a message using sqlite3_log() containing the current value of
  22659. ** errno and, if possible, the human-readable equivalent from strerror() or
  22660. ** strerror_r().
  22661. **
  22662. ** The first argument passed to the macro should be the error code that
  22663. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  22664. ** The two subsequent arguments should be the name of the OS function that
  22665. ** failed (e.g. "unlink", "open") and the associated file-system path,
  22666. ** if any.
  22667. */
  22668. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  22669. static int unixLogErrorAtLine(
  22670. int errcode, /* SQLite error code */
  22671. const char *zFunc, /* Name of OS function that failed */
  22672. const char *zPath, /* File path associated with error */
  22673. int iLine /* Source line number where error occurred */
  22674. ){
  22675. char *zErr; /* Message from strerror() or equivalent */
  22676. int iErrno = errno; /* Saved syscall error number */
  22677. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  22678. ** the strerror() function to obtain the human-readable error message
  22679. ** equivalent to errno. Otherwise, use strerror_r().
  22680. */
  22681. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  22682. char aErr[80];
  22683. memset(aErr, 0, sizeof(aErr));
  22684. zErr = aErr;
  22685. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  22686. ** assume that the system provides the GNU version of strerror_r() that
  22687. ** returns a pointer to a buffer containing the error message. That pointer
  22688. ** may point to aErr[], or it may point to some static storage somewhere.
  22689. ** Otherwise, assume that the system provides the POSIX version of
  22690. ** strerror_r(), which always writes an error message into aErr[].
  22691. **
  22692. ** If the code incorrectly assumes that it is the POSIX version that is
  22693. ** available, the error message will often be an empty string. Not a
  22694. ** huge problem. Incorrectly concluding that the GNU version is available
  22695. ** could lead to a segfault though.
  22696. */
  22697. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  22698. zErr =
  22699. # endif
  22700. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  22701. #elif SQLITE_THREADSAFE
  22702. /* This is a threadsafe build, but strerror_r() is not available. */
  22703. zErr = "";
  22704. #else
  22705. /* Non-threadsafe build, use strerror(). */
  22706. zErr = strerror(iErrno);
  22707. #endif
  22708. assert( errcode!=SQLITE_OK );
  22709. if( zPath==0 ) zPath = "";
  22710. sqlite3_log(errcode,
  22711. "os_unix.c:%d: (%d) %s(%s) - %s",
  22712. iLine, iErrno, zFunc, zPath, zErr
  22713. );
  22714. return errcode;
  22715. }
  22716. /*
  22717. ** Close a file descriptor.
  22718. **
  22719. ** We assume that close() almost always works, since it is only in a
  22720. ** very sick application or on a very sick platform that it might fail.
  22721. ** If it does fail, simply leak the file descriptor, but do log the
  22722. ** error.
  22723. **
  22724. ** Note that it is not safe to retry close() after EINTR since the
  22725. ** file descriptor might have already been reused by another thread.
  22726. ** So we don't even try to recover from an EINTR. Just log the error
  22727. ** and move on.
  22728. */
  22729. static void robust_close(unixFile *pFile, int h, int lineno){
  22730. if( osClose(h) ){
  22731. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  22732. pFile ? pFile->zPath : 0, lineno);
  22733. }
  22734. }
  22735. /*
  22736. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  22737. */
  22738. static void closePendingFds(unixFile *pFile){
  22739. unixInodeInfo *pInode = pFile->pInode;
  22740. UnixUnusedFd *p;
  22741. UnixUnusedFd *pNext;
  22742. for(p=pInode->pUnused; p; p=pNext){
  22743. pNext = p->pNext;
  22744. robust_close(pFile, p->fd, __LINE__);
  22745. sqlite3_free(p);
  22746. }
  22747. pInode->pUnused = 0;
  22748. }
  22749. /*
  22750. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  22751. **
  22752. ** The mutex entered using the unixEnterMutex() function must be held
  22753. ** when this function is called.
  22754. */
  22755. static void releaseInodeInfo(unixFile *pFile){
  22756. unixInodeInfo *pInode = pFile->pInode;
  22757. assert( unixMutexHeld() );
  22758. if( ALWAYS(pInode) ){
  22759. pInode->nRef--;
  22760. if( pInode->nRef==0 ){
  22761. assert( pInode->pShmNode==0 );
  22762. closePendingFds(pFile);
  22763. if( pInode->pPrev ){
  22764. assert( pInode->pPrev->pNext==pInode );
  22765. pInode->pPrev->pNext = pInode->pNext;
  22766. }else{
  22767. assert( inodeList==pInode );
  22768. inodeList = pInode->pNext;
  22769. }
  22770. if( pInode->pNext ){
  22771. assert( pInode->pNext->pPrev==pInode );
  22772. pInode->pNext->pPrev = pInode->pPrev;
  22773. }
  22774. sqlite3_free(pInode);
  22775. }
  22776. }
  22777. }
  22778. /*
  22779. ** Given a file descriptor, locate the unixInodeInfo object that
  22780. ** describes that file descriptor. Create a new one if necessary. The
  22781. ** return value might be uninitialized if an error occurs.
  22782. **
  22783. ** The mutex entered using the unixEnterMutex() function must be held
  22784. ** when this function is called.
  22785. **
  22786. ** Return an appropriate error code.
  22787. */
  22788. static int findInodeInfo(
  22789. unixFile *pFile, /* Unix file with file desc used in the key */
  22790. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  22791. ){
  22792. int rc; /* System call return code */
  22793. int fd; /* The file descriptor for pFile */
  22794. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  22795. struct stat statbuf; /* Low-level file information */
  22796. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  22797. assert( unixMutexHeld() );
  22798. /* Get low-level information about the file that we can used to
  22799. ** create a unique name for the file.
  22800. */
  22801. fd = pFile->h;
  22802. rc = osFstat(fd, &statbuf);
  22803. if( rc!=0 ){
  22804. pFile->lastErrno = errno;
  22805. #ifdef EOVERFLOW
  22806. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  22807. #endif
  22808. return SQLITE_IOERR;
  22809. }
  22810. #ifdef __APPLE__
  22811. /* On OS X on an msdos filesystem, the inode number is reported
  22812. ** incorrectly for zero-size files. See ticket #3260. To work
  22813. ** around this problem (we consider it a bug in OS X, not SQLite)
  22814. ** we always increase the file size to 1 by writing a single byte
  22815. ** prior to accessing the inode number. The one byte written is
  22816. ** an ASCII 'S' character which also happens to be the first byte
  22817. ** in the header of every SQLite database. In this way, if there
  22818. ** is a race condition such that another thread has already populated
  22819. ** the first page of the database, no damage is done.
  22820. */
  22821. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  22822. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  22823. if( rc!=1 ){
  22824. pFile->lastErrno = errno;
  22825. return SQLITE_IOERR;
  22826. }
  22827. rc = osFstat(fd, &statbuf);
  22828. if( rc!=0 ){
  22829. pFile->lastErrno = errno;
  22830. return SQLITE_IOERR;
  22831. }
  22832. }
  22833. #endif
  22834. memset(&fileId, 0, sizeof(fileId));
  22835. fileId.dev = statbuf.st_dev;
  22836. #if OS_VXWORKS
  22837. fileId.pId = pFile->pId;
  22838. #else
  22839. fileId.ino = statbuf.st_ino;
  22840. #endif
  22841. pInode = inodeList;
  22842. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  22843. pInode = pInode->pNext;
  22844. }
  22845. if( pInode==0 ){
  22846. pInode = sqlite3_malloc( sizeof(*pInode) );
  22847. if( pInode==0 ){
  22848. return SQLITE_NOMEM;
  22849. }
  22850. memset(pInode, 0, sizeof(*pInode));
  22851. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  22852. pInode->nRef = 1;
  22853. pInode->pNext = inodeList;
  22854. pInode->pPrev = 0;
  22855. if( inodeList ) inodeList->pPrev = pInode;
  22856. inodeList = pInode;
  22857. }else{
  22858. pInode->nRef++;
  22859. }
  22860. *ppInode = pInode;
  22861. return SQLITE_OK;
  22862. }
  22863. /*
  22864. ** This routine checks if there is a RESERVED lock held on the specified
  22865. ** file by this or any other process. If such a lock is held, set *pResOut
  22866. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22867. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22868. */
  22869. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  22870. int rc = SQLITE_OK;
  22871. int reserved = 0;
  22872. unixFile *pFile = (unixFile*)id;
  22873. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22874. assert( pFile );
  22875. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  22876. /* Check if a thread in this process holds such a lock */
  22877. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  22878. reserved = 1;
  22879. }
  22880. /* Otherwise see if some other process holds it.
  22881. */
  22882. #ifndef __DJGPP__
  22883. if( !reserved && !pFile->pInode->bProcessLock ){
  22884. struct flock lock;
  22885. lock.l_whence = SEEK_SET;
  22886. lock.l_start = RESERVED_BYTE;
  22887. lock.l_len = 1;
  22888. lock.l_type = F_WRLCK;
  22889. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  22890. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  22891. pFile->lastErrno = errno;
  22892. } else if( lock.l_type!=F_UNLCK ){
  22893. reserved = 1;
  22894. }
  22895. }
  22896. #endif
  22897. unixLeaveMutex();
  22898. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  22899. *pResOut = reserved;
  22900. return rc;
  22901. }
  22902. /*
  22903. ** Attempt to set a system-lock on the file pFile. The lock is
  22904. ** described by pLock.
  22905. **
  22906. ** If the pFile was opened read/write from unix-excl, then the only lock
  22907. ** ever obtained is an exclusive lock, and it is obtained exactly once
  22908. ** the first time any lock is attempted. All subsequent system locking
  22909. ** operations become no-ops. Locking operations still happen internally,
  22910. ** in order to coordinate access between separate database connections
  22911. ** within this process, but all of that is handled in memory and the
  22912. ** operating system does not participate.
  22913. **
  22914. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  22915. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  22916. ** and is read-only.
  22917. **
  22918. ** Zero is returned if the call completes successfully, or -1 if a call
  22919. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  22920. */
  22921. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  22922. int rc;
  22923. unixInodeInfo *pInode = pFile->pInode;
  22924. assert( unixMutexHeld() );
  22925. assert( pInode!=0 );
  22926. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  22927. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  22928. ){
  22929. if( pInode->bProcessLock==0 ){
  22930. struct flock lock;
  22931. assert( pInode->nLock==0 );
  22932. lock.l_whence = SEEK_SET;
  22933. lock.l_start = SHARED_FIRST;
  22934. lock.l_len = SHARED_SIZE;
  22935. lock.l_type = F_WRLCK;
  22936. rc = osFcntl(pFile->h, F_SETLK, &lock);
  22937. if( rc<0 ) return rc;
  22938. pInode->bProcessLock = 1;
  22939. pInode->nLock++;
  22940. }else{
  22941. rc = 0;
  22942. }
  22943. }else{
  22944. rc = osFcntl(pFile->h, F_SETLK, pLock);
  22945. }
  22946. return rc;
  22947. }
  22948. /*
  22949. ** Lock the file with the lock specified by parameter eFileLock - one
  22950. ** of the following:
  22951. **
  22952. ** (1) SHARED_LOCK
  22953. ** (2) RESERVED_LOCK
  22954. ** (3) PENDING_LOCK
  22955. ** (4) EXCLUSIVE_LOCK
  22956. **
  22957. ** Sometimes when requesting one lock state, additional lock states
  22958. ** are inserted in between. The locking might fail on one of the later
  22959. ** transitions leaving the lock state different from what it started but
  22960. ** still short of its goal. The following chart shows the allowed
  22961. ** transitions and the inserted intermediate states:
  22962. **
  22963. ** UNLOCKED -> SHARED
  22964. ** SHARED -> RESERVED
  22965. ** SHARED -> (PENDING) -> EXCLUSIVE
  22966. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22967. ** PENDING -> EXCLUSIVE
  22968. **
  22969. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22970. ** routine to lower a locking level.
  22971. */
  22972. static int unixLock(sqlite3_file *id, int eFileLock){
  22973. /* The following describes the implementation of the various locks and
  22974. ** lock transitions in terms of the POSIX advisory shared and exclusive
  22975. ** lock primitives (called read-locks and write-locks below, to avoid
  22976. ** confusion with SQLite lock names). The algorithms are complicated
  22977. ** slightly in order to be compatible with windows systems simultaneously
  22978. ** accessing the same database file, in case that is ever required.
  22979. **
  22980. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  22981. ** byte', each single bytes at well known offsets, and the 'shared byte
  22982. ** range', a range of 510 bytes at a well known offset.
  22983. **
  22984. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  22985. ** byte'. If this is successful, a random byte from the 'shared byte
  22986. ** range' is read-locked and the lock on the 'pending byte' released.
  22987. **
  22988. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  22989. ** A RESERVED lock is implemented by grabbing a write-lock on the
  22990. ** 'reserved byte'.
  22991. **
  22992. ** A process may only obtain a PENDING lock after it has obtained a
  22993. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  22994. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  22995. ** obtained, but existing SHARED locks are allowed to persist. A process
  22996. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  22997. ** This property is used by the algorithm for rolling back a journal file
  22998. ** after a crash.
  22999. **
  23000. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23001. ** implemented by obtaining a write-lock on the entire 'shared byte
  23002. ** range'. Since all other locks require a read-lock on one of the bytes
  23003. ** within this range, this ensures that no other locks are held on the
  23004. ** database.
  23005. **
  23006. ** The reason a single byte cannot be used instead of the 'shared byte
  23007. ** range' is that some versions of windows do not support read-locks. By
  23008. ** locking a random byte from a range, concurrent SHARED locks may exist
  23009. ** even if the locking primitive used is always a write-lock.
  23010. */
  23011. int rc = SQLITE_OK;
  23012. unixFile *pFile = (unixFile*)id;
  23013. unixInodeInfo *pInode;
  23014. struct flock lock;
  23015. int tErrno = 0;
  23016. assert( pFile );
  23017. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23018. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23019. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  23020. /* If there is already a lock of this type or more restrictive on the
  23021. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23022. ** unixEnterMutex() hasn't been called yet.
  23023. */
  23024. if( pFile->eFileLock>=eFileLock ){
  23025. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23026. azFileLock(eFileLock)));
  23027. return SQLITE_OK;
  23028. }
  23029. /* Make sure the locking sequence is correct.
  23030. ** (1) We never move from unlocked to anything higher than shared lock.
  23031. ** (2) SQLite never explicitly requests a pendig lock.
  23032. ** (3) A shared lock is always held when a reserve lock is requested.
  23033. */
  23034. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23035. assert( eFileLock!=PENDING_LOCK );
  23036. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23037. /* This mutex is needed because pFile->pInode is shared across threads
  23038. */
  23039. unixEnterMutex();
  23040. pInode = pFile->pInode;
  23041. /* If some thread using this PID has a lock via a different unixFile*
  23042. ** handle that precludes the requested lock, return BUSY.
  23043. */
  23044. if( (pFile->eFileLock!=pInode->eFileLock &&
  23045. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23046. ){
  23047. rc = SQLITE_BUSY;
  23048. goto end_lock;
  23049. }
  23050. /* If a SHARED lock is requested, and some thread using this PID already
  23051. ** has a SHARED or RESERVED lock, then increment reference counts and
  23052. ** return SQLITE_OK.
  23053. */
  23054. if( eFileLock==SHARED_LOCK &&
  23055. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23056. assert( eFileLock==SHARED_LOCK );
  23057. assert( pFile->eFileLock==0 );
  23058. assert( pInode->nShared>0 );
  23059. pFile->eFileLock = SHARED_LOCK;
  23060. pInode->nShared++;
  23061. pInode->nLock++;
  23062. goto end_lock;
  23063. }
  23064. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23065. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23066. ** be released.
  23067. */
  23068. lock.l_len = 1L;
  23069. lock.l_whence = SEEK_SET;
  23070. if( eFileLock==SHARED_LOCK
  23071. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  23072. ){
  23073. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  23074. lock.l_start = PENDING_BYTE;
  23075. if( unixFileLock(pFile, &lock) ){
  23076. tErrno = errno;
  23077. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23078. if( rc!=SQLITE_BUSY ){
  23079. pFile->lastErrno = tErrno;
  23080. }
  23081. goto end_lock;
  23082. }
  23083. }
  23084. /* If control gets to this point, then actually go ahead and make
  23085. ** operating system calls for the specified lock.
  23086. */
  23087. if( eFileLock==SHARED_LOCK ){
  23088. assert( pInode->nShared==0 );
  23089. assert( pInode->eFileLock==0 );
  23090. assert( rc==SQLITE_OK );
  23091. /* Now get the read-lock */
  23092. lock.l_start = SHARED_FIRST;
  23093. lock.l_len = SHARED_SIZE;
  23094. if( unixFileLock(pFile, &lock) ){
  23095. tErrno = errno;
  23096. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23097. }
  23098. /* Drop the temporary PENDING lock */
  23099. lock.l_start = PENDING_BYTE;
  23100. lock.l_len = 1L;
  23101. lock.l_type = F_UNLCK;
  23102. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  23103. /* This could happen with a network mount */
  23104. tErrno = errno;
  23105. rc = SQLITE_IOERR_UNLOCK;
  23106. }
  23107. if( rc ){
  23108. if( rc!=SQLITE_BUSY ){
  23109. pFile->lastErrno = tErrno;
  23110. }
  23111. goto end_lock;
  23112. }else{
  23113. pFile->eFileLock = SHARED_LOCK;
  23114. pInode->nLock++;
  23115. pInode->nShared = 1;
  23116. }
  23117. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  23118. /* We are trying for an exclusive lock but another thread in this
  23119. ** same process is still holding a shared lock. */
  23120. rc = SQLITE_BUSY;
  23121. }else{
  23122. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  23123. ** assumed that there is a SHARED or greater lock on the file
  23124. ** already.
  23125. */
  23126. assert( 0!=pFile->eFileLock );
  23127. lock.l_type = F_WRLCK;
  23128. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  23129. if( eFileLock==RESERVED_LOCK ){
  23130. lock.l_start = RESERVED_BYTE;
  23131. lock.l_len = 1L;
  23132. }else{
  23133. lock.l_start = SHARED_FIRST;
  23134. lock.l_len = SHARED_SIZE;
  23135. }
  23136. if( unixFileLock(pFile, &lock) ){
  23137. tErrno = errno;
  23138. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23139. if( rc!=SQLITE_BUSY ){
  23140. pFile->lastErrno = tErrno;
  23141. }
  23142. }
  23143. }
  23144. #ifdef SQLITE_DEBUG
  23145. /* Set up the transaction-counter change checking flags when
  23146. ** transitioning from a SHARED to a RESERVED lock. The change
  23147. ** from SHARED to RESERVED marks the beginning of a normal
  23148. ** write operation (not a hot journal rollback).
  23149. */
  23150. if( rc==SQLITE_OK
  23151. && pFile->eFileLock<=SHARED_LOCK
  23152. && eFileLock==RESERVED_LOCK
  23153. ){
  23154. pFile->transCntrChng = 0;
  23155. pFile->dbUpdate = 0;
  23156. pFile->inNormalWrite = 1;
  23157. }
  23158. #endif
  23159. if( rc==SQLITE_OK ){
  23160. pFile->eFileLock = eFileLock;
  23161. pInode->eFileLock = eFileLock;
  23162. }else if( eFileLock==EXCLUSIVE_LOCK ){
  23163. pFile->eFileLock = PENDING_LOCK;
  23164. pInode->eFileLock = PENDING_LOCK;
  23165. }
  23166. end_lock:
  23167. unixLeaveMutex();
  23168. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  23169. rc==SQLITE_OK ? "ok" : "failed"));
  23170. return rc;
  23171. }
  23172. /*
  23173. ** Add the file descriptor used by file handle pFile to the corresponding
  23174. ** pUnused list.
  23175. */
  23176. static void setPendingFd(unixFile *pFile){
  23177. unixInodeInfo *pInode = pFile->pInode;
  23178. UnixUnusedFd *p = pFile->pUnused;
  23179. p->pNext = pInode->pUnused;
  23180. pInode->pUnused = p;
  23181. pFile->h = -1;
  23182. pFile->pUnused = 0;
  23183. }
  23184. /*
  23185. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23186. ** must be either NO_LOCK or SHARED_LOCK.
  23187. **
  23188. ** If the locking level of the file descriptor is already at or below
  23189. ** the requested locking level, this routine is a no-op.
  23190. **
  23191. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  23192. ** the byte range is divided into 2 parts and the first part is unlocked then
  23193. ** set to a read lock, then the other part is simply unlocked. This works
  23194. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  23195. ** remove the write lock on a region when a read lock is set.
  23196. */
  23197. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  23198. unixFile *pFile = (unixFile*)id;
  23199. unixInodeInfo *pInode;
  23200. struct flock lock;
  23201. int rc = SQLITE_OK;
  23202. assert( pFile );
  23203. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  23204. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  23205. getpid()));
  23206. assert( eFileLock<=SHARED_LOCK );
  23207. if( pFile->eFileLock<=eFileLock ){
  23208. return SQLITE_OK;
  23209. }
  23210. unixEnterMutex();
  23211. pInode = pFile->pInode;
  23212. assert( pInode->nShared!=0 );
  23213. if( pFile->eFileLock>SHARED_LOCK ){
  23214. assert( pInode->eFileLock==pFile->eFileLock );
  23215. #ifdef SQLITE_DEBUG
  23216. /* When reducing a lock such that other processes can start
  23217. ** reading the database file again, make sure that the
  23218. ** transaction counter was updated if any part of the database
  23219. ** file changed. If the transaction counter is not updated,
  23220. ** other connections to the same file might not realize that
  23221. ** the file has changed and hence might not know to flush their
  23222. ** cache. The use of a stale cache can lead to database corruption.
  23223. */
  23224. pFile->inNormalWrite = 0;
  23225. #endif
  23226. /* downgrading to a shared lock on NFS involves clearing the write lock
  23227. ** before establishing the readlock - to avoid a race condition we downgrade
  23228. ** the lock in 2 blocks, so that part of the range will be covered by a
  23229. ** write lock until the rest is covered by a read lock:
  23230. ** 1: [WWWWW]
  23231. ** 2: [....W]
  23232. ** 3: [RRRRW]
  23233. ** 4: [RRRR.]
  23234. */
  23235. if( eFileLock==SHARED_LOCK ){
  23236. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  23237. (void)handleNFSUnlock;
  23238. assert( handleNFSUnlock==0 );
  23239. #endif
  23240. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23241. if( handleNFSUnlock ){
  23242. int tErrno; /* Error code from system call errors */
  23243. off_t divSize = SHARED_SIZE - 1;
  23244. lock.l_type = F_UNLCK;
  23245. lock.l_whence = SEEK_SET;
  23246. lock.l_start = SHARED_FIRST;
  23247. lock.l_len = divSize;
  23248. if( unixFileLock(pFile, &lock)==(-1) ){
  23249. tErrno = errno;
  23250. rc = SQLITE_IOERR_UNLOCK;
  23251. if( IS_LOCK_ERROR(rc) ){
  23252. pFile->lastErrno = tErrno;
  23253. }
  23254. goto end_unlock;
  23255. }
  23256. lock.l_type = F_RDLCK;
  23257. lock.l_whence = SEEK_SET;
  23258. lock.l_start = SHARED_FIRST;
  23259. lock.l_len = divSize;
  23260. if( unixFileLock(pFile, &lock)==(-1) ){
  23261. tErrno = errno;
  23262. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  23263. if( IS_LOCK_ERROR(rc) ){
  23264. pFile->lastErrno = tErrno;
  23265. }
  23266. goto end_unlock;
  23267. }
  23268. lock.l_type = F_UNLCK;
  23269. lock.l_whence = SEEK_SET;
  23270. lock.l_start = SHARED_FIRST+divSize;
  23271. lock.l_len = SHARED_SIZE-divSize;
  23272. if( unixFileLock(pFile, &lock)==(-1) ){
  23273. tErrno = errno;
  23274. rc = SQLITE_IOERR_UNLOCK;
  23275. if( IS_LOCK_ERROR(rc) ){
  23276. pFile->lastErrno = tErrno;
  23277. }
  23278. goto end_unlock;
  23279. }
  23280. }else
  23281. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23282. {
  23283. lock.l_type = F_RDLCK;
  23284. lock.l_whence = SEEK_SET;
  23285. lock.l_start = SHARED_FIRST;
  23286. lock.l_len = SHARED_SIZE;
  23287. if( unixFileLock(pFile, &lock) ){
  23288. /* In theory, the call to unixFileLock() cannot fail because another
  23289. ** process is holding an incompatible lock. If it does, this
  23290. ** indicates that the other process is not following the locking
  23291. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  23292. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  23293. ** an assert to fail). */
  23294. rc = SQLITE_IOERR_RDLOCK;
  23295. pFile->lastErrno = errno;
  23296. goto end_unlock;
  23297. }
  23298. }
  23299. }
  23300. lock.l_type = F_UNLCK;
  23301. lock.l_whence = SEEK_SET;
  23302. lock.l_start = PENDING_BYTE;
  23303. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  23304. if( unixFileLock(pFile, &lock)==0 ){
  23305. pInode->eFileLock = SHARED_LOCK;
  23306. }else{
  23307. rc = SQLITE_IOERR_UNLOCK;
  23308. pFile->lastErrno = errno;
  23309. goto end_unlock;
  23310. }
  23311. }
  23312. if( eFileLock==NO_LOCK ){
  23313. /* Decrement the shared lock counter. Release the lock using an
  23314. ** OS call only when all threads in this same process have released
  23315. ** the lock.
  23316. */
  23317. pInode->nShared--;
  23318. if( pInode->nShared==0 ){
  23319. lock.l_type = F_UNLCK;
  23320. lock.l_whence = SEEK_SET;
  23321. lock.l_start = lock.l_len = 0L;
  23322. if( unixFileLock(pFile, &lock)==0 ){
  23323. pInode->eFileLock = NO_LOCK;
  23324. }else{
  23325. rc = SQLITE_IOERR_UNLOCK;
  23326. pFile->lastErrno = errno;
  23327. pInode->eFileLock = NO_LOCK;
  23328. pFile->eFileLock = NO_LOCK;
  23329. }
  23330. }
  23331. /* Decrement the count of locks against this same file. When the
  23332. ** count reaches zero, close any other file descriptors whose close
  23333. ** was deferred because of outstanding locks.
  23334. */
  23335. pInode->nLock--;
  23336. assert( pInode->nLock>=0 );
  23337. if( pInode->nLock==0 ){
  23338. closePendingFds(pFile);
  23339. }
  23340. }
  23341. end_unlock:
  23342. unixLeaveMutex();
  23343. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  23344. return rc;
  23345. }
  23346. /*
  23347. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23348. ** must be either NO_LOCK or SHARED_LOCK.
  23349. **
  23350. ** If the locking level of the file descriptor is already at or below
  23351. ** the requested locking level, this routine is a no-op.
  23352. */
  23353. static int unixUnlock(sqlite3_file *id, int eFileLock){
  23354. return posixUnlock(id, eFileLock, 0);
  23355. }
  23356. /*
  23357. ** This function performs the parts of the "close file" operation
  23358. ** common to all locking schemes. It closes the directory and file
  23359. ** handles, if they are valid, and sets all fields of the unixFile
  23360. ** structure to 0.
  23361. **
  23362. ** It is *not* necessary to hold the mutex when this routine is called,
  23363. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  23364. ** vxworksReleaseFileId() routine.
  23365. */
  23366. static int closeUnixFile(sqlite3_file *id){
  23367. unixFile *pFile = (unixFile*)id;
  23368. if( pFile->h>=0 ){
  23369. robust_close(pFile, pFile->h, __LINE__);
  23370. pFile->h = -1;
  23371. }
  23372. #if OS_VXWORKS
  23373. if( pFile->pId ){
  23374. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  23375. osUnlink(pFile->pId->zCanonicalName);
  23376. }
  23377. vxworksReleaseFileId(pFile->pId);
  23378. pFile->pId = 0;
  23379. }
  23380. #endif
  23381. OSTRACE(("CLOSE %-3d\n", pFile->h));
  23382. OpenCounter(-1);
  23383. sqlite3_free(pFile->pUnused);
  23384. memset(pFile, 0, sizeof(unixFile));
  23385. return SQLITE_OK;
  23386. }
  23387. /*
  23388. ** Close a file.
  23389. */
  23390. static int unixClose(sqlite3_file *id){
  23391. int rc = SQLITE_OK;
  23392. unixFile *pFile = (unixFile *)id;
  23393. unixUnlock(id, NO_LOCK);
  23394. unixEnterMutex();
  23395. /* unixFile.pInode is always valid here. Otherwise, a different close
  23396. ** routine (e.g. nolockClose()) would be called instead.
  23397. */
  23398. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  23399. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  23400. /* If there are outstanding locks, do not actually close the file just
  23401. ** yet because that would clear those locks. Instead, add the file
  23402. ** descriptor to pInode->pUnused list. It will be automatically closed
  23403. ** when the last lock is cleared.
  23404. */
  23405. setPendingFd(pFile);
  23406. }
  23407. releaseInodeInfo(pFile);
  23408. rc = closeUnixFile(id);
  23409. unixLeaveMutex();
  23410. return rc;
  23411. }
  23412. /************** End of the posix advisory lock implementation *****************
  23413. ******************************************************************************/
  23414. /******************************************************************************
  23415. ****************************** No-op Locking **********************************
  23416. **
  23417. ** Of the various locking implementations available, this is by far the
  23418. ** simplest: locking is ignored. No attempt is made to lock the database
  23419. ** file for reading or writing.
  23420. **
  23421. ** This locking mode is appropriate for use on read-only databases
  23422. ** (ex: databases that are burned into CD-ROM, for example.) It can
  23423. ** also be used if the application employs some external mechanism to
  23424. ** prevent simultaneous access of the same database by two or more
  23425. ** database connections. But there is a serious risk of database
  23426. ** corruption if this locking mode is used in situations where multiple
  23427. ** database connections are accessing the same database file at the same
  23428. ** time and one or more of those connections are writing.
  23429. */
  23430. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  23431. UNUSED_PARAMETER(NotUsed);
  23432. *pResOut = 0;
  23433. return SQLITE_OK;
  23434. }
  23435. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  23436. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23437. return SQLITE_OK;
  23438. }
  23439. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  23440. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  23441. return SQLITE_OK;
  23442. }
  23443. /*
  23444. ** Close the file.
  23445. */
  23446. static int nolockClose(sqlite3_file *id) {
  23447. return closeUnixFile(id);
  23448. }
  23449. /******************* End of the no-op lock implementation *********************
  23450. ******************************************************************************/
  23451. /******************************************************************************
  23452. ************************* Begin dot-file Locking ******************************
  23453. **
  23454. ** The dotfile locking implementation uses the existance of separate lock
  23455. ** files (really a directory) to control access to the database. This works
  23456. ** on just about every filesystem imaginable. But there are serious downsides:
  23457. **
  23458. ** (1) There is zero concurrency. A single reader blocks all other
  23459. ** connections from reading or writing the database.
  23460. **
  23461. ** (2) An application crash or power loss can leave stale lock files
  23462. ** sitting around that need to be cleared manually.
  23463. **
  23464. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  23465. ** other locking strategy is available.
  23466. **
  23467. ** Dotfile locking works by creating a subdirectory in the same directory as
  23468. ** the database and with the same name but with a ".lock" extension added.
  23469. ** The existance of a lock directory implies an EXCLUSIVE lock. All other
  23470. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  23471. */
  23472. /*
  23473. ** The file suffix added to the data base filename in order to create the
  23474. ** lock directory.
  23475. */
  23476. #define DOTLOCK_SUFFIX ".lock"
  23477. /*
  23478. ** This routine checks if there is a RESERVED lock held on the specified
  23479. ** file by this or any other process. If such a lock is held, set *pResOut
  23480. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23481. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23482. **
  23483. ** In dotfile locking, either a lock exists or it does not. So in this
  23484. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  23485. ** is held on the file and false if the file is unlocked.
  23486. */
  23487. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  23488. int rc = SQLITE_OK;
  23489. int reserved = 0;
  23490. unixFile *pFile = (unixFile*)id;
  23491. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23492. assert( pFile );
  23493. /* Check if a thread in this process holds such a lock */
  23494. if( pFile->eFileLock>SHARED_LOCK ){
  23495. /* Either this connection or some other connection in the same process
  23496. ** holds a lock on the file. No need to check further. */
  23497. reserved = 1;
  23498. }else{
  23499. /* The lock is held if and only if the lockfile exists */
  23500. const char *zLockFile = (const char*)pFile->lockingContext;
  23501. reserved = osAccess(zLockFile, 0)==0;
  23502. }
  23503. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  23504. *pResOut = reserved;
  23505. return rc;
  23506. }
  23507. /*
  23508. ** Lock the file with the lock specified by parameter eFileLock - one
  23509. ** of the following:
  23510. **
  23511. ** (1) SHARED_LOCK
  23512. ** (2) RESERVED_LOCK
  23513. ** (3) PENDING_LOCK
  23514. ** (4) EXCLUSIVE_LOCK
  23515. **
  23516. ** Sometimes when requesting one lock state, additional lock states
  23517. ** are inserted in between. The locking might fail on one of the later
  23518. ** transitions leaving the lock state different from what it started but
  23519. ** still short of its goal. The following chart shows the allowed
  23520. ** transitions and the inserted intermediate states:
  23521. **
  23522. ** UNLOCKED -> SHARED
  23523. ** SHARED -> RESERVED
  23524. ** SHARED -> (PENDING) -> EXCLUSIVE
  23525. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23526. ** PENDING -> EXCLUSIVE
  23527. **
  23528. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23529. ** routine to lower a locking level.
  23530. **
  23531. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  23532. ** But we track the other locking levels internally.
  23533. */
  23534. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  23535. unixFile *pFile = (unixFile*)id;
  23536. char *zLockFile = (char *)pFile->lockingContext;
  23537. int rc = SQLITE_OK;
  23538. /* If we have any lock, then the lock file already exists. All we have
  23539. ** to do is adjust our internal record of the lock level.
  23540. */
  23541. if( pFile->eFileLock > NO_LOCK ){
  23542. pFile->eFileLock = eFileLock;
  23543. /* Always update the timestamp on the old file */
  23544. #ifdef HAVE_UTIME
  23545. utime(zLockFile, NULL);
  23546. #else
  23547. utimes(zLockFile, NULL);
  23548. #endif
  23549. return SQLITE_OK;
  23550. }
  23551. /* grab an exclusive lock */
  23552. rc = osMkdir(zLockFile, 0777);
  23553. if( rc<0 ){
  23554. /* failed to open/create the lock directory */
  23555. int tErrno = errno;
  23556. if( EEXIST == tErrno ){
  23557. rc = SQLITE_BUSY;
  23558. } else {
  23559. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23560. if( IS_LOCK_ERROR(rc) ){
  23561. pFile->lastErrno = tErrno;
  23562. }
  23563. }
  23564. return rc;
  23565. }
  23566. /* got it, set the type and return ok */
  23567. pFile->eFileLock = eFileLock;
  23568. return rc;
  23569. }
  23570. /*
  23571. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23572. ** must be either NO_LOCK or SHARED_LOCK.
  23573. **
  23574. ** If the locking level of the file descriptor is already at or below
  23575. ** the requested locking level, this routine is a no-op.
  23576. **
  23577. ** When the locking level reaches NO_LOCK, delete the lock file.
  23578. */
  23579. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  23580. unixFile *pFile = (unixFile*)id;
  23581. char *zLockFile = (char *)pFile->lockingContext;
  23582. int rc;
  23583. assert( pFile );
  23584. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  23585. pFile->eFileLock, getpid()));
  23586. assert( eFileLock<=SHARED_LOCK );
  23587. /* no-op if possible */
  23588. if( pFile->eFileLock==eFileLock ){
  23589. return SQLITE_OK;
  23590. }
  23591. /* To downgrade to shared, simply update our internal notion of the
  23592. ** lock state. No need to mess with the file on disk.
  23593. */
  23594. if( eFileLock==SHARED_LOCK ){
  23595. pFile->eFileLock = SHARED_LOCK;
  23596. return SQLITE_OK;
  23597. }
  23598. /* To fully unlock the database, delete the lock file */
  23599. assert( eFileLock==NO_LOCK );
  23600. rc = osRmdir(zLockFile);
  23601. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  23602. if( rc<0 ){
  23603. int tErrno = errno;
  23604. rc = 0;
  23605. if( ENOENT != tErrno ){
  23606. rc = SQLITE_IOERR_UNLOCK;
  23607. }
  23608. if( IS_LOCK_ERROR(rc) ){
  23609. pFile->lastErrno = tErrno;
  23610. }
  23611. return rc;
  23612. }
  23613. pFile->eFileLock = NO_LOCK;
  23614. return SQLITE_OK;
  23615. }
  23616. /*
  23617. ** Close a file. Make sure the lock has been released before closing.
  23618. */
  23619. static int dotlockClose(sqlite3_file *id) {
  23620. int rc = SQLITE_OK;
  23621. if( id ){
  23622. unixFile *pFile = (unixFile*)id;
  23623. dotlockUnlock(id, NO_LOCK);
  23624. sqlite3_free(pFile->lockingContext);
  23625. rc = closeUnixFile(id);
  23626. }
  23627. return rc;
  23628. }
  23629. /****************** End of the dot-file lock implementation *******************
  23630. ******************************************************************************/
  23631. /******************************************************************************
  23632. ************************** Begin flock Locking ********************************
  23633. **
  23634. ** Use the flock() system call to do file locking.
  23635. **
  23636. ** flock() locking is like dot-file locking in that the various
  23637. ** fine-grain locking levels supported by SQLite are collapsed into
  23638. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  23639. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  23640. ** still works when you do this, but concurrency is reduced since
  23641. ** only a single process can be reading the database at a time.
  23642. **
  23643. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  23644. ** compiling for VXWORKS.
  23645. */
  23646. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  23647. /*
  23648. ** Retry flock() calls that fail with EINTR
  23649. */
  23650. #ifdef EINTR
  23651. static int robust_flock(int fd, int op){
  23652. int rc;
  23653. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  23654. return rc;
  23655. }
  23656. #else
  23657. # define robust_flock(a,b) flock(a,b)
  23658. #endif
  23659. /*
  23660. ** This routine checks if there is a RESERVED lock held on the specified
  23661. ** file by this or any other process. If such a lock is held, set *pResOut
  23662. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23663. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23664. */
  23665. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  23666. int rc = SQLITE_OK;
  23667. int reserved = 0;
  23668. unixFile *pFile = (unixFile*)id;
  23669. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23670. assert( pFile );
  23671. /* Check if a thread in this process holds such a lock */
  23672. if( pFile->eFileLock>SHARED_LOCK ){
  23673. reserved = 1;
  23674. }
  23675. /* Otherwise see if some other process holds it. */
  23676. if( !reserved ){
  23677. /* attempt to get the lock */
  23678. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  23679. if( !lrc ){
  23680. /* got the lock, unlock it */
  23681. lrc = robust_flock(pFile->h, LOCK_UN);
  23682. if ( lrc ) {
  23683. int tErrno = errno;
  23684. /* unlock failed with an error */
  23685. lrc = SQLITE_IOERR_UNLOCK;
  23686. if( IS_LOCK_ERROR(lrc) ){
  23687. pFile->lastErrno = tErrno;
  23688. rc = lrc;
  23689. }
  23690. }
  23691. } else {
  23692. int tErrno = errno;
  23693. reserved = 1;
  23694. /* someone else might have it reserved */
  23695. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23696. if( IS_LOCK_ERROR(lrc) ){
  23697. pFile->lastErrno = tErrno;
  23698. rc = lrc;
  23699. }
  23700. }
  23701. }
  23702. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  23703. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  23704. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  23705. rc = SQLITE_OK;
  23706. reserved=1;
  23707. }
  23708. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  23709. *pResOut = reserved;
  23710. return rc;
  23711. }
  23712. /*
  23713. ** Lock the file with the lock specified by parameter eFileLock - one
  23714. ** of the following:
  23715. **
  23716. ** (1) SHARED_LOCK
  23717. ** (2) RESERVED_LOCK
  23718. ** (3) PENDING_LOCK
  23719. ** (4) EXCLUSIVE_LOCK
  23720. **
  23721. ** Sometimes when requesting one lock state, additional lock states
  23722. ** are inserted in between. The locking might fail on one of the later
  23723. ** transitions leaving the lock state different from what it started but
  23724. ** still short of its goal. The following chart shows the allowed
  23725. ** transitions and the inserted intermediate states:
  23726. **
  23727. ** UNLOCKED -> SHARED
  23728. ** SHARED -> RESERVED
  23729. ** SHARED -> (PENDING) -> EXCLUSIVE
  23730. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23731. ** PENDING -> EXCLUSIVE
  23732. **
  23733. ** flock() only really support EXCLUSIVE locks. We track intermediate
  23734. ** lock states in the sqlite3_file structure, but all locks SHARED or
  23735. ** above are really EXCLUSIVE locks and exclude all other processes from
  23736. ** access the file.
  23737. **
  23738. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23739. ** routine to lower a locking level.
  23740. */
  23741. static int flockLock(sqlite3_file *id, int eFileLock) {
  23742. int rc = SQLITE_OK;
  23743. unixFile *pFile = (unixFile*)id;
  23744. assert( pFile );
  23745. /* if we already have a lock, it is exclusive.
  23746. ** Just adjust level and punt on outta here. */
  23747. if (pFile->eFileLock > NO_LOCK) {
  23748. pFile->eFileLock = eFileLock;
  23749. return SQLITE_OK;
  23750. }
  23751. /* grab an exclusive lock */
  23752. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  23753. int tErrno = errno;
  23754. /* didn't get, must be busy */
  23755. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23756. if( IS_LOCK_ERROR(rc) ){
  23757. pFile->lastErrno = tErrno;
  23758. }
  23759. } else {
  23760. /* got it, set the type and return ok */
  23761. pFile->eFileLock = eFileLock;
  23762. }
  23763. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  23764. rc==SQLITE_OK ? "ok" : "failed"));
  23765. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  23766. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  23767. rc = SQLITE_BUSY;
  23768. }
  23769. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  23770. return rc;
  23771. }
  23772. /*
  23773. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23774. ** must be either NO_LOCK or SHARED_LOCK.
  23775. **
  23776. ** If the locking level of the file descriptor is already at or below
  23777. ** the requested locking level, this routine is a no-op.
  23778. */
  23779. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  23780. unixFile *pFile = (unixFile*)id;
  23781. assert( pFile );
  23782. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  23783. pFile->eFileLock, getpid()));
  23784. assert( eFileLock<=SHARED_LOCK );
  23785. /* no-op if possible */
  23786. if( pFile->eFileLock==eFileLock ){
  23787. return SQLITE_OK;
  23788. }
  23789. /* shared can just be set because we always have an exclusive */
  23790. if (eFileLock==SHARED_LOCK) {
  23791. pFile->eFileLock = eFileLock;
  23792. return SQLITE_OK;
  23793. }
  23794. /* no, really, unlock. */
  23795. if( robust_flock(pFile->h, LOCK_UN) ){
  23796. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  23797. return SQLITE_OK;
  23798. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  23799. return SQLITE_IOERR_UNLOCK;
  23800. }else{
  23801. pFile->eFileLock = NO_LOCK;
  23802. return SQLITE_OK;
  23803. }
  23804. }
  23805. /*
  23806. ** Close a file.
  23807. */
  23808. static int flockClose(sqlite3_file *id) {
  23809. int rc = SQLITE_OK;
  23810. if( id ){
  23811. flockUnlock(id, NO_LOCK);
  23812. rc = closeUnixFile(id);
  23813. }
  23814. return rc;
  23815. }
  23816. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  23817. /******************* End of the flock lock implementation *********************
  23818. ******************************************************************************/
  23819. /******************************************************************************
  23820. ************************ Begin Named Semaphore Locking ************************
  23821. **
  23822. ** Named semaphore locking is only supported on VxWorks.
  23823. **
  23824. ** Semaphore locking is like dot-lock and flock in that it really only
  23825. ** supports EXCLUSIVE locking. Only a single process can read or write
  23826. ** the database file at a time. This reduces potential concurrency, but
  23827. ** makes the lock implementation much easier.
  23828. */
  23829. #if OS_VXWORKS
  23830. /*
  23831. ** This routine checks if there is a RESERVED lock held on the specified
  23832. ** file by this or any other process. If such a lock is held, set *pResOut
  23833. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23834. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23835. */
  23836. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  23837. int rc = SQLITE_OK;
  23838. int reserved = 0;
  23839. unixFile *pFile = (unixFile*)id;
  23840. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23841. assert( pFile );
  23842. /* Check if a thread in this process holds such a lock */
  23843. if( pFile->eFileLock>SHARED_LOCK ){
  23844. reserved = 1;
  23845. }
  23846. /* Otherwise see if some other process holds it. */
  23847. if( !reserved ){
  23848. sem_t *pSem = pFile->pInode->pSem;
  23849. struct stat statBuf;
  23850. if( sem_trywait(pSem)==-1 ){
  23851. int tErrno = errno;
  23852. if( EAGAIN != tErrno ){
  23853. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  23854. pFile->lastErrno = tErrno;
  23855. } else {
  23856. /* someone else has the lock when we are in NO_LOCK */
  23857. reserved = (pFile->eFileLock < SHARED_LOCK);
  23858. }
  23859. }else{
  23860. /* we could have it if we want it */
  23861. sem_post(pSem);
  23862. }
  23863. }
  23864. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  23865. *pResOut = reserved;
  23866. return rc;
  23867. }
  23868. /*
  23869. ** Lock the file with the lock specified by parameter eFileLock - one
  23870. ** of the following:
  23871. **
  23872. ** (1) SHARED_LOCK
  23873. ** (2) RESERVED_LOCK
  23874. ** (3) PENDING_LOCK
  23875. ** (4) EXCLUSIVE_LOCK
  23876. **
  23877. ** Sometimes when requesting one lock state, additional lock states
  23878. ** are inserted in between. The locking might fail on one of the later
  23879. ** transitions leaving the lock state different from what it started but
  23880. ** still short of its goal. The following chart shows the allowed
  23881. ** transitions and the inserted intermediate states:
  23882. **
  23883. ** UNLOCKED -> SHARED
  23884. ** SHARED -> RESERVED
  23885. ** SHARED -> (PENDING) -> EXCLUSIVE
  23886. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23887. ** PENDING -> EXCLUSIVE
  23888. **
  23889. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  23890. ** lock states in the sqlite3_file structure, but all locks SHARED or
  23891. ** above are really EXCLUSIVE locks and exclude all other processes from
  23892. ** access the file.
  23893. **
  23894. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23895. ** routine to lower a locking level.
  23896. */
  23897. static int semLock(sqlite3_file *id, int eFileLock) {
  23898. unixFile *pFile = (unixFile*)id;
  23899. int fd;
  23900. sem_t *pSem = pFile->pInode->pSem;
  23901. int rc = SQLITE_OK;
  23902. /* if we already have a lock, it is exclusive.
  23903. ** Just adjust level and punt on outta here. */
  23904. if (pFile->eFileLock > NO_LOCK) {
  23905. pFile->eFileLock = eFileLock;
  23906. rc = SQLITE_OK;
  23907. goto sem_end_lock;
  23908. }
  23909. /* lock semaphore now but bail out when already locked. */
  23910. if( sem_trywait(pSem)==-1 ){
  23911. rc = SQLITE_BUSY;
  23912. goto sem_end_lock;
  23913. }
  23914. /* got it, set the type and return ok */
  23915. pFile->eFileLock = eFileLock;
  23916. sem_end_lock:
  23917. return rc;
  23918. }
  23919. /*
  23920. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23921. ** must be either NO_LOCK or SHARED_LOCK.
  23922. **
  23923. ** If the locking level of the file descriptor is already at or below
  23924. ** the requested locking level, this routine is a no-op.
  23925. */
  23926. static int semUnlock(sqlite3_file *id, int eFileLock) {
  23927. unixFile *pFile = (unixFile*)id;
  23928. sem_t *pSem = pFile->pInode->pSem;
  23929. assert( pFile );
  23930. assert( pSem );
  23931. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  23932. pFile->eFileLock, getpid()));
  23933. assert( eFileLock<=SHARED_LOCK );
  23934. /* no-op if possible */
  23935. if( pFile->eFileLock==eFileLock ){
  23936. return SQLITE_OK;
  23937. }
  23938. /* shared can just be set because we always have an exclusive */
  23939. if (eFileLock==SHARED_LOCK) {
  23940. pFile->eFileLock = eFileLock;
  23941. return SQLITE_OK;
  23942. }
  23943. /* no, really unlock. */
  23944. if ( sem_post(pSem)==-1 ) {
  23945. int rc, tErrno = errno;
  23946. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  23947. if( IS_LOCK_ERROR(rc) ){
  23948. pFile->lastErrno = tErrno;
  23949. }
  23950. return rc;
  23951. }
  23952. pFile->eFileLock = NO_LOCK;
  23953. return SQLITE_OK;
  23954. }
  23955. /*
  23956. ** Close a file.
  23957. */
  23958. static int semClose(sqlite3_file *id) {
  23959. if( id ){
  23960. unixFile *pFile = (unixFile*)id;
  23961. semUnlock(id, NO_LOCK);
  23962. assert( pFile );
  23963. unixEnterMutex();
  23964. releaseInodeInfo(pFile);
  23965. unixLeaveMutex();
  23966. closeUnixFile(id);
  23967. }
  23968. return SQLITE_OK;
  23969. }
  23970. #endif /* OS_VXWORKS */
  23971. /*
  23972. ** Named semaphore locking is only available on VxWorks.
  23973. **
  23974. *************** End of the named semaphore lock implementation ****************
  23975. ******************************************************************************/
  23976. /******************************************************************************
  23977. *************************** Begin AFP Locking *********************************
  23978. **
  23979. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  23980. ** on Apple Macintosh computers - both OS9 and OSX.
  23981. **
  23982. ** Third-party implementations of AFP are available. But this code here
  23983. ** only works on OSX.
  23984. */
  23985. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23986. /*
  23987. ** The afpLockingContext structure contains all afp lock specific state
  23988. */
  23989. typedef struct afpLockingContext afpLockingContext;
  23990. struct afpLockingContext {
  23991. int reserved;
  23992. const char *dbPath; /* Name of the open file */
  23993. };
  23994. struct ByteRangeLockPB2
  23995. {
  23996. unsigned long long offset; /* offset to first byte to lock */
  23997. unsigned long long length; /* nbr of bytes to lock */
  23998. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  23999. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24000. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24001. int fd; /* file desc to assoc this lock with */
  24002. };
  24003. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24004. /*
  24005. ** This is a utility for setting or clearing a bit-range lock on an
  24006. ** AFP filesystem.
  24007. **
  24008. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24009. */
  24010. static int afpSetLock(
  24011. const char *path, /* Name of the file to be locked or unlocked */
  24012. unixFile *pFile, /* Open file descriptor on path */
  24013. unsigned long long offset, /* First byte to be locked */
  24014. unsigned long long length, /* Number of bytes to lock */
  24015. int setLockFlag /* True to set lock. False to clear lock */
  24016. ){
  24017. struct ByteRangeLockPB2 pb;
  24018. int err;
  24019. pb.unLockFlag = setLockFlag ? 0 : 1;
  24020. pb.startEndFlag = 0;
  24021. pb.offset = offset;
  24022. pb.length = length;
  24023. pb.fd = pFile->h;
  24024. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24025. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24026. offset, length));
  24027. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24028. if ( err==-1 ) {
  24029. int rc;
  24030. int tErrno = errno;
  24031. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24032. path, tErrno, strerror(tErrno)));
  24033. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24034. rc = SQLITE_BUSY;
  24035. #else
  24036. rc = sqliteErrorFromPosixError(tErrno,
  24037. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24038. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24039. if( IS_LOCK_ERROR(rc) ){
  24040. pFile->lastErrno = tErrno;
  24041. }
  24042. return rc;
  24043. } else {
  24044. return SQLITE_OK;
  24045. }
  24046. }
  24047. /*
  24048. ** This routine checks if there is a RESERVED lock held on the specified
  24049. ** file by this or any other process. If such a lock is held, set *pResOut
  24050. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24051. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24052. */
  24053. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24054. int rc = SQLITE_OK;
  24055. int reserved = 0;
  24056. unixFile *pFile = (unixFile*)id;
  24057. afpLockingContext *context;
  24058. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24059. assert( pFile );
  24060. context = (afpLockingContext *) pFile->lockingContext;
  24061. if( context->reserved ){
  24062. *pResOut = 1;
  24063. return SQLITE_OK;
  24064. }
  24065. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24066. /* Check if a thread in this process holds such a lock */
  24067. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24068. reserved = 1;
  24069. }
  24070. /* Otherwise see if some other process holds it.
  24071. */
  24072. if( !reserved ){
  24073. /* lock the RESERVED byte */
  24074. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24075. if( SQLITE_OK==lrc ){
  24076. /* if we succeeded in taking the reserved lock, unlock it to restore
  24077. ** the original state */
  24078. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24079. } else {
  24080. /* if we failed to get the lock then someone else must have it */
  24081. reserved = 1;
  24082. }
  24083. if( IS_LOCK_ERROR(lrc) ){
  24084. rc=lrc;
  24085. }
  24086. }
  24087. unixLeaveMutex();
  24088. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  24089. *pResOut = reserved;
  24090. return rc;
  24091. }
  24092. /*
  24093. ** Lock the file with the lock specified by parameter eFileLock - one
  24094. ** of the following:
  24095. **
  24096. ** (1) SHARED_LOCK
  24097. ** (2) RESERVED_LOCK
  24098. ** (3) PENDING_LOCK
  24099. ** (4) EXCLUSIVE_LOCK
  24100. **
  24101. ** Sometimes when requesting one lock state, additional lock states
  24102. ** are inserted in between. The locking might fail on one of the later
  24103. ** transitions leaving the lock state different from what it started but
  24104. ** still short of its goal. The following chart shows the allowed
  24105. ** transitions and the inserted intermediate states:
  24106. **
  24107. ** UNLOCKED -> SHARED
  24108. ** SHARED -> RESERVED
  24109. ** SHARED -> (PENDING) -> EXCLUSIVE
  24110. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24111. ** PENDING -> EXCLUSIVE
  24112. **
  24113. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24114. ** routine to lower a locking level.
  24115. */
  24116. static int afpLock(sqlite3_file *id, int eFileLock){
  24117. int rc = SQLITE_OK;
  24118. unixFile *pFile = (unixFile*)id;
  24119. unixInodeInfo *pInode = pFile->pInode;
  24120. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24121. assert( pFile );
  24122. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  24123. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24124. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  24125. /* If there is already a lock of this type or more restrictive on the
  24126. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  24127. ** unixEnterMutex() hasn't been called yet.
  24128. */
  24129. if( pFile->eFileLock>=eFileLock ){
  24130. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  24131. azFileLock(eFileLock)));
  24132. return SQLITE_OK;
  24133. }
  24134. /* Make sure the locking sequence is correct
  24135. ** (1) We never move from unlocked to anything higher than shared lock.
  24136. ** (2) SQLite never explicitly requests a pendig lock.
  24137. ** (3) A shared lock is always held when a reserve lock is requested.
  24138. */
  24139. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24140. assert( eFileLock!=PENDING_LOCK );
  24141. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24142. /* This mutex is needed because pFile->pInode is shared across threads
  24143. */
  24144. unixEnterMutex();
  24145. pInode = pFile->pInode;
  24146. /* If some thread using this PID has a lock via a different unixFile*
  24147. ** handle that precludes the requested lock, return BUSY.
  24148. */
  24149. if( (pFile->eFileLock!=pInode->eFileLock &&
  24150. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24151. ){
  24152. rc = SQLITE_BUSY;
  24153. goto afp_end_lock;
  24154. }
  24155. /* If a SHARED lock is requested, and some thread using this PID already
  24156. ** has a SHARED or RESERVED lock, then increment reference counts and
  24157. ** return SQLITE_OK.
  24158. */
  24159. if( eFileLock==SHARED_LOCK &&
  24160. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24161. assert( eFileLock==SHARED_LOCK );
  24162. assert( pFile->eFileLock==0 );
  24163. assert( pInode->nShared>0 );
  24164. pFile->eFileLock = SHARED_LOCK;
  24165. pInode->nShared++;
  24166. pInode->nLock++;
  24167. goto afp_end_lock;
  24168. }
  24169. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24170. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24171. ** be released.
  24172. */
  24173. if( eFileLock==SHARED_LOCK
  24174. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24175. ){
  24176. int failed;
  24177. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  24178. if (failed) {
  24179. rc = failed;
  24180. goto afp_end_lock;
  24181. }
  24182. }
  24183. /* If control gets to this point, then actually go ahead and make
  24184. ** operating system calls for the specified lock.
  24185. */
  24186. if( eFileLock==SHARED_LOCK ){
  24187. int lrc1, lrc2, lrc1Errno = 0;
  24188. long lk, mask;
  24189. assert( pInode->nShared==0 );
  24190. assert( pInode->eFileLock==0 );
  24191. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  24192. /* Now get the read-lock SHARED_LOCK */
  24193. /* note that the quality of the randomness doesn't matter that much */
  24194. lk = random();
  24195. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  24196. lrc1 = afpSetLock(context->dbPath, pFile,
  24197. SHARED_FIRST+pInode->sharedByte, 1, 1);
  24198. if( IS_LOCK_ERROR(lrc1) ){
  24199. lrc1Errno = pFile->lastErrno;
  24200. }
  24201. /* Drop the temporary PENDING lock */
  24202. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24203. if( IS_LOCK_ERROR(lrc1) ) {
  24204. pFile->lastErrno = lrc1Errno;
  24205. rc = lrc1;
  24206. goto afp_end_lock;
  24207. } else if( IS_LOCK_ERROR(lrc2) ){
  24208. rc = lrc2;
  24209. goto afp_end_lock;
  24210. } else if( lrc1 != SQLITE_OK ) {
  24211. rc = lrc1;
  24212. } else {
  24213. pFile->eFileLock = SHARED_LOCK;
  24214. pInode->nLock++;
  24215. pInode->nShared = 1;
  24216. }
  24217. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24218. /* We are trying for an exclusive lock but another thread in this
  24219. ** same process is still holding a shared lock. */
  24220. rc = SQLITE_BUSY;
  24221. }else{
  24222. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24223. ** assumed that there is a SHARED or greater lock on the file
  24224. ** already.
  24225. */
  24226. int failed = 0;
  24227. assert( 0!=pFile->eFileLock );
  24228. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  24229. /* Acquire a RESERVED lock */
  24230. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24231. if( !failed ){
  24232. context->reserved = 1;
  24233. }
  24234. }
  24235. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  24236. /* Acquire an EXCLUSIVE lock */
  24237. /* Remove the shared lock before trying the range. we'll need to
  24238. ** reestablish the shared lock if we can't get the afpUnlock
  24239. */
  24240. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  24241. pInode->sharedByte, 1, 0)) ){
  24242. int failed2 = SQLITE_OK;
  24243. /* now attemmpt to get the exclusive lock range */
  24244. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  24245. SHARED_SIZE, 1);
  24246. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  24247. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  24248. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  24249. ** a critical I/O error
  24250. */
  24251. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  24252. SQLITE_IOERR_LOCK;
  24253. goto afp_end_lock;
  24254. }
  24255. }else{
  24256. rc = failed;
  24257. }
  24258. }
  24259. if( failed ){
  24260. rc = failed;
  24261. }
  24262. }
  24263. if( rc==SQLITE_OK ){
  24264. pFile->eFileLock = eFileLock;
  24265. pInode->eFileLock = eFileLock;
  24266. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24267. pFile->eFileLock = PENDING_LOCK;
  24268. pInode->eFileLock = PENDING_LOCK;
  24269. }
  24270. afp_end_lock:
  24271. unixLeaveMutex();
  24272. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  24273. rc==SQLITE_OK ? "ok" : "failed"));
  24274. return rc;
  24275. }
  24276. /*
  24277. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24278. ** must be either NO_LOCK or SHARED_LOCK.
  24279. **
  24280. ** If the locking level of the file descriptor is already at or below
  24281. ** the requested locking level, this routine is a no-op.
  24282. */
  24283. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  24284. int rc = SQLITE_OK;
  24285. unixFile *pFile = (unixFile*)id;
  24286. unixInodeInfo *pInode;
  24287. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24288. int skipShared = 0;
  24289. #ifdef SQLITE_TEST
  24290. int h = pFile->h;
  24291. #endif
  24292. assert( pFile );
  24293. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  24294. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  24295. getpid()));
  24296. assert( eFileLock<=SHARED_LOCK );
  24297. if( pFile->eFileLock<=eFileLock ){
  24298. return SQLITE_OK;
  24299. }
  24300. unixEnterMutex();
  24301. pInode = pFile->pInode;
  24302. assert( pInode->nShared!=0 );
  24303. if( pFile->eFileLock>SHARED_LOCK ){
  24304. assert( pInode->eFileLock==pFile->eFileLock );
  24305. SimulateIOErrorBenign(1);
  24306. SimulateIOError( h=(-1) )
  24307. SimulateIOErrorBenign(0);
  24308. #ifdef SQLITE_DEBUG
  24309. /* When reducing a lock such that other processes can start
  24310. ** reading the database file again, make sure that the
  24311. ** transaction counter was updated if any part of the database
  24312. ** file changed. If the transaction counter is not updated,
  24313. ** other connections to the same file might not realize that
  24314. ** the file has changed and hence might not know to flush their
  24315. ** cache. The use of a stale cache can lead to database corruption.
  24316. */
  24317. assert( pFile->inNormalWrite==0
  24318. || pFile->dbUpdate==0
  24319. || pFile->transCntrChng==1 );
  24320. pFile->inNormalWrite = 0;
  24321. #endif
  24322. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  24323. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  24324. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  24325. /* only re-establish the shared lock if necessary */
  24326. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24327. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  24328. } else {
  24329. skipShared = 1;
  24330. }
  24331. }
  24332. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  24333. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24334. }
  24335. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  24336. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24337. if( !rc ){
  24338. context->reserved = 0;
  24339. }
  24340. }
  24341. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  24342. pInode->eFileLock = SHARED_LOCK;
  24343. }
  24344. }
  24345. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  24346. /* Decrement the shared lock counter. Release the lock using an
  24347. ** OS call only when all threads in this same process have released
  24348. ** the lock.
  24349. */
  24350. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  24351. pInode->nShared--;
  24352. if( pInode->nShared==0 ){
  24353. SimulateIOErrorBenign(1);
  24354. SimulateIOError( h=(-1) )
  24355. SimulateIOErrorBenign(0);
  24356. if( !skipShared ){
  24357. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  24358. }
  24359. if( !rc ){
  24360. pInode->eFileLock = NO_LOCK;
  24361. pFile->eFileLock = NO_LOCK;
  24362. }
  24363. }
  24364. if( rc==SQLITE_OK ){
  24365. pInode->nLock--;
  24366. assert( pInode->nLock>=0 );
  24367. if( pInode->nLock==0 ){
  24368. closePendingFds(pFile);
  24369. }
  24370. }
  24371. }
  24372. unixLeaveMutex();
  24373. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24374. return rc;
  24375. }
  24376. /*
  24377. ** Close a file & cleanup AFP specific locking context
  24378. */
  24379. static int afpClose(sqlite3_file *id) {
  24380. int rc = SQLITE_OK;
  24381. if( id ){
  24382. unixFile *pFile = (unixFile*)id;
  24383. afpUnlock(id, NO_LOCK);
  24384. unixEnterMutex();
  24385. if( pFile->pInode && pFile->pInode->nLock ){
  24386. /* If there are outstanding locks, do not actually close the file just
  24387. ** yet because that would clear those locks. Instead, add the file
  24388. ** descriptor to pInode->aPending. It will be automatically closed when
  24389. ** the last lock is cleared.
  24390. */
  24391. setPendingFd(pFile);
  24392. }
  24393. releaseInodeInfo(pFile);
  24394. sqlite3_free(pFile->lockingContext);
  24395. rc = closeUnixFile(id);
  24396. unixLeaveMutex();
  24397. }
  24398. return rc;
  24399. }
  24400. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24401. /*
  24402. ** The code above is the AFP lock implementation. The code is specific
  24403. ** to MacOSX and does not work on other unix platforms. No alternative
  24404. ** is available. If you don't compile for a mac, then the "unix-afp"
  24405. ** VFS is not available.
  24406. **
  24407. ********************* End of the AFP lock implementation **********************
  24408. ******************************************************************************/
  24409. /******************************************************************************
  24410. *************************** Begin NFS Locking ********************************/
  24411. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24412. /*
  24413. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24414. ** must be either NO_LOCK or SHARED_LOCK.
  24415. **
  24416. ** If the locking level of the file descriptor is already at or below
  24417. ** the requested locking level, this routine is a no-op.
  24418. */
  24419. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  24420. return posixUnlock(id, eFileLock, 1);
  24421. }
  24422. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24423. /*
  24424. ** The code above is the NFS lock implementation. The code is specific
  24425. ** to MacOSX and does not work on other unix platforms. No alternative
  24426. ** is available.
  24427. **
  24428. ********************* End of the NFS lock implementation **********************
  24429. ******************************************************************************/
  24430. /******************************************************************************
  24431. **************** Non-locking sqlite3_file methods *****************************
  24432. **
  24433. ** The next division contains implementations for all methods of the
  24434. ** sqlite3_file object other than the locking methods. The locking
  24435. ** methods were defined in divisions above (one locking method per
  24436. ** division). Those methods that are common to all locking modes
  24437. ** are gather together into this division.
  24438. */
  24439. /*
  24440. ** Seek to the offset passed as the second argument, then read cnt
  24441. ** bytes into pBuf. Return the number of bytes actually read.
  24442. **
  24443. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  24444. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  24445. ** one system to another. Since SQLite does not define USE_PREAD
  24446. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  24447. ** See tickets #2741 and #2681.
  24448. **
  24449. ** To avoid stomping the errno value on a failed read the lastErrno value
  24450. ** is set before returning.
  24451. */
  24452. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  24453. int got;
  24454. int prior = 0;
  24455. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  24456. i64 newOffset;
  24457. #endif
  24458. TIMER_START;
  24459. assert( cnt==(cnt&0x1ffff) );
  24460. cnt &= 0x1ffff;
  24461. do{
  24462. #if defined(USE_PREAD)
  24463. got = osPread(id->h, pBuf, cnt, offset);
  24464. SimulateIOError( got = -1 );
  24465. #elif defined(USE_PREAD64)
  24466. got = osPread64(id->h, pBuf, cnt, offset);
  24467. SimulateIOError( got = -1 );
  24468. #else
  24469. newOffset = lseek(id->h, offset, SEEK_SET);
  24470. SimulateIOError( newOffset-- );
  24471. if( newOffset!=offset ){
  24472. if( newOffset == -1 ){
  24473. ((unixFile*)id)->lastErrno = errno;
  24474. }else{
  24475. ((unixFile*)id)->lastErrno = 0;
  24476. }
  24477. return -1;
  24478. }
  24479. got = osRead(id->h, pBuf, cnt);
  24480. #endif
  24481. if( got==cnt ) break;
  24482. if( got<0 ){
  24483. if( errno==EINTR ){ got = 1; continue; }
  24484. prior = 0;
  24485. ((unixFile*)id)->lastErrno = errno;
  24486. break;
  24487. }else if( got>0 ){
  24488. cnt -= got;
  24489. offset += got;
  24490. prior += got;
  24491. pBuf = (void*)(got + (char*)pBuf);
  24492. }
  24493. }while( got>0 );
  24494. TIMER_END;
  24495. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  24496. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  24497. return got+prior;
  24498. }
  24499. /*
  24500. ** Read data from a file into a buffer. Return SQLITE_OK if all
  24501. ** bytes were read successfully and SQLITE_IOERR if anything goes
  24502. ** wrong.
  24503. */
  24504. static int unixRead(
  24505. sqlite3_file *id,
  24506. void *pBuf,
  24507. int amt,
  24508. sqlite3_int64 offset
  24509. ){
  24510. unixFile *pFile = (unixFile *)id;
  24511. int got;
  24512. assert( id );
  24513. /* If this is a database file (not a journal, master-journal or temp
  24514. ** file), the bytes in the locking range should never be read or written. */
  24515. #if 0
  24516. assert( pFile->pUnused==0
  24517. || offset>=PENDING_BYTE+512
  24518. || offset+amt<=PENDING_BYTE
  24519. );
  24520. #endif
  24521. got = seekAndRead(pFile, offset, pBuf, amt);
  24522. if( got==amt ){
  24523. return SQLITE_OK;
  24524. }else if( got<0 ){
  24525. /* lastErrno set by seekAndRead */
  24526. return SQLITE_IOERR_READ;
  24527. }else{
  24528. pFile->lastErrno = 0; /* not a system error */
  24529. /* Unread parts of the buffer must be zero-filled */
  24530. memset(&((char*)pBuf)[got], 0, amt-got);
  24531. return SQLITE_IOERR_SHORT_READ;
  24532. }
  24533. }
  24534. /*
  24535. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  24536. ** Return the number of bytes actually read. Update the offset.
  24537. **
  24538. ** To avoid stomping the errno value on a failed write the lastErrno value
  24539. ** is set before returning.
  24540. */
  24541. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  24542. int got;
  24543. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  24544. i64 newOffset;
  24545. #endif
  24546. assert( cnt==(cnt&0x1ffff) );
  24547. cnt &= 0x1ffff;
  24548. TIMER_START;
  24549. #if defined(USE_PREAD)
  24550. do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
  24551. #elif defined(USE_PREAD64)
  24552. do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
  24553. #else
  24554. do{
  24555. newOffset = lseek(id->h, offset, SEEK_SET);
  24556. SimulateIOError( newOffset-- );
  24557. if( newOffset!=offset ){
  24558. if( newOffset == -1 ){
  24559. ((unixFile*)id)->lastErrno = errno;
  24560. }else{
  24561. ((unixFile*)id)->lastErrno = 0;
  24562. }
  24563. return -1;
  24564. }
  24565. got = osWrite(id->h, pBuf, cnt);
  24566. }while( got<0 && errno==EINTR );
  24567. #endif
  24568. TIMER_END;
  24569. if( got<0 ){
  24570. ((unixFile*)id)->lastErrno = errno;
  24571. }
  24572. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
  24573. return got;
  24574. }
  24575. /*
  24576. ** Write data from a buffer into a file. Return SQLITE_OK on success
  24577. ** or some other error code on failure.
  24578. */
  24579. static int unixWrite(
  24580. sqlite3_file *id,
  24581. const void *pBuf,
  24582. int amt,
  24583. sqlite3_int64 offset
  24584. ){
  24585. unixFile *pFile = (unixFile*)id;
  24586. int wrote = 0;
  24587. assert( id );
  24588. assert( amt>0 );
  24589. /* If this is a database file (not a journal, master-journal or temp
  24590. ** file), the bytes in the locking range should never be read or written. */
  24591. #if 0
  24592. assert( pFile->pUnused==0
  24593. || offset>=PENDING_BYTE+512
  24594. || offset+amt<=PENDING_BYTE
  24595. );
  24596. #endif
  24597. #ifdef SQLITE_DEBUG
  24598. /* If we are doing a normal write to a database file (as opposed to
  24599. ** doing a hot-journal rollback or a write to some file other than a
  24600. ** normal database file) then record the fact that the database
  24601. ** has changed. If the transaction counter is modified, record that
  24602. ** fact too.
  24603. */
  24604. if( pFile->inNormalWrite ){
  24605. pFile->dbUpdate = 1; /* The database has been modified */
  24606. if( offset<=24 && offset+amt>=27 ){
  24607. int rc;
  24608. char oldCntr[4];
  24609. SimulateIOErrorBenign(1);
  24610. rc = seekAndRead(pFile, 24, oldCntr, 4);
  24611. SimulateIOErrorBenign(0);
  24612. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  24613. pFile->transCntrChng = 1; /* The transaction counter has changed */
  24614. }
  24615. }
  24616. }
  24617. #endif
  24618. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  24619. amt -= wrote;
  24620. offset += wrote;
  24621. pBuf = &((char*)pBuf)[wrote];
  24622. }
  24623. SimulateIOError(( wrote=(-1), amt=1 ));
  24624. SimulateDiskfullError(( wrote=0, amt=1 ));
  24625. if( amt>0 ){
  24626. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  24627. /* lastErrno set by seekAndWrite */
  24628. return SQLITE_IOERR_WRITE;
  24629. }else{
  24630. pFile->lastErrno = 0; /* not a system error */
  24631. return SQLITE_FULL;
  24632. }
  24633. }
  24634. return SQLITE_OK;
  24635. }
  24636. #ifdef SQLITE_TEST
  24637. /*
  24638. ** Count the number of fullsyncs and normal syncs. This is used to test
  24639. ** that syncs and fullsyncs are occurring at the right times.
  24640. */
  24641. SQLITE_API int sqlite3_sync_count = 0;
  24642. SQLITE_API int sqlite3_fullsync_count = 0;
  24643. #endif
  24644. /*
  24645. ** We do not trust systems to provide a working fdatasync(). Some do.
  24646. ** Others do no. To be safe, we will stick with the (slightly slower)
  24647. ** fsync(). If you know that your system does support fdatasync() correctly,
  24648. ** then simply compile with -Dfdatasync=fdatasync
  24649. */
  24650. #if !defined(fdatasync)
  24651. # define fdatasync fsync
  24652. #endif
  24653. /*
  24654. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  24655. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  24656. ** only available on Mac OS X. But that could change.
  24657. */
  24658. #ifdef F_FULLFSYNC
  24659. # define HAVE_FULLFSYNC 1
  24660. #else
  24661. # define HAVE_FULLFSYNC 0
  24662. #endif
  24663. /*
  24664. ** The fsync() system call does not work as advertised on many
  24665. ** unix systems. The following procedure is an attempt to make
  24666. ** it work better.
  24667. **
  24668. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  24669. ** for testing when we want to run through the test suite quickly.
  24670. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  24671. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  24672. ** or power failure will likely corrupt the database file.
  24673. **
  24674. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  24675. ** The idea behind dataOnly is that it should only write the file content
  24676. ** to disk, not the inode. We only set dataOnly if the file size is
  24677. ** unchanged since the file size is part of the inode. However,
  24678. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  24679. ** file size has changed. The only real difference between fdatasync()
  24680. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  24681. ** inode if the mtime or owner or other inode attributes have changed.
  24682. ** We only care about the file size, not the other file attributes, so
  24683. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  24684. ** So, we always use fdatasync() if it is available, regardless of
  24685. ** the value of the dataOnly flag.
  24686. */
  24687. static int full_fsync(int fd, int fullSync, int dataOnly){
  24688. int rc;
  24689. /* The following "ifdef/elif/else/" block has the same structure as
  24690. ** the one below. It is replicated here solely to avoid cluttering
  24691. ** up the real code with the UNUSED_PARAMETER() macros.
  24692. */
  24693. #ifdef SQLITE_NO_SYNC
  24694. UNUSED_PARAMETER(fd);
  24695. UNUSED_PARAMETER(fullSync);
  24696. UNUSED_PARAMETER(dataOnly);
  24697. #elif HAVE_FULLFSYNC
  24698. UNUSED_PARAMETER(dataOnly);
  24699. #else
  24700. UNUSED_PARAMETER(fullSync);
  24701. UNUSED_PARAMETER(dataOnly);
  24702. #endif
  24703. /* Record the number of times that we do a normal fsync() and
  24704. ** FULLSYNC. This is used during testing to verify that this procedure
  24705. ** gets called with the correct arguments.
  24706. */
  24707. #ifdef SQLITE_TEST
  24708. if( fullSync ) sqlite3_fullsync_count++;
  24709. sqlite3_sync_count++;
  24710. #endif
  24711. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  24712. ** no-op
  24713. */
  24714. #ifdef SQLITE_NO_SYNC
  24715. rc = SQLITE_OK;
  24716. #elif HAVE_FULLFSYNC
  24717. if( fullSync ){
  24718. rc = osFcntl(fd, F_FULLFSYNC, 0);
  24719. }else{
  24720. rc = 1;
  24721. }
  24722. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  24723. ** It shouldn't be possible for fullfsync to fail on the local
  24724. ** file system (on OSX), so failure indicates that FULLFSYNC
  24725. ** isn't supported for this file system. So, attempt an fsync
  24726. ** and (for now) ignore the overhead of a superfluous fcntl call.
  24727. ** It'd be better to detect fullfsync support once and avoid
  24728. ** the fcntl call every time sync is called.
  24729. */
  24730. if( rc ) rc = fsync(fd);
  24731. #elif defined(__APPLE__)
  24732. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  24733. ** so currently we default to the macro that redefines fdatasync to fsync
  24734. */
  24735. rc = fsync(fd);
  24736. #else
  24737. rc = fdatasync(fd);
  24738. #if OS_VXWORKS
  24739. if( rc==-1 && errno==ENOTSUP ){
  24740. rc = fsync(fd);
  24741. }
  24742. #endif /* OS_VXWORKS */
  24743. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  24744. if( OS_VXWORKS && rc!= -1 ){
  24745. rc = 0;
  24746. }
  24747. return rc;
  24748. }
  24749. /*
  24750. ** Open a file descriptor to the directory containing file zFilename.
  24751. ** If successful, *pFd is set to the opened file descriptor and
  24752. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  24753. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  24754. ** value.
  24755. **
  24756. ** The directory file descriptor is used for only one thing - to
  24757. ** fsync() a directory to make sure file creation and deletion events
  24758. ** are flushed to disk. Such fsyncs are not needed on newer
  24759. ** journaling filesystems, but are required on older filesystems.
  24760. **
  24761. ** This routine can be overridden using the xSetSysCall interface.
  24762. ** The ability to override this routine was added in support of the
  24763. ** chromium sandbox. Opening a directory is a security risk (we are
  24764. ** told) so making it overrideable allows the chromium sandbox to
  24765. ** replace this routine with a harmless no-op. To make this routine
  24766. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  24767. ** *pFd set to a negative number.
  24768. **
  24769. ** If SQLITE_OK is returned, the caller is responsible for closing
  24770. ** the file descriptor *pFd using close().
  24771. */
  24772. static int openDirectory(const char *zFilename, int *pFd){
  24773. int ii;
  24774. int fd = -1;
  24775. char zDirname[MAX_PATHNAME+1];
  24776. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  24777. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  24778. if( ii>0 ){
  24779. zDirname[ii] = '\0';
  24780. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  24781. if( fd>=0 ){
  24782. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  24783. }
  24784. }
  24785. *pFd = fd;
  24786. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  24787. }
  24788. /*
  24789. ** Make sure all writes to a particular file are committed to disk.
  24790. **
  24791. ** If dataOnly==0 then both the file itself and its metadata (file
  24792. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  24793. ** file data is synced.
  24794. **
  24795. ** Under Unix, also make sure that the directory entry for the file
  24796. ** has been created by fsync-ing the directory that contains the file.
  24797. ** If we do not do this and we encounter a power failure, the directory
  24798. ** entry for the journal might not exist after we reboot. The next
  24799. ** SQLite to access the file will not know that the journal exists (because
  24800. ** the directory entry for the journal was never created) and the transaction
  24801. ** will not roll back - possibly leading to database corruption.
  24802. */
  24803. static int unixSync(sqlite3_file *id, int flags){
  24804. int rc;
  24805. unixFile *pFile = (unixFile*)id;
  24806. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  24807. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  24808. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  24809. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  24810. || (flags&0x0F)==SQLITE_SYNC_FULL
  24811. );
  24812. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  24813. ** line is to test that doing so does not cause any problems.
  24814. */
  24815. SimulateDiskfullError( return SQLITE_FULL );
  24816. assert( pFile );
  24817. OSTRACE(("SYNC %-3d\n", pFile->h));
  24818. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  24819. SimulateIOError( rc=1 );
  24820. if( rc ){
  24821. pFile->lastErrno = errno;
  24822. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  24823. }
  24824. /* Also fsync the directory containing the file if the DIRSYNC flag
  24825. ** is set. This is a one-time occurrance. Many systems (examples: AIX)
  24826. ** are unable to fsync a directory, so ignore errors on the fsync.
  24827. */
  24828. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  24829. int dirfd;
  24830. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  24831. HAVE_FULLFSYNC, isFullsync));
  24832. rc = osOpenDirectory(pFile->zPath, &dirfd);
  24833. if( rc==SQLITE_OK && dirfd>=0 ){
  24834. full_fsync(dirfd, 0, 0);
  24835. robust_close(pFile, dirfd, __LINE__);
  24836. }else if( rc==SQLITE_CANTOPEN ){
  24837. rc = SQLITE_OK;
  24838. }
  24839. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  24840. }
  24841. return rc;
  24842. }
  24843. /*
  24844. ** Truncate an open file to a specified size
  24845. */
  24846. static int unixTruncate(sqlite3_file *id, i64 nByte){
  24847. unixFile *pFile = (unixFile *)id;
  24848. int rc;
  24849. assert( pFile );
  24850. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  24851. /* If the user has configured a chunk-size for this file, truncate the
  24852. ** file so that it consists of an integer number of chunks (i.e. the
  24853. ** actual file size after the operation may be larger than the requested
  24854. ** size).
  24855. */
  24856. if( pFile->szChunk>0 ){
  24857. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  24858. }
  24859. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  24860. if( rc ){
  24861. pFile->lastErrno = errno;
  24862. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  24863. }else{
  24864. #ifdef SQLITE_DEBUG
  24865. /* If we are doing a normal write to a database file (as opposed to
  24866. ** doing a hot-journal rollback or a write to some file other than a
  24867. ** normal database file) and we truncate the file to zero length,
  24868. ** that effectively updates the change counter. This might happen
  24869. ** when restoring a database using the backup API from a zero-length
  24870. ** source.
  24871. */
  24872. if( pFile->inNormalWrite && nByte==0 ){
  24873. pFile->transCntrChng = 1;
  24874. }
  24875. #endif
  24876. return SQLITE_OK;
  24877. }
  24878. }
  24879. /*
  24880. ** Determine the current size of a file in bytes
  24881. */
  24882. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  24883. int rc;
  24884. struct stat buf;
  24885. assert( id );
  24886. rc = osFstat(((unixFile*)id)->h, &buf);
  24887. SimulateIOError( rc=1 );
  24888. if( rc!=0 ){
  24889. ((unixFile*)id)->lastErrno = errno;
  24890. return SQLITE_IOERR_FSTAT;
  24891. }
  24892. *pSize = buf.st_size;
  24893. /* When opening a zero-size database, the findInodeInfo() procedure
  24894. ** writes a single byte into that file in order to work around a bug
  24895. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  24896. ** layers, we need to report this file size as zero even though it is
  24897. ** really 1. Ticket #3260.
  24898. */
  24899. if( *pSize==1 ) *pSize = 0;
  24900. return SQLITE_OK;
  24901. }
  24902. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  24903. /*
  24904. ** Handler for proxy-locking file-control verbs. Defined below in the
  24905. ** proxying locking division.
  24906. */
  24907. static int proxyFileControl(sqlite3_file*,int,void*);
  24908. #endif
  24909. /*
  24910. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  24911. ** file-control operation. Enlarge the database to nBytes in size
  24912. ** (rounded up to the next chunk-size). If the database is already
  24913. ** nBytes or larger, this routine is a no-op.
  24914. */
  24915. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  24916. if( pFile->szChunk>0 ){
  24917. i64 nSize; /* Required file size */
  24918. struct stat buf; /* Used to hold return values of fstat() */
  24919. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  24920. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  24921. if( nSize>(i64)buf.st_size ){
  24922. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  24923. /* The code below is handling the return value of osFallocate()
  24924. ** correctly. posix_fallocate() is defined to "returns zero on success,
  24925. ** or an error number on failure". See the manpage for details. */
  24926. int err;
  24927. do{
  24928. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  24929. }while( err==EINTR );
  24930. if( err ) return SQLITE_IOERR_WRITE;
  24931. #else
  24932. /* If the OS does not have posix_fallocate(), fake it. First use
  24933. ** ftruncate() to set the file size, then write a single byte to
  24934. ** the last byte in each block within the extended region. This
  24935. ** is the same technique used by glibc to implement posix_fallocate()
  24936. ** on systems that do not have a real fallocate() system call.
  24937. */
  24938. int nBlk = buf.st_blksize; /* File-system block size */
  24939. i64 iWrite; /* Next offset to write to */
  24940. if( robust_ftruncate(pFile->h, nSize) ){
  24941. pFile->lastErrno = errno;
  24942. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  24943. }
  24944. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  24945. while( iWrite<nSize ){
  24946. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  24947. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  24948. iWrite += nBlk;
  24949. }
  24950. #endif
  24951. }
  24952. }
  24953. return SQLITE_OK;
  24954. }
  24955. /*
  24956. ** If *pArg is inititially negative then this is a query. Set *pArg to
  24957. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  24958. **
  24959. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  24960. */
  24961. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  24962. if( *pArg<0 ){
  24963. *pArg = (pFile->ctrlFlags & mask)!=0;
  24964. }else if( (*pArg)==0 ){
  24965. pFile->ctrlFlags &= ~mask;
  24966. }else{
  24967. pFile->ctrlFlags |= mask;
  24968. }
  24969. }
  24970. /* Forward declaration */
  24971. static int unixGetTempname(int nBuf, char *zBuf);
  24972. /*
  24973. ** Information and control of an open file handle.
  24974. */
  24975. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  24976. unixFile *pFile = (unixFile*)id;
  24977. switch( op ){
  24978. case SQLITE_FCNTL_LOCKSTATE: {
  24979. *(int*)pArg = pFile->eFileLock;
  24980. return SQLITE_OK;
  24981. }
  24982. case SQLITE_LAST_ERRNO: {
  24983. *(int*)pArg = pFile->lastErrno;
  24984. return SQLITE_OK;
  24985. }
  24986. case SQLITE_FCNTL_CHUNK_SIZE: {
  24987. pFile->szChunk = *(int *)pArg;
  24988. return SQLITE_OK;
  24989. }
  24990. case SQLITE_FCNTL_SIZE_HINT: {
  24991. int rc;
  24992. SimulateIOErrorBenign(1);
  24993. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  24994. SimulateIOErrorBenign(0);
  24995. return rc;
  24996. }
  24997. case SQLITE_FCNTL_PERSIST_WAL: {
  24998. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  24999. return SQLITE_OK;
  25000. }
  25001. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  25002. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  25003. return SQLITE_OK;
  25004. }
  25005. case SQLITE_FCNTL_VFSNAME: {
  25006. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  25007. return SQLITE_OK;
  25008. }
  25009. case SQLITE_FCNTL_TEMPFILENAME: {
  25010. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  25011. if( zTFile ){
  25012. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  25013. *(char**)pArg = zTFile;
  25014. }
  25015. return SQLITE_OK;
  25016. }
  25017. #ifdef SQLITE_DEBUG
  25018. /* The pager calls this method to signal that it has done
  25019. ** a rollback and that the database is therefore unchanged and
  25020. ** it hence it is OK for the transaction change counter to be
  25021. ** unchanged.
  25022. */
  25023. case SQLITE_FCNTL_DB_UNCHANGED: {
  25024. ((unixFile*)id)->dbUpdate = 0;
  25025. return SQLITE_OK;
  25026. }
  25027. #endif
  25028. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25029. case SQLITE_SET_LOCKPROXYFILE:
  25030. case SQLITE_GET_LOCKPROXYFILE: {
  25031. return proxyFileControl(id,op,pArg);
  25032. }
  25033. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25034. }
  25035. return SQLITE_NOTFOUND;
  25036. }
  25037. /*
  25038. ** Return the sector size in bytes of the underlying block device for
  25039. ** the specified file. This is almost always 512 bytes, but may be
  25040. ** larger for some devices.
  25041. **
  25042. ** SQLite code assumes this function cannot fail. It also assumes that
  25043. ** if two files are created in the same file-system directory (i.e.
  25044. ** a database and its journal file) that the sector size will be the
  25045. ** same for both.
  25046. */
  25047. #ifndef __QNXNTO__
  25048. static int unixSectorSize(sqlite3_file *NotUsed){
  25049. UNUSED_PARAMETER(NotUsed);
  25050. return SQLITE_DEFAULT_SECTOR_SIZE;
  25051. }
  25052. #endif
  25053. /*
  25054. ** The following version of unixSectorSize() is optimized for QNX.
  25055. */
  25056. #ifdef __QNXNTO__
  25057. #include <sys/dcmd_blk.h>
  25058. #include <sys/statvfs.h>
  25059. static int unixSectorSize(sqlite3_file *id){
  25060. unixFile *pFile = (unixFile*)id;
  25061. if( pFile->sectorSize == 0 ){
  25062. struct statvfs fsInfo;
  25063. /* Set defaults for non-supported filesystems */
  25064. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25065. pFile->deviceCharacteristics = 0;
  25066. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  25067. return pFile->sectorSize;
  25068. }
  25069. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  25070. pFile->sectorSize = fsInfo.f_bsize;
  25071. pFile->deviceCharacteristics =
  25072. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  25073. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25074. ** the write succeeds */
  25075. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25076. ** so it is ordered */
  25077. 0;
  25078. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  25079. pFile->sectorSize = fsInfo.f_bsize;
  25080. pFile->deviceCharacteristics =
  25081. /* etfs cluster size writes are atomic */
  25082. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  25083. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25084. ** the write succeeds */
  25085. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25086. ** so it is ordered */
  25087. 0;
  25088. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  25089. pFile->sectorSize = fsInfo.f_bsize;
  25090. pFile->deviceCharacteristics =
  25091. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  25092. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25093. ** the write succeeds */
  25094. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25095. ** so it is ordered */
  25096. 0;
  25097. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  25098. pFile->sectorSize = fsInfo.f_bsize;
  25099. pFile->deviceCharacteristics =
  25100. /* full bitset of atomics from max sector size and smaller */
  25101. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25102. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25103. ** so it is ordered */
  25104. 0;
  25105. }else if( strstr(fsInfo.f_basetype, "dos") ){
  25106. pFile->sectorSize = fsInfo.f_bsize;
  25107. pFile->deviceCharacteristics =
  25108. /* full bitset of atomics from max sector size and smaller */
  25109. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25110. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25111. ** so it is ordered */
  25112. 0;
  25113. }else{
  25114. pFile->deviceCharacteristics =
  25115. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  25116. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25117. ** the write succeeds */
  25118. 0;
  25119. }
  25120. }
  25121. /* Last chance verification. If the sector size isn't a multiple of 512
  25122. ** then it isn't valid.*/
  25123. if( pFile->sectorSize % 512 != 0 ){
  25124. pFile->deviceCharacteristics = 0;
  25125. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25126. }
  25127. return pFile->sectorSize;
  25128. }
  25129. #endif /* __QNXNTO__ */
  25130. /*
  25131. ** Return the device characteristics for the file.
  25132. **
  25133. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  25134. ** However, that choice is contraversial since technically the underlying
  25135. ** file system does not always provide powersafe overwrites. (In other
  25136. ** words, after a power-loss event, parts of the file that were never
  25137. ** written might end up being altered.) However, non-PSOW behavior is very,
  25138. ** very rare. And asserting PSOW makes a large reduction in the amount
  25139. ** of required I/O for journaling, since a lot of padding is eliminated.
  25140. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  25141. ** available to turn it off and URI query parameter available to turn it off.
  25142. */
  25143. static int unixDeviceCharacteristics(sqlite3_file *id){
  25144. unixFile *p = (unixFile*)id;
  25145. int rc = 0;
  25146. #ifdef __QNXNTO__
  25147. if( p->sectorSize==0 ) unixSectorSize(id);
  25148. rc = p->deviceCharacteristics;
  25149. #endif
  25150. if( p->ctrlFlags & UNIXFILE_PSOW ){
  25151. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  25152. }
  25153. return rc;
  25154. }
  25155. #ifndef SQLITE_OMIT_WAL
  25156. /*
  25157. ** Object used to represent an shared memory buffer.
  25158. **
  25159. ** When multiple threads all reference the same wal-index, each thread
  25160. ** has its own unixShm object, but they all point to a single instance
  25161. ** of this unixShmNode object. In other words, each wal-index is opened
  25162. ** only once per process.
  25163. **
  25164. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25165. ** We could coalesce this object into unixInodeInfo, but that would mean
  25166. ** every open file that does not use shared memory (in other words, most
  25167. ** open files) would have to carry around this extra information. So
  25168. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25169. ** and the unixShmNode object is created only when needed.
  25170. **
  25171. ** unixMutexHeld() must be true when creating or destroying
  25172. ** this object or while reading or writing the following fields:
  25173. **
  25174. ** nRef
  25175. **
  25176. ** The following fields are read-only after the object is created:
  25177. **
  25178. ** fid
  25179. ** zFilename
  25180. **
  25181. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25182. ** unixMutexHeld() is true when reading or writing any other field
  25183. ** in this structure.
  25184. */
  25185. struct unixShmNode {
  25186. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25187. sqlite3_mutex *mutex; /* Mutex to access this object */
  25188. char *zFilename; /* Name of the mmapped file */
  25189. int h; /* Open file descriptor */
  25190. int szRegion; /* Size of shared-memory regions */
  25191. u16 nRegion; /* Size of array apRegion */
  25192. u8 isReadonly; /* True if read-only */
  25193. char **apRegion; /* Array of mapped shared-memory regions */
  25194. int nRef; /* Number of unixShm objects pointing to this */
  25195. unixShm *pFirst; /* All unixShm objects pointing to this */
  25196. #ifdef SQLITE_DEBUG
  25197. u8 exclMask; /* Mask of exclusive locks held */
  25198. u8 sharedMask; /* Mask of shared locks held */
  25199. u8 nextShmId; /* Next available unixShm.id value */
  25200. #endif
  25201. };
  25202. /*
  25203. ** Structure used internally by this VFS to record the state of an
  25204. ** open shared memory connection.
  25205. **
  25206. ** The following fields are initialized when this object is created and
  25207. ** are read-only thereafter:
  25208. **
  25209. ** unixShm.pFile
  25210. ** unixShm.id
  25211. **
  25212. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  25213. ** while accessing any read/write fields.
  25214. */
  25215. struct unixShm {
  25216. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  25217. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  25218. u8 hasMutex; /* True if holding the unixShmNode mutex */
  25219. u8 id; /* Id of this connection within its unixShmNode */
  25220. u16 sharedMask; /* Mask of shared locks held */
  25221. u16 exclMask; /* Mask of exclusive locks held */
  25222. };
  25223. /*
  25224. ** Constants used for locking
  25225. */
  25226. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  25227. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  25228. /*
  25229. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  25230. **
  25231. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  25232. ** otherwise.
  25233. */
  25234. static int unixShmSystemLock(
  25235. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  25236. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  25237. int ofst, /* First byte of the locking range */
  25238. int n /* Number of bytes to lock */
  25239. ){
  25240. struct flock f; /* The posix advisory locking structure */
  25241. int rc = SQLITE_OK; /* Result code form fcntl() */
  25242. /* Access to the unixShmNode object is serialized by the caller */
  25243. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  25244. /* Shared locks never span more than one byte */
  25245. assert( n==1 || lockType!=F_RDLCK );
  25246. /* Locks are within range */
  25247. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  25248. if( pShmNode->h>=0 ){
  25249. /* Initialize the locking parameters */
  25250. memset(&f, 0, sizeof(f));
  25251. f.l_type = lockType;
  25252. f.l_whence = SEEK_SET;
  25253. f.l_start = ofst;
  25254. f.l_len = n;
  25255. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  25256. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  25257. }
  25258. /* Update the global lock state and do debug tracing */
  25259. #ifdef SQLITE_DEBUG
  25260. { u16 mask;
  25261. OSTRACE(("SHM-LOCK "));
  25262. mask = (1<<(ofst+n)) - (1<<ofst);
  25263. if( rc==SQLITE_OK ){
  25264. if( lockType==F_UNLCK ){
  25265. OSTRACE(("unlock %d ok", ofst));
  25266. pShmNode->exclMask &= ~mask;
  25267. pShmNode->sharedMask &= ~mask;
  25268. }else if( lockType==F_RDLCK ){
  25269. OSTRACE(("read-lock %d ok", ofst));
  25270. pShmNode->exclMask &= ~mask;
  25271. pShmNode->sharedMask |= mask;
  25272. }else{
  25273. assert( lockType==F_WRLCK );
  25274. OSTRACE(("write-lock %d ok", ofst));
  25275. pShmNode->exclMask |= mask;
  25276. pShmNode->sharedMask &= ~mask;
  25277. }
  25278. }else{
  25279. if( lockType==F_UNLCK ){
  25280. OSTRACE(("unlock %d failed", ofst));
  25281. }else if( lockType==F_RDLCK ){
  25282. OSTRACE(("read-lock failed"));
  25283. }else{
  25284. assert( lockType==F_WRLCK );
  25285. OSTRACE(("write-lock %d failed", ofst));
  25286. }
  25287. }
  25288. OSTRACE((" - afterwards %03x,%03x\n",
  25289. pShmNode->sharedMask, pShmNode->exclMask));
  25290. }
  25291. #endif
  25292. return rc;
  25293. }
  25294. /*
  25295. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  25296. **
  25297. ** This is not a VFS shared-memory method; it is a utility function called
  25298. ** by VFS shared-memory methods.
  25299. */
  25300. static void unixShmPurge(unixFile *pFd){
  25301. unixShmNode *p = pFd->pInode->pShmNode;
  25302. assert( unixMutexHeld() );
  25303. if( p && p->nRef==0 ){
  25304. int i;
  25305. assert( p->pInode==pFd->pInode );
  25306. sqlite3_mutex_free(p->mutex);
  25307. for(i=0; i<p->nRegion; i++){
  25308. if( p->h>=0 ){
  25309. munmap(p->apRegion[i], p->szRegion);
  25310. }else{
  25311. sqlite3_free(p->apRegion[i]);
  25312. }
  25313. }
  25314. sqlite3_free(p->apRegion);
  25315. if( p->h>=0 ){
  25316. robust_close(pFd, p->h, __LINE__);
  25317. p->h = -1;
  25318. }
  25319. p->pInode->pShmNode = 0;
  25320. sqlite3_free(p);
  25321. }
  25322. }
  25323. /*
  25324. ** Open a shared-memory area associated with open database file pDbFd.
  25325. ** This particular implementation uses mmapped files.
  25326. **
  25327. ** The file used to implement shared-memory is in the same directory
  25328. ** as the open database file and has the same name as the open database
  25329. ** file with the "-shm" suffix added. For example, if the database file
  25330. ** is "/home/user1/config.db" then the file that is created and mmapped
  25331. ** for shared memory will be called "/home/user1/config.db-shm".
  25332. **
  25333. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  25334. ** some other tmpfs mount. But if a file in a different directory
  25335. ** from the database file is used, then differing access permissions
  25336. ** or a chroot() might cause two different processes on the same
  25337. ** database to end up using different files for shared memory -
  25338. ** meaning that their memory would not really be shared - resulting
  25339. ** in database corruption. Nevertheless, this tmpfs file usage
  25340. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  25341. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  25342. ** option results in an incompatible build of SQLite; builds of SQLite
  25343. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  25344. ** same database file at the same time, database corruption will likely
  25345. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  25346. ** "unsupported" and may go away in a future SQLite release.
  25347. **
  25348. ** When opening a new shared-memory file, if no other instances of that
  25349. ** file are currently open, in this process or in other processes, then
  25350. ** the file must be truncated to zero length or have its header cleared.
  25351. **
  25352. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  25353. ** that means that an exclusive lock is held on the database file and
  25354. ** that no other processes are able to read or write the database. In
  25355. ** that case, we do not really need shared memory. No shared memory
  25356. ** file is created. The shared memory will be simulated with heap memory.
  25357. */
  25358. static int unixOpenSharedMemory(unixFile *pDbFd){
  25359. struct unixShm *p = 0; /* The connection to be opened */
  25360. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  25361. int rc; /* Result code */
  25362. unixInodeInfo *pInode; /* The inode of fd */
  25363. char *zShmFilename; /* Name of the file used for SHM */
  25364. int nShmFilename; /* Size of the SHM filename in bytes */
  25365. /* Allocate space for the new unixShm object. */
  25366. p = sqlite3_malloc( sizeof(*p) );
  25367. if( p==0 ) return SQLITE_NOMEM;
  25368. memset(p, 0, sizeof(*p));
  25369. assert( pDbFd->pShm==0 );
  25370. /* Check to see if a unixShmNode object already exists. Reuse an existing
  25371. ** one if present. Create a new one if necessary.
  25372. */
  25373. unixEnterMutex();
  25374. pInode = pDbFd->pInode;
  25375. pShmNode = pInode->pShmNode;
  25376. if( pShmNode==0 ){
  25377. struct stat sStat; /* fstat() info for database file */
  25378. /* Call fstat() to figure out the permissions on the database file. If
  25379. ** a new *-shm file is created, an attempt will be made to create it
  25380. ** with the same permissions.
  25381. */
  25382. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  25383. rc = SQLITE_IOERR_FSTAT;
  25384. goto shm_open_err;
  25385. }
  25386. #ifdef SQLITE_SHM_DIRECTORY
  25387. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  25388. #else
  25389. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  25390. #endif
  25391. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  25392. if( pShmNode==0 ){
  25393. rc = SQLITE_NOMEM;
  25394. goto shm_open_err;
  25395. }
  25396. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  25397. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  25398. #ifdef SQLITE_SHM_DIRECTORY
  25399. sqlite3_snprintf(nShmFilename, zShmFilename,
  25400. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  25401. (u32)sStat.st_ino, (u32)sStat.st_dev);
  25402. #else
  25403. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  25404. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  25405. #endif
  25406. pShmNode->h = -1;
  25407. pDbFd->pInode->pShmNode = pShmNode;
  25408. pShmNode->pInode = pDbFd->pInode;
  25409. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  25410. if( pShmNode->mutex==0 ){
  25411. rc = SQLITE_NOMEM;
  25412. goto shm_open_err;
  25413. }
  25414. if( pInode->bProcessLock==0 ){
  25415. int openFlags = O_RDWR | O_CREAT;
  25416. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  25417. openFlags = O_RDONLY;
  25418. pShmNode->isReadonly = 1;
  25419. }
  25420. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  25421. if( pShmNode->h<0 ){
  25422. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  25423. goto shm_open_err;
  25424. }
  25425. /* If this process is running as root, make sure that the SHM file
  25426. ** is owned by the same user that owns the original database. Otherwise,
  25427. ** the original owner will not be able to connect.
  25428. */
  25429. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  25430. /* Check to see if another process is holding the dead-man switch.
  25431. ** If not, truncate the file to zero length.
  25432. */
  25433. rc = SQLITE_OK;
  25434. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  25435. if( robust_ftruncate(pShmNode->h, 0) ){
  25436. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  25437. }
  25438. }
  25439. if( rc==SQLITE_OK ){
  25440. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  25441. }
  25442. if( rc ) goto shm_open_err;
  25443. }
  25444. }
  25445. /* Make the new connection a child of the unixShmNode */
  25446. p->pShmNode = pShmNode;
  25447. #ifdef SQLITE_DEBUG
  25448. p->id = pShmNode->nextShmId++;
  25449. #endif
  25450. pShmNode->nRef++;
  25451. pDbFd->pShm = p;
  25452. unixLeaveMutex();
  25453. /* The reference count on pShmNode has already been incremented under
  25454. ** the cover of the unixEnterMutex() mutex and the pointer from the
  25455. ** new (struct unixShm) object to the pShmNode has been set. All that is
  25456. ** left to do is to link the new object into the linked list starting
  25457. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  25458. ** mutex.
  25459. */
  25460. sqlite3_mutex_enter(pShmNode->mutex);
  25461. p->pNext = pShmNode->pFirst;
  25462. pShmNode->pFirst = p;
  25463. sqlite3_mutex_leave(pShmNode->mutex);
  25464. return SQLITE_OK;
  25465. /* Jump here on any error */
  25466. shm_open_err:
  25467. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  25468. sqlite3_free(p);
  25469. unixLeaveMutex();
  25470. return rc;
  25471. }
  25472. /*
  25473. ** This function is called to obtain a pointer to region iRegion of the
  25474. ** shared-memory associated with the database file fd. Shared-memory regions
  25475. ** are numbered starting from zero. Each shared-memory region is szRegion
  25476. ** bytes in size.
  25477. **
  25478. ** If an error occurs, an error code is returned and *pp is set to NULL.
  25479. **
  25480. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  25481. ** region has not been allocated (by any client, including one running in a
  25482. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  25483. ** bExtend is non-zero and the requested shared-memory region has not yet
  25484. ** been allocated, it is allocated by this function.
  25485. **
  25486. ** If the shared-memory region has already been allocated or is allocated by
  25487. ** this call as described above, then it is mapped into this processes
  25488. ** address space (if it is not already), *pp is set to point to the mapped
  25489. ** memory and SQLITE_OK returned.
  25490. */
  25491. static int unixShmMap(
  25492. sqlite3_file *fd, /* Handle open on database file */
  25493. int iRegion, /* Region to retrieve */
  25494. int szRegion, /* Size of regions */
  25495. int bExtend, /* True to extend file if necessary */
  25496. void volatile **pp /* OUT: Mapped memory */
  25497. ){
  25498. unixFile *pDbFd = (unixFile*)fd;
  25499. unixShm *p;
  25500. unixShmNode *pShmNode;
  25501. int rc = SQLITE_OK;
  25502. /* If the shared-memory file has not yet been opened, open it now. */
  25503. if( pDbFd->pShm==0 ){
  25504. rc = unixOpenSharedMemory(pDbFd);
  25505. if( rc!=SQLITE_OK ) return rc;
  25506. }
  25507. p = pDbFd->pShm;
  25508. pShmNode = p->pShmNode;
  25509. sqlite3_mutex_enter(pShmNode->mutex);
  25510. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  25511. assert( pShmNode->pInode==pDbFd->pInode );
  25512. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  25513. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  25514. if( pShmNode->nRegion<=iRegion ){
  25515. char **apNew; /* New apRegion[] array */
  25516. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  25517. struct stat sStat; /* Used by fstat() */
  25518. pShmNode->szRegion = szRegion;
  25519. if( pShmNode->h>=0 ){
  25520. /* The requested region is not mapped into this processes address space.
  25521. ** Check to see if it has been allocated (i.e. if the wal-index file is
  25522. ** large enough to contain the requested region).
  25523. */
  25524. if( osFstat(pShmNode->h, &sStat) ){
  25525. rc = SQLITE_IOERR_SHMSIZE;
  25526. goto shmpage_out;
  25527. }
  25528. if( sStat.st_size<nByte ){
  25529. /* The requested memory region does not exist. If bExtend is set to
  25530. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  25531. **
  25532. ** Alternatively, if bExtend is true, use ftruncate() to allocate
  25533. ** the requested memory region.
  25534. */
  25535. if( !bExtend ) goto shmpage_out;
  25536. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25537. if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
  25538. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
  25539. pShmNode->zFilename);
  25540. goto shmpage_out;
  25541. }
  25542. #else
  25543. if( robust_ftruncate(pShmNode->h, nByte) ){
  25544. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
  25545. pShmNode->zFilename);
  25546. goto shmpage_out;
  25547. }
  25548. #endif
  25549. }
  25550. }
  25551. /* Map the requested memory region into this processes address space. */
  25552. apNew = (char **)sqlite3_realloc(
  25553. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  25554. );
  25555. if( !apNew ){
  25556. rc = SQLITE_IOERR_NOMEM;
  25557. goto shmpage_out;
  25558. }
  25559. pShmNode->apRegion = apNew;
  25560. while(pShmNode->nRegion<=iRegion){
  25561. void *pMem;
  25562. if( pShmNode->h>=0 ){
  25563. pMem = mmap(0, szRegion,
  25564. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  25565. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  25566. );
  25567. if( pMem==MAP_FAILED ){
  25568. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  25569. goto shmpage_out;
  25570. }
  25571. }else{
  25572. pMem = sqlite3_malloc(szRegion);
  25573. if( pMem==0 ){
  25574. rc = SQLITE_NOMEM;
  25575. goto shmpage_out;
  25576. }
  25577. memset(pMem, 0, szRegion);
  25578. }
  25579. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  25580. pShmNode->nRegion++;
  25581. }
  25582. }
  25583. shmpage_out:
  25584. if( pShmNode->nRegion>iRegion ){
  25585. *pp = pShmNode->apRegion[iRegion];
  25586. }else{
  25587. *pp = 0;
  25588. }
  25589. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  25590. sqlite3_mutex_leave(pShmNode->mutex);
  25591. return rc;
  25592. }
  25593. /*
  25594. ** Change the lock state for a shared-memory segment.
  25595. **
  25596. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  25597. ** different here than in posix. In xShmLock(), one can go from unlocked
  25598. ** to shared and back or from unlocked to exclusive and back. But one may
  25599. ** not go from shared to exclusive or from exclusive to shared.
  25600. */
  25601. static int unixShmLock(
  25602. sqlite3_file *fd, /* Database file holding the shared memory */
  25603. int ofst, /* First lock to acquire or release */
  25604. int n, /* Number of locks to acquire or release */
  25605. int flags /* What to do with the lock */
  25606. ){
  25607. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  25608. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  25609. unixShm *pX; /* For looping over all siblings */
  25610. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  25611. int rc = SQLITE_OK; /* Result code */
  25612. u16 mask; /* Mask of locks to take or release */
  25613. assert( pShmNode==pDbFd->pInode->pShmNode );
  25614. assert( pShmNode->pInode==pDbFd->pInode );
  25615. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  25616. assert( n>=1 );
  25617. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  25618. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  25619. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  25620. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  25621. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  25622. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  25623. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  25624. mask = (1<<(ofst+n)) - (1<<ofst);
  25625. assert( n>1 || mask==(1<<ofst) );
  25626. sqlite3_mutex_enter(pShmNode->mutex);
  25627. if( flags & SQLITE_SHM_UNLOCK ){
  25628. u16 allMask = 0; /* Mask of locks held by siblings */
  25629. /* See if any siblings hold this same lock */
  25630. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  25631. if( pX==p ) continue;
  25632. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  25633. allMask |= pX->sharedMask;
  25634. }
  25635. /* Unlock the system-level locks */
  25636. if( (mask & allMask)==0 ){
  25637. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  25638. }else{
  25639. rc = SQLITE_OK;
  25640. }
  25641. /* Undo the local locks */
  25642. if( rc==SQLITE_OK ){
  25643. p->exclMask &= ~mask;
  25644. p->sharedMask &= ~mask;
  25645. }
  25646. }else if( flags & SQLITE_SHM_SHARED ){
  25647. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  25648. /* Find out which shared locks are already held by sibling connections.
  25649. ** If any sibling already holds an exclusive lock, go ahead and return
  25650. ** SQLITE_BUSY.
  25651. */
  25652. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  25653. if( (pX->exclMask & mask)!=0 ){
  25654. rc = SQLITE_BUSY;
  25655. break;
  25656. }
  25657. allShared |= pX->sharedMask;
  25658. }
  25659. /* Get shared locks at the system level, if necessary */
  25660. if( rc==SQLITE_OK ){
  25661. if( (allShared & mask)==0 ){
  25662. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  25663. }else{
  25664. rc = SQLITE_OK;
  25665. }
  25666. }
  25667. /* Get the local shared locks */
  25668. if( rc==SQLITE_OK ){
  25669. p->sharedMask |= mask;
  25670. }
  25671. }else{
  25672. /* Make sure no sibling connections hold locks that will block this
  25673. ** lock. If any do, return SQLITE_BUSY right away.
  25674. */
  25675. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  25676. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  25677. rc = SQLITE_BUSY;
  25678. break;
  25679. }
  25680. }
  25681. /* Get the exclusive locks at the system level. Then if successful
  25682. ** also mark the local connection as being locked.
  25683. */
  25684. if( rc==SQLITE_OK ){
  25685. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  25686. if( rc==SQLITE_OK ){
  25687. assert( (p->sharedMask & mask)==0 );
  25688. p->exclMask |= mask;
  25689. }
  25690. }
  25691. }
  25692. sqlite3_mutex_leave(pShmNode->mutex);
  25693. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  25694. p->id, getpid(), p->sharedMask, p->exclMask));
  25695. return rc;
  25696. }
  25697. /*
  25698. ** Implement a memory barrier or memory fence on shared memory.
  25699. **
  25700. ** All loads and stores begun before the barrier must complete before
  25701. ** any load or store begun after the barrier.
  25702. */
  25703. static void unixShmBarrier(
  25704. sqlite3_file *fd /* Database file holding the shared memory */
  25705. ){
  25706. UNUSED_PARAMETER(fd);
  25707. unixEnterMutex();
  25708. unixLeaveMutex();
  25709. }
  25710. /*
  25711. ** Close a connection to shared-memory. Delete the underlying
  25712. ** storage if deleteFlag is true.
  25713. **
  25714. ** If there is no shared memory associated with the connection then this
  25715. ** routine is a harmless no-op.
  25716. */
  25717. static int unixShmUnmap(
  25718. sqlite3_file *fd, /* The underlying database file */
  25719. int deleteFlag /* Delete shared-memory if true */
  25720. ){
  25721. unixShm *p; /* The connection to be closed */
  25722. unixShmNode *pShmNode; /* The underlying shared-memory file */
  25723. unixShm **pp; /* For looping over sibling connections */
  25724. unixFile *pDbFd; /* The underlying database file */
  25725. pDbFd = (unixFile*)fd;
  25726. p = pDbFd->pShm;
  25727. if( p==0 ) return SQLITE_OK;
  25728. pShmNode = p->pShmNode;
  25729. assert( pShmNode==pDbFd->pInode->pShmNode );
  25730. assert( pShmNode->pInode==pDbFd->pInode );
  25731. /* Remove connection p from the set of connections associated
  25732. ** with pShmNode */
  25733. sqlite3_mutex_enter(pShmNode->mutex);
  25734. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  25735. *pp = p->pNext;
  25736. /* Free the connection p */
  25737. sqlite3_free(p);
  25738. pDbFd->pShm = 0;
  25739. sqlite3_mutex_leave(pShmNode->mutex);
  25740. /* If pShmNode->nRef has reached 0, then close the underlying
  25741. ** shared-memory file, too */
  25742. unixEnterMutex();
  25743. assert( pShmNode->nRef>0 );
  25744. pShmNode->nRef--;
  25745. if( pShmNode->nRef==0 ){
  25746. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  25747. unixShmPurge(pDbFd);
  25748. }
  25749. unixLeaveMutex();
  25750. return SQLITE_OK;
  25751. }
  25752. #else
  25753. # define unixShmMap 0
  25754. # define unixShmLock 0
  25755. # define unixShmBarrier 0
  25756. # define unixShmUnmap 0
  25757. #endif /* #ifndef SQLITE_OMIT_WAL */
  25758. /*
  25759. ** Here ends the implementation of all sqlite3_file methods.
  25760. **
  25761. ********************** End sqlite3_file Methods *******************************
  25762. ******************************************************************************/
  25763. /*
  25764. ** This division contains definitions of sqlite3_io_methods objects that
  25765. ** implement various file locking strategies. It also contains definitions
  25766. ** of "finder" functions. A finder-function is used to locate the appropriate
  25767. ** sqlite3_io_methods object for a particular database file. The pAppData
  25768. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  25769. ** the correct finder-function for that VFS.
  25770. **
  25771. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  25772. ** object. The only interesting finder-function is autolockIoFinder, which
  25773. ** looks at the filesystem type and tries to guess the best locking
  25774. ** strategy from that.
  25775. **
  25776. ** For finder-funtion F, two objects are created:
  25777. **
  25778. ** (1) The real finder-function named "FImpt()".
  25779. **
  25780. ** (2) A constant pointer to this function named just "F".
  25781. **
  25782. **
  25783. ** A pointer to the F pointer is used as the pAppData value for VFS
  25784. ** objects. We have to do this instead of letting pAppData point
  25785. ** directly at the finder-function since C90 rules prevent a void*
  25786. ** from be cast into a function pointer.
  25787. **
  25788. **
  25789. ** Each instance of this macro generates two objects:
  25790. **
  25791. ** * A constant sqlite3_io_methods object call METHOD that has locking
  25792. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  25793. **
  25794. ** * An I/O method finder function called FINDER that returns a pointer
  25795. ** to the METHOD object in the previous bullet.
  25796. */
  25797. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  25798. static const sqlite3_io_methods METHOD = { \
  25799. VERSION, /* iVersion */ \
  25800. CLOSE, /* xClose */ \
  25801. unixRead, /* xRead */ \
  25802. unixWrite, /* xWrite */ \
  25803. unixTruncate, /* xTruncate */ \
  25804. unixSync, /* xSync */ \
  25805. unixFileSize, /* xFileSize */ \
  25806. LOCK, /* xLock */ \
  25807. UNLOCK, /* xUnlock */ \
  25808. CKLOCK, /* xCheckReservedLock */ \
  25809. unixFileControl, /* xFileControl */ \
  25810. unixSectorSize, /* xSectorSize */ \
  25811. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  25812. unixShmMap, /* xShmMap */ \
  25813. unixShmLock, /* xShmLock */ \
  25814. unixShmBarrier, /* xShmBarrier */ \
  25815. unixShmUnmap /* xShmUnmap */ \
  25816. }; \
  25817. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  25818. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  25819. return &METHOD; \
  25820. } \
  25821. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  25822. = FINDER##Impl;
  25823. /*
  25824. ** Here are all of the sqlite3_io_methods objects for each of the
  25825. ** locking strategies. Functions that return pointers to these methods
  25826. ** are also created.
  25827. */
  25828. IOMETHODS(
  25829. posixIoFinder, /* Finder function name */
  25830. posixIoMethods, /* sqlite3_io_methods object name */
  25831. 2, /* shared memory is enabled */
  25832. unixClose, /* xClose method */
  25833. unixLock, /* xLock method */
  25834. unixUnlock, /* xUnlock method */
  25835. unixCheckReservedLock /* xCheckReservedLock method */
  25836. )
  25837. IOMETHODS(
  25838. nolockIoFinder, /* Finder function name */
  25839. nolockIoMethods, /* sqlite3_io_methods object name */
  25840. 1, /* shared memory is disabled */
  25841. nolockClose, /* xClose method */
  25842. nolockLock, /* xLock method */
  25843. nolockUnlock, /* xUnlock method */
  25844. nolockCheckReservedLock /* xCheckReservedLock method */
  25845. )
  25846. IOMETHODS(
  25847. dotlockIoFinder, /* Finder function name */
  25848. dotlockIoMethods, /* sqlite3_io_methods object name */
  25849. 1, /* shared memory is disabled */
  25850. dotlockClose, /* xClose method */
  25851. dotlockLock, /* xLock method */
  25852. dotlockUnlock, /* xUnlock method */
  25853. dotlockCheckReservedLock /* xCheckReservedLock method */
  25854. )
  25855. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  25856. IOMETHODS(
  25857. flockIoFinder, /* Finder function name */
  25858. flockIoMethods, /* sqlite3_io_methods object name */
  25859. 1, /* shared memory is disabled */
  25860. flockClose, /* xClose method */
  25861. flockLock, /* xLock method */
  25862. flockUnlock, /* xUnlock method */
  25863. flockCheckReservedLock /* xCheckReservedLock method */
  25864. )
  25865. #endif
  25866. #if OS_VXWORKS
  25867. IOMETHODS(
  25868. semIoFinder, /* Finder function name */
  25869. semIoMethods, /* sqlite3_io_methods object name */
  25870. 1, /* shared memory is disabled */
  25871. semClose, /* xClose method */
  25872. semLock, /* xLock method */
  25873. semUnlock, /* xUnlock method */
  25874. semCheckReservedLock /* xCheckReservedLock method */
  25875. )
  25876. #endif
  25877. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25878. IOMETHODS(
  25879. afpIoFinder, /* Finder function name */
  25880. afpIoMethods, /* sqlite3_io_methods object name */
  25881. 1, /* shared memory is disabled */
  25882. afpClose, /* xClose method */
  25883. afpLock, /* xLock method */
  25884. afpUnlock, /* xUnlock method */
  25885. afpCheckReservedLock /* xCheckReservedLock method */
  25886. )
  25887. #endif
  25888. /*
  25889. ** The proxy locking method is a "super-method" in the sense that it
  25890. ** opens secondary file descriptors for the conch and lock files and
  25891. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  25892. ** secondary files. For this reason, the division that implements
  25893. ** proxy locking is located much further down in the file. But we need
  25894. ** to go ahead and define the sqlite3_io_methods and finder function
  25895. ** for proxy locking here. So we forward declare the I/O methods.
  25896. */
  25897. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25898. static int proxyClose(sqlite3_file*);
  25899. static int proxyLock(sqlite3_file*, int);
  25900. static int proxyUnlock(sqlite3_file*, int);
  25901. static int proxyCheckReservedLock(sqlite3_file*, int*);
  25902. IOMETHODS(
  25903. proxyIoFinder, /* Finder function name */
  25904. proxyIoMethods, /* sqlite3_io_methods object name */
  25905. 1, /* shared memory is disabled */
  25906. proxyClose, /* xClose method */
  25907. proxyLock, /* xLock method */
  25908. proxyUnlock, /* xUnlock method */
  25909. proxyCheckReservedLock /* xCheckReservedLock method */
  25910. )
  25911. #endif
  25912. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  25913. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25914. IOMETHODS(
  25915. nfsIoFinder, /* Finder function name */
  25916. nfsIoMethods, /* sqlite3_io_methods object name */
  25917. 1, /* shared memory is disabled */
  25918. unixClose, /* xClose method */
  25919. unixLock, /* xLock method */
  25920. nfsUnlock, /* xUnlock method */
  25921. unixCheckReservedLock /* xCheckReservedLock method */
  25922. )
  25923. #endif
  25924. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25925. /*
  25926. ** This "finder" function attempts to determine the best locking strategy
  25927. ** for the database file "filePath". It then returns the sqlite3_io_methods
  25928. ** object that implements that strategy.
  25929. **
  25930. ** This is for MacOSX only.
  25931. */
  25932. static const sqlite3_io_methods *autolockIoFinderImpl(
  25933. const char *filePath, /* name of the database file */
  25934. unixFile *pNew /* open file object for the database file */
  25935. ){
  25936. static const struct Mapping {
  25937. const char *zFilesystem; /* Filesystem type name */
  25938. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  25939. } aMap[] = {
  25940. { "hfs", &posixIoMethods },
  25941. { "ufs", &posixIoMethods },
  25942. { "afpfs", &afpIoMethods },
  25943. { "smbfs", &afpIoMethods },
  25944. { "webdav", &nolockIoMethods },
  25945. { 0, 0 }
  25946. };
  25947. int i;
  25948. struct statfs fsInfo;
  25949. struct flock lockInfo;
  25950. if( !filePath ){
  25951. /* If filePath==NULL that means we are dealing with a transient file
  25952. ** that does not need to be locked. */
  25953. return &nolockIoMethods;
  25954. }
  25955. if( statfs(filePath, &fsInfo) != -1 ){
  25956. if( fsInfo.f_flags & MNT_RDONLY ){
  25957. return &nolockIoMethods;
  25958. }
  25959. for(i=0; aMap[i].zFilesystem; i++){
  25960. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  25961. return aMap[i].pMethods;
  25962. }
  25963. }
  25964. }
  25965. /* Default case. Handles, amongst others, "nfs".
  25966. ** Test byte-range lock using fcntl(). If the call succeeds,
  25967. ** assume that the file-system supports POSIX style locks.
  25968. */
  25969. lockInfo.l_len = 1;
  25970. lockInfo.l_start = 0;
  25971. lockInfo.l_whence = SEEK_SET;
  25972. lockInfo.l_type = F_RDLCK;
  25973. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  25974. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  25975. return &nfsIoMethods;
  25976. } else {
  25977. return &posixIoMethods;
  25978. }
  25979. }else{
  25980. return &dotlockIoMethods;
  25981. }
  25982. }
  25983. static const sqlite3_io_methods
  25984. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  25985. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25986. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  25987. /*
  25988. ** This "finder" function attempts to determine the best locking strategy
  25989. ** for the database file "filePath". It then returns the sqlite3_io_methods
  25990. ** object that implements that strategy.
  25991. **
  25992. ** This is for VXWorks only.
  25993. */
  25994. static const sqlite3_io_methods *autolockIoFinderImpl(
  25995. const char *filePath, /* name of the database file */
  25996. unixFile *pNew /* the open file object */
  25997. ){
  25998. struct flock lockInfo;
  25999. if( !filePath ){
  26000. /* If filePath==NULL that means we are dealing with a transient file
  26001. ** that does not need to be locked. */
  26002. return &nolockIoMethods;
  26003. }
  26004. /* Test if fcntl() is supported and use POSIX style locks.
  26005. ** Otherwise fall back to the named semaphore method.
  26006. */
  26007. lockInfo.l_len = 1;
  26008. lockInfo.l_start = 0;
  26009. lockInfo.l_whence = SEEK_SET;
  26010. lockInfo.l_type = F_RDLCK;
  26011. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26012. return &posixIoMethods;
  26013. }else{
  26014. return &semIoMethods;
  26015. }
  26016. }
  26017. static const sqlite3_io_methods
  26018. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26019. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  26020. /*
  26021. ** An abstract type for a pointer to a IO method finder function:
  26022. */
  26023. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  26024. /****************************************************************************
  26025. **************************** sqlite3_vfs methods ****************************
  26026. **
  26027. ** This division contains the implementation of methods on the
  26028. ** sqlite3_vfs object.
  26029. */
  26030. /*
  26031. ** Initialize the contents of the unixFile structure pointed to by pId.
  26032. */
  26033. static int fillInUnixFile(
  26034. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26035. int h, /* Open file descriptor of file being opened */
  26036. sqlite3_file *pId, /* Write to the unixFile structure here */
  26037. const char *zFilename, /* Name of the file being opened */
  26038. int ctrlFlags /* Zero or more UNIXFILE_* values */
  26039. ){
  26040. const sqlite3_io_methods *pLockingStyle;
  26041. unixFile *pNew = (unixFile *)pId;
  26042. int rc = SQLITE_OK;
  26043. assert( pNew->pInode==NULL );
  26044. /* Usually the path zFilename should not be a relative pathname. The
  26045. ** exception is when opening the proxy "conch" file in builds that
  26046. ** include the special Apple locking styles.
  26047. */
  26048. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26049. assert( zFilename==0 || zFilename[0]=='/'
  26050. || pVfs->pAppData==(void*)&autolockIoFinder );
  26051. #else
  26052. assert( zFilename==0 || zFilename[0]=='/' );
  26053. #endif
  26054. /* No locking occurs in temporary files */
  26055. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  26056. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  26057. pNew->h = h;
  26058. pNew->pVfs = pVfs;
  26059. pNew->zPath = zFilename;
  26060. pNew->ctrlFlags = (u8)ctrlFlags;
  26061. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  26062. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  26063. pNew->ctrlFlags |= UNIXFILE_PSOW;
  26064. }
  26065. if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
  26066. pNew->ctrlFlags |= UNIXFILE_EXCL;
  26067. }
  26068. #if OS_VXWORKS
  26069. pNew->pId = vxworksFindFileId(zFilename);
  26070. if( pNew->pId==0 ){
  26071. ctrlFlags |= UNIXFILE_NOLOCK;
  26072. rc = SQLITE_NOMEM;
  26073. }
  26074. #endif
  26075. if( ctrlFlags & UNIXFILE_NOLOCK ){
  26076. pLockingStyle = &nolockIoMethods;
  26077. }else{
  26078. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  26079. #if SQLITE_ENABLE_LOCKING_STYLE
  26080. /* Cache zFilename in the locking context (AFP and dotlock override) for
  26081. ** proxyLock activation is possible (remote proxy is based on db name)
  26082. ** zFilename remains valid until file is closed, to support */
  26083. pNew->lockingContext = (void*)zFilename;
  26084. #endif
  26085. }
  26086. if( pLockingStyle == &posixIoMethods
  26087. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26088. || pLockingStyle == &nfsIoMethods
  26089. #endif
  26090. ){
  26091. unixEnterMutex();
  26092. rc = findInodeInfo(pNew, &pNew->pInode);
  26093. if( rc!=SQLITE_OK ){
  26094. /* If an error occured in findInodeInfo(), close the file descriptor
  26095. ** immediately, before releasing the mutex. findInodeInfo() may fail
  26096. ** in two scenarios:
  26097. **
  26098. ** (a) A call to fstat() failed.
  26099. ** (b) A malloc failed.
  26100. **
  26101. ** Scenario (b) may only occur if the process is holding no other
  26102. ** file descriptors open on the same file. If there were other file
  26103. ** descriptors on this file, then no malloc would be required by
  26104. ** findInodeInfo(). If this is the case, it is quite safe to close
  26105. ** handle h - as it is guaranteed that no posix locks will be released
  26106. ** by doing so.
  26107. **
  26108. ** If scenario (a) caused the error then things are not so safe. The
  26109. ** implicit assumption here is that if fstat() fails, things are in
  26110. ** such bad shape that dropping a lock or two doesn't matter much.
  26111. */
  26112. robust_close(pNew, h, __LINE__);
  26113. h = -1;
  26114. }
  26115. unixLeaveMutex();
  26116. }
  26117. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26118. else if( pLockingStyle == &afpIoMethods ){
  26119. /* AFP locking uses the file path so it needs to be included in
  26120. ** the afpLockingContext.
  26121. */
  26122. afpLockingContext *pCtx;
  26123. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  26124. if( pCtx==0 ){
  26125. rc = SQLITE_NOMEM;
  26126. }else{
  26127. /* NB: zFilename exists and remains valid until the file is closed
  26128. ** according to requirement F11141. So we do not need to make a
  26129. ** copy of the filename. */
  26130. pCtx->dbPath = zFilename;
  26131. pCtx->reserved = 0;
  26132. srandomdev();
  26133. unixEnterMutex();
  26134. rc = findInodeInfo(pNew, &pNew->pInode);
  26135. if( rc!=SQLITE_OK ){
  26136. sqlite3_free(pNew->lockingContext);
  26137. robust_close(pNew, h, __LINE__);
  26138. h = -1;
  26139. }
  26140. unixLeaveMutex();
  26141. }
  26142. }
  26143. #endif
  26144. else if( pLockingStyle == &dotlockIoMethods ){
  26145. /* Dotfile locking uses the file path so it needs to be included in
  26146. ** the dotlockLockingContext
  26147. */
  26148. char *zLockFile;
  26149. int nFilename;
  26150. assert( zFilename!=0 );
  26151. nFilename = (int)strlen(zFilename) + 6;
  26152. zLockFile = (char *)sqlite3_malloc(nFilename);
  26153. if( zLockFile==0 ){
  26154. rc = SQLITE_NOMEM;
  26155. }else{
  26156. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  26157. }
  26158. pNew->lockingContext = zLockFile;
  26159. }
  26160. #if OS_VXWORKS
  26161. else if( pLockingStyle == &semIoMethods ){
  26162. /* Named semaphore locking uses the file path so it needs to be
  26163. ** included in the semLockingContext
  26164. */
  26165. unixEnterMutex();
  26166. rc = findInodeInfo(pNew, &pNew->pInode);
  26167. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  26168. char *zSemName = pNew->pInode->aSemName;
  26169. int n;
  26170. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  26171. pNew->pId->zCanonicalName);
  26172. for( n=1; zSemName[n]; n++ )
  26173. if( zSemName[n]=='/' ) zSemName[n] = '_';
  26174. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  26175. if( pNew->pInode->pSem == SEM_FAILED ){
  26176. rc = SQLITE_NOMEM;
  26177. pNew->pInode->aSemName[0] = '\0';
  26178. }
  26179. }
  26180. unixLeaveMutex();
  26181. }
  26182. #endif
  26183. pNew->lastErrno = 0;
  26184. #if OS_VXWORKS
  26185. if( rc!=SQLITE_OK ){
  26186. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26187. h = -1;
  26188. osUnlink(zFilename);
  26189. isDelete = 0;
  26190. }
  26191. if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
  26192. #endif
  26193. if( rc!=SQLITE_OK ){
  26194. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26195. }else{
  26196. pNew->pMethod = pLockingStyle;
  26197. OpenCounter(+1);
  26198. }
  26199. return rc;
  26200. }
  26201. /*
  26202. ** Return the name of a directory in which to put temporary files.
  26203. ** If no suitable temporary file directory can be found, return NULL.
  26204. */
  26205. static const char *unixTempFileDir(void){
  26206. static const char *azDirs[] = {
  26207. 0,
  26208. 0,
  26209. "/var/tmp",
  26210. "/usr/tmp",
  26211. "/tmp",
  26212. 0 /* List terminator */
  26213. };
  26214. unsigned int i;
  26215. struct stat buf;
  26216. const char *zDir = 0;
  26217. azDirs[0] = sqlite3_temp_directory;
  26218. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  26219. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  26220. if( zDir==0 ) continue;
  26221. if( osStat(zDir, &buf) ) continue;
  26222. if( !S_ISDIR(buf.st_mode) ) continue;
  26223. if( osAccess(zDir, 07) ) continue;
  26224. break;
  26225. }
  26226. return zDir;
  26227. }
  26228. /*
  26229. ** Create a temporary file name in zBuf. zBuf must be allocated
  26230. ** by the calling process and must be big enough to hold at least
  26231. ** pVfs->mxPathname bytes.
  26232. */
  26233. static int unixGetTempname(int nBuf, char *zBuf){
  26234. static const unsigned char zChars[] =
  26235. "abcdefghijklmnopqrstuvwxyz"
  26236. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  26237. "0123456789";
  26238. unsigned int i, j;
  26239. const char *zDir;
  26240. /* It's odd to simulate an io-error here, but really this is just
  26241. ** using the io-error infrastructure to test that SQLite handles this
  26242. ** function failing.
  26243. */
  26244. SimulateIOError( return SQLITE_IOERR );
  26245. zDir = unixTempFileDir();
  26246. if( zDir==0 ) zDir = ".";
  26247. /* Check that the output buffer is large enough for the temporary file
  26248. ** name. If it is not, return SQLITE_ERROR.
  26249. */
  26250. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  26251. return SQLITE_ERROR;
  26252. }
  26253. do{
  26254. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  26255. j = (int)strlen(zBuf);
  26256. sqlite3_randomness(15, &zBuf[j]);
  26257. for(i=0; i<15; i++, j++){
  26258. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  26259. }
  26260. zBuf[j] = 0;
  26261. zBuf[j+1] = 0;
  26262. }while( osAccess(zBuf,0)==0 );
  26263. return SQLITE_OK;
  26264. }
  26265. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26266. /*
  26267. ** Routine to transform a unixFile into a proxy-locking unixFile.
  26268. ** Implementation in the proxy-lock division, but used by unixOpen()
  26269. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  26270. */
  26271. static int proxyTransformUnixFile(unixFile*, const char*);
  26272. #endif
  26273. /*
  26274. ** Search for an unused file descriptor that was opened on the database
  26275. ** file (not a journal or master-journal file) identified by pathname
  26276. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  26277. ** argument to this function.
  26278. **
  26279. ** Such a file descriptor may exist if a database connection was closed
  26280. ** but the associated file descriptor could not be closed because some
  26281. ** other file descriptor open on the same file is holding a file-lock.
  26282. ** Refer to comments in the unixClose() function and the lengthy comment
  26283. ** describing "Posix Advisory Locking" at the start of this file for
  26284. ** further details. Also, ticket #4018.
  26285. **
  26286. ** If a suitable file descriptor is found, then it is returned. If no
  26287. ** such file descriptor is located, -1 is returned.
  26288. */
  26289. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  26290. UnixUnusedFd *pUnused = 0;
  26291. /* Do not search for an unused file descriptor on vxworks. Not because
  26292. ** vxworks would not benefit from the change (it might, we're not sure),
  26293. ** but because no way to test it is currently available. It is better
  26294. ** not to risk breaking vxworks support for the sake of such an obscure
  26295. ** feature. */
  26296. #if !OS_VXWORKS
  26297. struct stat sStat; /* Results of stat() call */
  26298. /* A stat() call may fail for various reasons. If this happens, it is
  26299. ** almost certain that an open() call on the same path will also fail.
  26300. ** For this reason, if an error occurs in the stat() call here, it is
  26301. ** ignored and -1 is returned. The caller will try to open a new file
  26302. ** descriptor on the same path, fail, and return an error to SQLite.
  26303. **
  26304. ** Even if a subsequent open() call does succeed, the consequences of
  26305. ** not searching for a resusable file descriptor are not dire. */
  26306. if( 0==osStat(zPath, &sStat) ){
  26307. unixInodeInfo *pInode;
  26308. unixEnterMutex();
  26309. pInode = inodeList;
  26310. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  26311. || pInode->fileId.ino!=sStat.st_ino) ){
  26312. pInode = pInode->pNext;
  26313. }
  26314. if( pInode ){
  26315. UnixUnusedFd **pp;
  26316. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  26317. pUnused = *pp;
  26318. if( pUnused ){
  26319. *pp = pUnused->pNext;
  26320. }
  26321. }
  26322. unixLeaveMutex();
  26323. }
  26324. #endif /* if !OS_VXWORKS */
  26325. return pUnused;
  26326. }
  26327. /*
  26328. ** This function is called by unixOpen() to determine the unix permissions
  26329. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  26330. ** and a value suitable for passing as the third argument to open(2) is
  26331. ** written to *pMode. If an IO error occurs, an SQLite error code is
  26332. ** returned and the value of *pMode is not modified.
  26333. **
  26334. ** In most cases cases, this routine sets *pMode to 0, which will become
  26335. ** an indication to robust_open() to create the file using
  26336. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  26337. ** But if the file being opened is a WAL or regular journal file, then
  26338. ** this function queries the file-system for the permissions on the
  26339. ** corresponding database file and sets *pMode to this value. Whenever
  26340. ** possible, WAL and journal files are created using the same permissions
  26341. ** as the associated database file.
  26342. **
  26343. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  26344. ** original filename is unavailable. But 8_3_NAMES is only used for
  26345. ** FAT filesystems and permissions do not matter there, so just use
  26346. ** the default permissions.
  26347. */
  26348. static int findCreateFileMode(
  26349. const char *zPath, /* Path of file (possibly) being created */
  26350. int flags, /* Flags passed as 4th argument to xOpen() */
  26351. mode_t *pMode, /* OUT: Permissions to open file with */
  26352. uid_t *pUid, /* OUT: uid to set on the file */
  26353. gid_t *pGid /* OUT: gid to set on the file */
  26354. ){
  26355. int rc = SQLITE_OK; /* Return Code */
  26356. *pMode = 0;
  26357. *pUid = 0;
  26358. *pGid = 0;
  26359. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  26360. char zDb[MAX_PATHNAME+1]; /* Database file path */
  26361. int nDb; /* Number of valid bytes in zDb */
  26362. struct stat sStat; /* Output of stat() on database file */
  26363. /* zPath is a path to a WAL or journal file. The following block derives
  26364. ** the path to the associated database file from zPath. This block handles
  26365. ** the following naming conventions:
  26366. **
  26367. ** "<path to db>-journal"
  26368. ** "<path to db>-wal"
  26369. ** "<path to db>-journalNN"
  26370. ** "<path to db>-walNN"
  26371. **
  26372. ** where NN is a decimal number. The NN naming schemes are
  26373. ** used by the test_multiplex.c module.
  26374. */
  26375. nDb = sqlite3Strlen30(zPath) - 1;
  26376. #ifdef SQLITE_ENABLE_8_3_NAMES
  26377. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  26378. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  26379. #else
  26380. while( zPath[nDb]!='-' ){
  26381. assert( nDb>0 );
  26382. assert( zPath[nDb]!='\n' );
  26383. nDb--;
  26384. }
  26385. #endif
  26386. memcpy(zDb, zPath, nDb);
  26387. zDb[nDb] = '\0';
  26388. if( 0==osStat(zDb, &sStat) ){
  26389. *pMode = sStat.st_mode & 0777;
  26390. *pUid = sStat.st_uid;
  26391. *pGid = sStat.st_gid;
  26392. }else{
  26393. rc = SQLITE_IOERR_FSTAT;
  26394. }
  26395. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  26396. *pMode = 0600;
  26397. }
  26398. return rc;
  26399. }
  26400. /*
  26401. ** Open the file zPath.
  26402. **
  26403. ** Previously, the SQLite OS layer used three functions in place of this
  26404. ** one:
  26405. **
  26406. ** sqlite3OsOpenReadWrite();
  26407. ** sqlite3OsOpenReadOnly();
  26408. ** sqlite3OsOpenExclusive();
  26409. **
  26410. ** These calls correspond to the following combinations of flags:
  26411. **
  26412. ** ReadWrite() -> (READWRITE | CREATE)
  26413. ** ReadOnly() -> (READONLY)
  26414. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  26415. **
  26416. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  26417. ** true, the file was configured to be automatically deleted when the
  26418. ** file handle closed. To achieve the same effect using this new
  26419. ** interface, add the DELETEONCLOSE flag to those specified above for
  26420. ** OpenExclusive().
  26421. */
  26422. static int unixOpen(
  26423. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  26424. const char *zPath, /* Pathname of file to be opened */
  26425. sqlite3_file *pFile, /* The file descriptor to be filled in */
  26426. int flags, /* Input flags to control the opening */
  26427. int *pOutFlags /* Output flags returned to SQLite core */
  26428. ){
  26429. unixFile *p = (unixFile *)pFile;
  26430. int fd = -1; /* File descriptor returned by open() */
  26431. int openFlags = 0; /* Flags to pass to open() */
  26432. int eType = flags&0xFFFFFF00; /* Type of file to open */
  26433. int noLock; /* True to omit locking primitives */
  26434. int rc = SQLITE_OK; /* Function Return Code */
  26435. int ctrlFlags = 0; /* UNIXFILE_* flags */
  26436. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  26437. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  26438. int isCreate = (flags & SQLITE_OPEN_CREATE);
  26439. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  26440. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  26441. #if SQLITE_ENABLE_LOCKING_STYLE
  26442. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  26443. #endif
  26444. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  26445. struct statfs fsInfo;
  26446. #endif
  26447. /* If creating a master or main-file journal, this function will open
  26448. ** a file-descriptor on the directory too. The first time unixSync()
  26449. ** is called the directory file descriptor will be fsync()ed and close()d.
  26450. */
  26451. int syncDir = (isCreate && (
  26452. eType==SQLITE_OPEN_MASTER_JOURNAL
  26453. || eType==SQLITE_OPEN_MAIN_JOURNAL
  26454. || eType==SQLITE_OPEN_WAL
  26455. ));
  26456. /* If argument zPath is a NULL pointer, this function is required to open
  26457. ** a temporary file. Use this buffer to store the file name in.
  26458. */
  26459. char zTmpname[MAX_PATHNAME+2];
  26460. const char *zName = zPath;
  26461. /* Check the following statements are true:
  26462. **
  26463. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  26464. ** (b) if CREATE is set, then READWRITE must also be set, and
  26465. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  26466. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  26467. */
  26468. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  26469. assert(isCreate==0 || isReadWrite);
  26470. assert(isExclusive==0 || isCreate);
  26471. assert(isDelete==0 || isCreate);
  26472. /* The main DB, main journal, WAL file and master journal are never
  26473. ** automatically deleted. Nor are they ever temporary files. */
  26474. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  26475. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  26476. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  26477. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  26478. /* Assert that the upper layer has set one of the "file-type" flags. */
  26479. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  26480. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  26481. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  26482. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  26483. );
  26484. memset(p, 0, sizeof(unixFile));
  26485. if( eType==SQLITE_OPEN_MAIN_DB ){
  26486. UnixUnusedFd *pUnused;
  26487. pUnused = findReusableFd(zName, flags);
  26488. if( pUnused ){
  26489. fd = pUnused->fd;
  26490. }else{
  26491. pUnused = sqlite3_malloc(sizeof(*pUnused));
  26492. if( !pUnused ){
  26493. return SQLITE_NOMEM;
  26494. }
  26495. }
  26496. p->pUnused = pUnused;
  26497. /* Database filenames are double-zero terminated if they are not
  26498. ** URIs with parameters. Hence, they can always be passed into
  26499. ** sqlite3_uri_parameter(). */
  26500. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  26501. }else if( !zName ){
  26502. /* If zName is NULL, the upper layer is requesting a temp file. */
  26503. assert(isDelete && !syncDir);
  26504. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  26505. if( rc!=SQLITE_OK ){
  26506. return rc;
  26507. }
  26508. zName = zTmpname;
  26509. /* Generated temporary filenames are always double-zero terminated
  26510. ** for use by sqlite3_uri_parameter(). */
  26511. assert( zName[strlen(zName)+1]==0 );
  26512. }
  26513. /* Determine the value of the flags parameter passed to POSIX function
  26514. ** open(). These must be calculated even if open() is not called, as
  26515. ** they may be stored as part of the file handle and used by the
  26516. ** 'conch file' locking functions later on. */
  26517. if( isReadonly ) openFlags |= O_RDONLY;
  26518. if( isReadWrite ) openFlags |= O_RDWR;
  26519. if( isCreate ) openFlags |= O_CREAT;
  26520. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  26521. openFlags |= (O_LARGEFILE|O_BINARY);
  26522. if( fd<0 ){
  26523. mode_t openMode; /* Permissions to create file with */
  26524. uid_t uid; /* Userid for the file */
  26525. gid_t gid; /* Groupid for the file */
  26526. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  26527. if( rc!=SQLITE_OK ){
  26528. assert( !p->pUnused );
  26529. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  26530. return rc;
  26531. }
  26532. fd = robust_open(zName, openFlags, openMode);
  26533. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  26534. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  26535. /* Failed to open the file for read/write access. Try read-only. */
  26536. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  26537. openFlags &= ~(O_RDWR|O_CREAT);
  26538. flags |= SQLITE_OPEN_READONLY;
  26539. openFlags |= O_RDONLY;
  26540. isReadonly = 1;
  26541. fd = robust_open(zName, openFlags, openMode);
  26542. }
  26543. if( fd<0 ){
  26544. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  26545. goto open_finished;
  26546. }
  26547. /* If this process is running as root and if creating a new rollback
  26548. ** journal or WAL file, set the ownership of the journal or WAL to be
  26549. ** the same as the original database.
  26550. */
  26551. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  26552. osFchown(fd, uid, gid);
  26553. }
  26554. }
  26555. assert( fd>=0 );
  26556. if( pOutFlags ){
  26557. *pOutFlags = flags;
  26558. }
  26559. if( p->pUnused ){
  26560. p->pUnused->fd = fd;
  26561. p->pUnused->flags = flags;
  26562. }
  26563. if( isDelete ){
  26564. #if OS_VXWORKS
  26565. zPath = zName;
  26566. #else
  26567. osUnlink(zName);
  26568. #endif
  26569. }
  26570. #if SQLITE_ENABLE_LOCKING_STYLE
  26571. else{
  26572. p->openFlags = openFlags;
  26573. }
  26574. #endif
  26575. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  26576. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  26577. if( fstatfs(fd, &fsInfo) == -1 ){
  26578. ((unixFile*)pFile)->lastErrno = errno;
  26579. robust_close(p, fd, __LINE__);
  26580. return SQLITE_IOERR_ACCESS;
  26581. }
  26582. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  26583. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  26584. }
  26585. #endif
  26586. /* Set up appropriate ctrlFlags */
  26587. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  26588. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  26589. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  26590. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  26591. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  26592. #if SQLITE_ENABLE_LOCKING_STYLE
  26593. #if SQLITE_PREFER_PROXY_LOCKING
  26594. isAutoProxy = 1;
  26595. #endif
  26596. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  26597. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  26598. int useProxy = 0;
  26599. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  26600. ** never use proxy, NULL means use proxy for non-local files only. */
  26601. if( envforce!=NULL ){
  26602. useProxy = atoi(envforce)>0;
  26603. }else{
  26604. if( statfs(zPath, &fsInfo) == -1 ){
  26605. /* In theory, the close(fd) call is sub-optimal. If the file opened
  26606. ** with fd is a database file, and there are other connections open
  26607. ** on that file that are currently holding advisory locks on it,
  26608. ** then the call to close() will cancel those locks. In practice,
  26609. ** we're assuming that statfs() doesn't fail very often. At least
  26610. ** not while other file descriptors opened by the same process on
  26611. ** the same file are working. */
  26612. p->lastErrno = errno;
  26613. robust_close(p, fd, __LINE__);
  26614. rc = SQLITE_IOERR_ACCESS;
  26615. goto open_finished;
  26616. }
  26617. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  26618. }
  26619. if( useProxy ){
  26620. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  26621. if( rc==SQLITE_OK ){
  26622. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  26623. if( rc!=SQLITE_OK ){
  26624. /* Use unixClose to clean up the resources added in fillInUnixFile
  26625. ** and clear all the structure's references. Specifically,
  26626. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  26627. */
  26628. unixClose(pFile);
  26629. return rc;
  26630. }
  26631. }
  26632. goto open_finished;
  26633. }
  26634. }
  26635. #endif
  26636. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  26637. open_finished:
  26638. if( rc!=SQLITE_OK ){
  26639. sqlite3_free(p->pUnused);
  26640. }
  26641. return rc;
  26642. }
  26643. /*
  26644. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  26645. ** the directory after deleting the file.
  26646. */
  26647. static int unixDelete(
  26648. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  26649. const char *zPath, /* Name of file to be deleted */
  26650. int dirSync /* If true, fsync() directory after deleting file */
  26651. ){
  26652. int rc = SQLITE_OK;
  26653. UNUSED_PARAMETER(NotUsed);
  26654. SimulateIOError(return SQLITE_IOERR_DELETE);
  26655. if( osUnlink(zPath)==(-1) ){
  26656. if( errno==ENOENT ){
  26657. rc = SQLITE_IOERR_DELETE_NOENT;
  26658. }else{
  26659. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  26660. }
  26661. return rc;
  26662. }
  26663. #ifndef SQLITE_DISABLE_DIRSYNC
  26664. if( (dirSync & 1)!=0 ){
  26665. int fd;
  26666. rc = osOpenDirectory(zPath, &fd);
  26667. if( rc==SQLITE_OK ){
  26668. #if OS_VXWORKS
  26669. if( fsync(fd)==-1 )
  26670. #else
  26671. if( fsync(fd) )
  26672. #endif
  26673. {
  26674. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  26675. }
  26676. robust_close(0, fd, __LINE__);
  26677. }else if( rc==SQLITE_CANTOPEN ){
  26678. rc = SQLITE_OK;
  26679. }
  26680. }
  26681. #endif
  26682. return rc;
  26683. }
  26684. /*
  26685. ** Test the existance of or access permissions of file zPath. The
  26686. ** test performed depends on the value of flags:
  26687. **
  26688. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  26689. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  26690. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  26691. **
  26692. ** Otherwise return 0.
  26693. */
  26694. static int unixAccess(
  26695. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  26696. const char *zPath, /* Path of the file to examine */
  26697. int flags, /* What do we want to learn about the zPath file? */
  26698. int *pResOut /* Write result boolean here */
  26699. ){
  26700. int amode = 0;
  26701. UNUSED_PARAMETER(NotUsed);
  26702. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  26703. switch( flags ){
  26704. case SQLITE_ACCESS_EXISTS:
  26705. amode = F_OK;
  26706. break;
  26707. case SQLITE_ACCESS_READWRITE:
  26708. amode = W_OK|R_OK;
  26709. break;
  26710. case SQLITE_ACCESS_READ:
  26711. amode = R_OK;
  26712. break;
  26713. default:
  26714. assert(!"Invalid flags argument");
  26715. }
  26716. *pResOut = (osAccess(zPath, amode)==0);
  26717. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  26718. struct stat buf;
  26719. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  26720. *pResOut = 0;
  26721. }
  26722. }
  26723. return SQLITE_OK;
  26724. }
  26725. /*
  26726. ** Turn a relative pathname into a full pathname. The relative path
  26727. ** is stored as a nul-terminated string in the buffer pointed to by
  26728. ** zPath.
  26729. **
  26730. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  26731. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  26732. ** this buffer before returning.
  26733. */
  26734. static int unixFullPathname(
  26735. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26736. const char *zPath, /* Possibly relative input path */
  26737. int nOut, /* Size of output buffer in bytes */
  26738. char *zOut /* Output buffer */
  26739. ){
  26740. /* It's odd to simulate an io-error here, but really this is just
  26741. ** using the io-error infrastructure to test that SQLite handles this
  26742. ** function failing. This function could fail if, for example, the
  26743. ** current working directory has been unlinked.
  26744. */
  26745. SimulateIOError( return SQLITE_ERROR );
  26746. assert( pVfs->mxPathname==MAX_PATHNAME );
  26747. UNUSED_PARAMETER(pVfs);
  26748. zOut[nOut-1] = '\0';
  26749. if( zPath[0]=='/' ){
  26750. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  26751. }else{
  26752. int nCwd;
  26753. if( osGetcwd(zOut, nOut-1)==0 ){
  26754. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  26755. }
  26756. nCwd = (int)strlen(zOut);
  26757. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  26758. }
  26759. return SQLITE_OK;
  26760. }
  26761. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  26762. /*
  26763. ** Interfaces for opening a shared library, finding entry points
  26764. ** within the shared library, and closing the shared library.
  26765. */
  26766. #include <dlfcn.h>
  26767. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  26768. UNUSED_PARAMETER(NotUsed);
  26769. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  26770. }
  26771. /*
  26772. ** SQLite calls this function immediately after a call to unixDlSym() or
  26773. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  26774. ** message is available, it is written to zBufOut. If no error message
  26775. ** is available, zBufOut is left unmodified and SQLite uses a default
  26776. ** error message.
  26777. */
  26778. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  26779. const char *zErr;
  26780. UNUSED_PARAMETER(NotUsed);
  26781. unixEnterMutex();
  26782. zErr = dlerror();
  26783. if( zErr ){
  26784. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  26785. }
  26786. unixLeaveMutex();
  26787. }
  26788. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  26789. /*
  26790. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  26791. ** cast into a pointer to a function. And yet the library dlsym() routine
  26792. ** returns a void* which is really a pointer to a function. So how do we
  26793. ** use dlsym() with -pedantic-errors?
  26794. **
  26795. ** Variable x below is defined to be a pointer to a function taking
  26796. ** parameters void* and const char* and returning a pointer to a function.
  26797. ** We initialize x by assigning it a pointer to the dlsym() function.
  26798. ** (That assignment requires a cast.) Then we call the function that
  26799. ** x points to.
  26800. **
  26801. ** This work-around is unlikely to work correctly on any system where
  26802. ** you really cannot cast a function pointer into void*. But then, on the
  26803. ** other hand, dlsym() will not work on such a system either, so we have
  26804. ** not really lost anything.
  26805. */
  26806. void (*(*x)(void*,const char*))(void);
  26807. UNUSED_PARAMETER(NotUsed);
  26808. x = (void(*(*)(void*,const char*))(void))dlsym;
  26809. return (*x)(p, zSym);
  26810. }
  26811. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  26812. UNUSED_PARAMETER(NotUsed);
  26813. dlclose(pHandle);
  26814. }
  26815. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  26816. #define unixDlOpen 0
  26817. #define unixDlError 0
  26818. #define unixDlSym 0
  26819. #define unixDlClose 0
  26820. #endif
  26821. /*
  26822. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  26823. */
  26824. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  26825. UNUSED_PARAMETER(NotUsed);
  26826. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  26827. /* We have to initialize zBuf to prevent valgrind from reporting
  26828. ** errors. The reports issued by valgrind are incorrect - we would
  26829. ** prefer that the randomness be increased by making use of the
  26830. ** uninitialized space in zBuf - but valgrind errors tend to worry
  26831. ** some users. Rather than argue, it seems easier just to initialize
  26832. ** the whole array and silence valgrind, even if that means less randomness
  26833. ** in the random seed.
  26834. **
  26835. ** When testing, initializing zBuf[] to zero is all we do. That means
  26836. ** that we always use the same random number sequence. This makes the
  26837. ** tests repeatable.
  26838. */
  26839. memset(zBuf, 0, nBuf);
  26840. #if !defined(SQLITE_TEST)
  26841. {
  26842. int pid, fd, got;
  26843. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  26844. if( fd<0 ){
  26845. time_t t;
  26846. time(&t);
  26847. memcpy(zBuf, &t, sizeof(t));
  26848. pid = getpid();
  26849. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  26850. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  26851. nBuf = sizeof(t) + sizeof(pid);
  26852. }else{
  26853. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  26854. robust_close(0, fd, __LINE__);
  26855. }
  26856. }
  26857. #endif
  26858. return nBuf;
  26859. }
  26860. /*
  26861. ** Sleep for a little while. Return the amount of time slept.
  26862. ** The argument is the number of microseconds we want to sleep.
  26863. ** The return value is the number of microseconds of sleep actually
  26864. ** requested from the underlying operating system, a number which
  26865. ** might be greater than or equal to the argument, but not less
  26866. ** than the argument.
  26867. */
  26868. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  26869. #if OS_VXWORKS
  26870. struct timespec sp;
  26871. sp.tv_sec = microseconds / 1000000;
  26872. sp.tv_nsec = (microseconds % 1000000) * 1000;
  26873. nanosleep(&sp, NULL);
  26874. UNUSED_PARAMETER(NotUsed);
  26875. return microseconds;
  26876. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  26877. usleep(microseconds);
  26878. UNUSED_PARAMETER(NotUsed);
  26879. return microseconds;
  26880. #else
  26881. int seconds = (microseconds+999999)/1000000;
  26882. sleep(seconds);
  26883. UNUSED_PARAMETER(NotUsed);
  26884. return seconds*1000000;
  26885. #endif
  26886. }
  26887. /*
  26888. ** The following variable, if set to a non-zero value, is interpreted as
  26889. ** the number of seconds since 1970 and is used to set the result of
  26890. ** sqlite3OsCurrentTime() during testing.
  26891. */
  26892. #ifdef SQLITE_TEST
  26893. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  26894. #endif
  26895. /*
  26896. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  26897. ** the current time and date as a Julian Day number times 86_400_000. In
  26898. ** other words, write into *piNow the number of milliseconds since the Julian
  26899. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  26900. ** proleptic Gregorian calendar.
  26901. **
  26902. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  26903. ** cannot be found.
  26904. */
  26905. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  26906. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  26907. int rc = SQLITE_OK;
  26908. #if defined(NO_GETTOD)
  26909. time_t t;
  26910. time(&t);
  26911. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  26912. #elif OS_VXWORKS
  26913. struct timespec sNow;
  26914. clock_gettime(CLOCK_REALTIME, &sNow);
  26915. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  26916. #else
  26917. struct timeval sNow;
  26918. if( gettimeofday(&sNow, 0)==0 ){
  26919. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  26920. }else{
  26921. rc = SQLITE_ERROR;
  26922. }
  26923. #endif
  26924. #ifdef SQLITE_TEST
  26925. if( sqlite3_current_time ){
  26926. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  26927. }
  26928. #endif
  26929. UNUSED_PARAMETER(NotUsed);
  26930. return rc;
  26931. }
  26932. /*
  26933. ** Find the current time (in Universal Coordinated Time). Write the
  26934. ** current time and date as a Julian Day number into *prNow and
  26935. ** return 0. Return 1 if the time and date cannot be found.
  26936. */
  26937. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  26938. sqlite3_int64 i = 0;
  26939. int rc;
  26940. UNUSED_PARAMETER(NotUsed);
  26941. rc = unixCurrentTimeInt64(0, &i);
  26942. *prNow = i/86400000.0;
  26943. return rc;
  26944. }
  26945. /*
  26946. ** We added the xGetLastError() method with the intention of providing
  26947. ** better low-level error messages when operating-system problems come up
  26948. ** during SQLite operation. But so far, none of that has been implemented
  26949. ** in the core. So this routine is never called. For now, it is merely
  26950. ** a place-holder.
  26951. */
  26952. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  26953. UNUSED_PARAMETER(NotUsed);
  26954. UNUSED_PARAMETER(NotUsed2);
  26955. UNUSED_PARAMETER(NotUsed3);
  26956. return 0;
  26957. }
  26958. /*
  26959. ************************ End of sqlite3_vfs methods ***************************
  26960. ******************************************************************************/
  26961. /******************************************************************************
  26962. ************************** Begin Proxy Locking ********************************
  26963. **
  26964. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  26965. ** other locking methods on secondary lock files. Proxy locking is a
  26966. ** meta-layer over top of the primitive locking implemented above. For
  26967. ** this reason, the division that implements of proxy locking is deferred
  26968. ** until late in the file (here) after all of the other I/O methods have
  26969. ** been defined - so that the primitive locking methods are available
  26970. ** as services to help with the implementation of proxy locking.
  26971. **
  26972. ****
  26973. **
  26974. ** The default locking schemes in SQLite use byte-range locks on the
  26975. ** database file to coordinate safe, concurrent access by multiple readers
  26976. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  26977. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  26978. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  26979. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  26980. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  26981. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  26982. ** address in the shared range is taken for a SHARED lock, the entire
  26983. ** shared range is taken for an EXCLUSIVE lock):
  26984. **
  26985. ** PENDING_BYTE 0x40000000
  26986. ** RESERVED_BYTE 0x40000001
  26987. ** SHARED_RANGE 0x40000002 -> 0x40000200
  26988. **
  26989. ** This works well on the local file system, but shows a nearly 100x
  26990. ** slowdown in read performance on AFP because the AFP client disables
  26991. ** the read cache when byte-range locks are present. Enabling the read
  26992. ** cache exposes a cache coherency problem that is present on all OS X
  26993. ** supported network file systems. NFS and AFP both observe the
  26994. ** close-to-open semantics for ensuring cache coherency
  26995. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  26996. ** address the requirements for concurrent database access by multiple
  26997. ** readers and writers
  26998. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  26999. **
  27000. ** To address the performance and cache coherency issues, proxy file locking
  27001. ** changes the way database access is controlled by limiting access to a
  27002. ** single host at a time and moving file locks off of the database file
  27003. ** and onto a proxy file on the local file system.
  27004. **
  27005. **
  27006. ** Using proxy locks
  27007. ** -----------------
  27008. **
  27009. ** C APIs
  27010. **
  27011. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  27012. ** <proxy_path> | ":auto:");
  27013. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  27014. **
  27015. **
  27016. ** SQL pragmas
  27017. **
  27018. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  27019. ** PRAGMA [database.]lock_proxy_file
  27020. **
  27021. ** Specifying ":auto:" means that if there is a conch file with a matching
  27022. ** host ID in it, the proxy path in the conch file will be used, otherwise
  27023. ** a proxy path based on the user's temp dir
  27024. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  27025. ** actual proxy file name is generated from the name and path of the
  27026. ** database file. For example:
  27027. **
  27028. ** For database path "/Users/me/foo.db"
  27029. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  27030. **
  27031. ** Once a lock proxy is configured for a database connection, it can not
  27032. ** be removed, however it may be switched to a different proxy path via
  27033. ** the above APIs (assuming the conch file is not being held by another
  27034. ** connection or process).
  27035. **
  27036. **
  27037. ** How proxy locking works
  27038. ** -----------------------
  27039. **
  27040. ** Proxy file locking relies primarily on two new supporting files:
  27041. **
  27042. ** * conch file to limit access to the database file to a single host
  27043. ** at a time
  27044. **
  27045. ** * proxy file to act as a proxy for the advisory locks normally
  27046. ** taken on the database
  27047. **
  27048. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  27049. ** by taking an sqlite-style shared lock on the conch file, reading the
  27050. ** contents and comparing the host's unique host ID (see below) and lock
  27051. ** proxy path against the values stored in the conch. The conch file is
  27052. ** stored in the same directory as the database file and the file name
  27053. ** is patterned after the database file name as ".<databasename>-conch".
  27054. ** If the conch file does not exist, or it's contents do not match the
  27055. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  27056. ** lock and the conch file contents is updated with the host ID and proxy
  27057. ** path and the lock is downgraded to a shared lock again. If the conch
  27058. ** is held by another process (with a shared lock), the exclusive lock
  27059. ** will fail and SQLITE_BUSY is returned.
  27060. **
  27061. ** The proxy file - a single-byte file used for all advisory file locks
  27062. ** normally taken on the database file. This allows for safe sharing
  27063. ** of the database file for multiple readers and writers on the same
  27064. ** host (the conch ensures that they all use the same local lock file).
  27065. **
  27066. ** Requesting the lock proxy does not immediately take the conch, it is
  27067. ** only taken when the first request to lock database file is made.
  27068. ** This matches the semantics of the traditional locking behavior, where
  27069. ** opening a connection to a database file does not take a lock on it.
  27070. ** The shared lock and an open file descriptor are maintained until
  27071. ** the connection to the database is closed.
  27072. **
  27073. ** The proxy file and the lock file are never deleted so they only need
  27074. ** to be created the first time they are used.
  27075. **
  27076. ** Configuration options
  27077. ** ---------------------
  27078. **
  27079. ** SQLITE_PREFER_PROXY_LOCKING
  27080. **
  27081. ** Database files accessed on non-local file systems are
  27082. ** automatically configured for proxy locking, lock files are
  27083. ** named automatically using the same logic as
  27084. ** PRAGMA lock_proxy_file=":auto:"
  27085. **
  27086. ** SQLITE_PROXY_DEBUG
  27087. **
  27088. ** Enables the logging of error messages during host id file
  27089. ** retrieval and creation
  27090. **
  27091. ** LOCKPROXYDIR
  27092. **
  27093. ** Overrides the default directory used for lock proxy files that
  27094. ** are named automatically via the ":auto:" setting
  27095. **
  27096. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  27097. **
  27098. ** Permissions to use when creating a directory for storing the
  27099. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  27100. **
  27101. **
  27102. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  27103. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  27104. ** force proxy locking to be used for every database file opened, and 0
  27105. ** will force automatic proxy locking to be disabled for all database
  27106. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  27107. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  27108. */
  27109. /*
  27110. ** Proxy locking is only available on MacOSX
  27111. */
  27112. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27113. /*
  27114. ** The proxyLockingContext has the path and file structures for the remote
  27115. ** and local proxy files in it
  27116. */
  27117. typedef struct proxyLockingContext proxyLockingContext;
  27118. struct proxyLockingContext {
  27119. unixFile *conchFile; /* Open conch file */
  27120. char *conchFilePath; /* Name of the conch file */
  27121. unixFile *lockProxy; /* Open proxy lock file */
  27122. char *lockProxyPath; /* Name of the proxy lock file */
  27123. char *dbPath; /* Name of the open file */
  27124. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  27125. void *oldLockingContext; /* Original lockingcontext to restore on close */
  27126. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  27127. };
  27128. /*
  27129. ** The proxy lock file path for the database at dbPath is written into lPath,
  27130. ** which must point to valid, writable memory large enough for a maxLen length
  27131. ** file path.
  27132. */
  27133. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  27134. int len;
  27135. int dbLen;
  27136. int i;
  27137. #ifdef LOCKPROXYDIR
  27138. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  27139. #else
  27140. # ifdef _CS_DARWIN_USER_TEMP_DIR
  27141. {
  27142. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  27143. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  27144. lPath, errno, getpid()));
  27145. return SQLITE_IOERR_LOCK;
  27146. }
  27147. len = strlcat(lPath, "sqliteplocks", maxLen);
  27148. }
  27149. # else
  27150. len = strlcpy(lPath, "/tmp/", maxLen);
  27151. # endif
  27152. #endif
  27153. if( lPath[len-1]!='/' ){
  27154. len = strlcat(lPath, "/", maxLen);
  27155. }
  27156. /* transform the db path to a unique cache name */
  27157. dbLen = (int)strlen(dbPath);
  27158. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  27159. char c = dbPath[i];
  27160. lPath[i+len] = (c=='/')?'_':c;
  27161. }
  27162. lPath[i+len]='\0';
  27163. strlcat(lPath, ":auto:", maxLen);
  27164. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  27165. return SQLITE_OK;
  27166. }
  27167. /*
  27168. ** Creates the lock file and any missing directories in lockPath
  27169. */
  27170. static int proxyCreateLockPath(const char *lockPath){
  27171. int i, len;
  27172. char buf[MAXPATHLEN];
  27173. int start = 0;
  27174. assert(lockPath!=NULL);
  27175. /* try to create all the intermediate directories */
  27176. len = (int)strlen(lockPath);
  27177. buf[0] = lockPath[0];
  27178. for( i=1; i<len; i++ ){
  27179. if( lockPath[i] == '/' && (i - start > 0) ){
  27180. /* only mkdir if leaf dir != "." or "/" or ".." */
  27181. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  27182. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  27183. buf[i]='\0';
  27184. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  27185. int err=errno;
  27186. if( err!=EEXIST ) {
  27187. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  27188. "'%s' proxy lock path=%s pid=%d\n",
  27189. buf, strerror(err), lockPath, getpid()));
  27190. return err;
  27191. }
  27192. }
  27193. }
  27194. start=i+1;
  27195. }
  27196. buf[i] = lockPath[i];
  27197. }
  27198. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  27199. return 0;
  27200. }
  27201. /*
  27202. ** Create a new VFS file descriptor (stored in memory obtained from
  27203. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  27204. **
  27205. ** The caller is responsible not only for closing the file descriptor
  27206. ** but also for freeing the memory associated with the file descriptor.
  27207. */
  27208. static int proxyCreateUnixFile(
  27209. const char *path, /* path for the new unixFile */
  27210. unixFile **ppFile, /* unixFile created and returned by ref */
  27211. int islockfile /* if non zero missing dirs will be created */
  27212. ) {
  27213. int fd = -1;
  27214. unixFile *pNew;
  27215. int rc = SQLITE_OK;
  27216. int openFlags = O_RDWR | O_CREAT;
  27217. sqlite3_vfs dummyVfs;
  27218. int terrno = 0;
  27219. UnixUnusedFd *pUnused = NULL;
  27220. /* 1. first try to open/create the file
  27221. ** 2. if that fails, and this is a lock file (not-conch), try creating
  27222. ** the parent directories and then try again.
  27223. ** 3. if that fails, try to open the file read-only
  27224. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  27225. */
  27226. pUnused = findReusableFd(path, openFlags);
  27227. if( pUnused ){
  27228. fd = pUnused->fd;
  27229. }else{
  27230. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27231. if( !pUnused ){
  27232. return SQLITE_NOMEM;
  27233. }
  27234. }
  27235. if( fd<0 ){
  27236. fd = robust_open(path, openFlags, 0);
  27237. terrno = errno;
  27238. if( fd<0 && errno==ENOENT && islockfile ){
  27239. if( proxyCreateLockPath(path) == SQLITE_OK ){
  27240. fd = robust_open(path, openFlags, 0);
  27241. }
  27242. }
  27243. }
  27244. if( fd<0 ){
  27245. openFlags = O_RDONLY;
  27246. fd = robust_open(path, openFlags, 0);
  27247. terrno = errno;
  27248. }
  27249. if( fd<0 ){
  27250. if( islockfile ){
  27251. return SQLITE_BUSY;
  27252. }
  27253. switch (terrno) {
  27254. case EACCES:
  27255. return SQLITE_PERM;
  27256. case EIO:
  27257. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  27258. default:
  27259. return SQLITE_CANTOPEN_BKPT;
  27260. }
  27261. }
  27262. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  27263. if( pNew==NULL ){
  27264. rc = SQLITE_NOMEM;
  27265. goto end_create_proxy;
  27266. }
  27267. memset(pNew, 0, sizeof(unixFile));
  27268. pNew->openFlags = openFlags;
  27269. memset(&dummyVfs, 0, sizeof(dummyVfs));
  27270. dummyVfs.pAppData = (void*)&autolockIoFinder;
  27271. dummyVfs.zName = "dummy";
  27272. pUnused->fd = fd;
  27273. pUnused->flags = openFlags;
  27274. pNew->pUnused = pUnused;
  27275. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  27276. if( rc==SQLITE_OK ){
  27277. *ppFile = pNew;
  27278. return SQLITE_OK;
  27279. }
  27280. end_create_proxy:
  27281. robust_close(pNew, fd, __LINE__);
  27282. sqlite3_free(pNew);
  27283. sqlite3_free(pUnused);
  27284. return rc;
  27285. }
  27286. #ifdef SQLITE_TEST
  27287. /* simulate multiple hosts by creating unique hostid file paths */
  27288. SQLITE_API int sqlite3_hostid_num = 0;
  27289. #endif
  27290. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  27291. /* Not always defined in the headers as it ought to be */
  27292. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  27293. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  27294. ** bytes of writable memory.
  27295. */
  27296. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  27297. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  27298. memset(pHostID, 0, PROXY_HOSTIDLEN);
  27299. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  27300. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  27301. {
  27302. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  27303. if( gethostuuid(pHostID, &timeout) ){
  27304. int err = errno;
  27305. if( pError ){
  27306. *pError = err;
  27307. }
  27308. return SQLITE_IOERR;
  27309. }
  27310. }
  27311. #else
  27312. UNUSED_PARAMETER(pError);
  27313. #endif
  27314. #ifdef SQLITE_TEST
  27315. /* simulate multiple hosts by creating unique hostid file paths */
  27316. if( sqlite3_hostid_num != 0){
  27317. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  27318. }
  27319. #endif
  27320. return SQLITE_OK;
  27321. }
  27322. /* The conch file contains the header, host id and lock file path
  27323. */
  27324. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  27325. #define PROXY_HEADERLEN 1 /* conch file header length */
  27326. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  27327. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  27328. /*
  27329. ** Takes an open conch file, copies the contents to a new path and then moves
  27330. ** it back. The newly created file's file descriptor is assigned to the
  27331. ** conch file structure and finally the original conch file descriptor is
  27332. ** closed. Returns zero if successful.
  27333. */
  27334. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  27335. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27336. unixFile *conchFile = pCtx->conchFile;
  27337. char tPath[MAXPATHLEN];
  27338. char buf[PROXY_MAXCONCHLEN];
  27339. char *cPath = pCtx->conchFilePath;
  27340. size_t readLen = 0;
  27341. size_t pathLen = 0;
  27342. char errmsg[64] = "";
  27343. int fd = -1;
  27344. int rc = -1;
  27345. UNUSED_PARAMETER(myHostID);
  27346. /* create a new path by replace the trailing '-conch' with '-break' */
  27347. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  27348. if( pathLen>MAXPATHLEN || pathLen<6 ||
  27349. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  27350. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  27351. goto end_breaklock;
  27352. }
  27353. /* read the conch content */
  27354. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  27355. if( readLen<PROXY_PATHINDEX ){
  27356. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  27357. goto end_breaklock;
  27358. }
  27359. /* write it out to the temporary break file */
  27360. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  27361. if( fd<0 ){
  27362. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  27363. goto end_breaklock;
  27364. }
  27365. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  27366. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  27367. goto end_breaklock;
  27368. }
  27369. if( rename(tPath, cPath) ){
  27370. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  27371. goto end_breaklock;
  27372. }
  27373. rc = 0;
  27374. fprintf(stderr, "broke stale lock on %s\n", cPath);
  27375. robust_close(pFile, conchFile->h, __LINE__);
  27376. conchFile->h = fd;
  27377. conchFile->openFlags = O_RDWR | O_CREAT;
  27378. end_breaklock:
  27379. if( rc ){
  27380. if( fd>=0 ){
  27381. osUnlink(tPath);
  27382. robust_close(pFile, fd, __LINE__);
  27383. }
  27384. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  27385. }
  27386. return rc;
  27387. }
  27388. /* Take the requested lock on the conch file and break a stale lock if the
  27389. ** host id matches.
  27390. */
  27391. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  27392. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27393. unixFile *conchFile = pCtx->conchFile;
  27394. int rc = SQLITE_OK;
  27395. int nTries = 0;
  27396. struct timespec conchModTime;
  27397. memset(&conchModTime, 0, sizeof(conchModTime));
  27398. do {
  27399. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  27400. nTries ++;
  27401. if( rc==SQLITE_BUSY ){
  27402. /* If the lock failed (busy):
  27403. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  27404. * 2nd try: fail if the mod time changed or host id is different, wait
  27405. * 10 sec and try again
  27406. * 3rd try: break the lock unless the mod time has changed.
  27407. */
  27408. struct stat buf;
  27409. if( osFstat(conchFile->h, &buf) ){
  27410. pFile->lastErrno = errno;
  27411. return SQLITE_IOERR_LOCK;
  27412. }
  27413. if( nTries==1 ){
  27414. conchModTime = buf.st_mtimespec;
  27415. usleep(500000); /* wait 0.5 sec and try the lock again*/
  27416. continue;
  27417. }
  27418. assert( nTries>1 );
  27419. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  27420. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  27421. return SQLITE_BUSY;
  27422. }
  27423. if( nTries==2 ){
  27424. char tBuf[PROXY_MAXCONCHLEN];
  27425. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  27426. if( len<0 ){
  27427. pFile->lastErrno = errno;
  27428. return SQLITE_IOERR_LOCK;
  27429. }
  27430. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  27431. /* don't break the lock if the host id doesn't match */
  27432. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  27433. return SQLITE_BUSY;
  27434. }
  27435. }else{
  27436. /* don't break the lock on short read or a version mismatch */
  27437. return SQLITE_BUSY;
  27438. }
  27439. usleep(10000000); /* wait 10 sec and try the lock again */
  27440. continue;
  27441. }
  27442. assert( nTries==3 );
  27443. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  27444. rc = SQLITE_OK;
  27445. if( lockType==EXCLUSIVE_LOCK ){
  27446. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  27447. }
  27448. if( !rc ){
  27449. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  27450. }
  27451. }
  27452. }
  27453. } while( rc==SQLITE_BUSY && nTries<3 );
  27454. return rc;
  27455. }
  27456. /* Takes the conch by taking a shared lock and read the contents conch, if
  27457. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  27458. ** lockPath means that the lockPath in the conch file will be used if the
  27459. ** host IDs match, or a new lock path will be generated automatically
  27460. ** and written to the conch file.
  27461. */
  27462. static int proxyTakeConch(unixFile *pFile){
  27463. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27464. if( pCtx->conchHeld!=0 ){
  27465. return SQLITE_OK;
  27466. }else{
  27467. unixFile *conchFile = pCtx->conchFile;
  27468. uuid_t myHostID;
  27469. int pError = 0;
  27470. char readBuf[PROXY_MAXCONCHLEN];
  27471. char lockPath[MAXPATHLEN];
  27472. char *tempLockPath = NULL;
  27473. int rc = SQLITE_OK;
  27474. int createConch = 0;
  27475. int hostIdMatch = 0;
  27476. int readLen = 0;
  27477. int tryOldLockPath = 0;
  27478. int forceNewLockPath = 0;
  27479. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  27480. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  27481. rc = proxyGetHostID(myHostID, &pError);
  27482. if( (rc&0xff)==SQLITE_IOERR ){
  27483. pFile->lastErrno = pError;
  27484. goto end_takeconch;
  27485. }
  27486. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  27487. if( rc!=SQLITE_OK ){
  27488. goto end_takeconch;
  27489. }
  27490. /* read the existing conch file */
  27491. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  27492. if( readLen<0 ){
  27493. /* I/O error: lastErrno set by seekAndRead */
  27494. pFile->lastErrno = conchFile->lastErrno;
  27495. rc = SQLITE_IOERR_READ;
  27496. goto end_takeconch;
  27497. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  27498. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  27499. /* a short read or version format mismatch means we need to create a new
  27500. ** conch file.
  27501. */
  27502. createConch = 1;
  27503. }
  27504. /* if the host id matches and the lock path already exists in the conch
  27505. ** we'll try to use the path there, if we can't open that path, we'll
  27506. ** retry with a new auto-generated path
  27507. */
  27508. do { /* in case we need to try again for an :auto: named lock file */
  27509. if( !createConch && !forceNewLockPath ){
  27510. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  27511. PROXY_HOSTIDLEN);
  27512. /* if the conch has data compare the contents */
  27513. if( !pCtx->lockProxyPath ){
  27514. /* for auto-named local lock file, just check the host ID and we'll
  27515. ** use the local lock file path that's already in there
  27516. */
  27517. if( hostIdMatch ){
  27518. size_t pathLen = (readLen - PROXY_PATHINDEX);
  27519. if( pathLen>=MAXPATHLEN ){
  27520. pathLen=MAXPATHLEN-1;
  27521. }
  27522. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  27523. lockPath[pathLen] = 0;
  27524. tempLockPath = lockPath;
  27525. tryOldLockPath = 1;
  27526. /* create a copy of the lock path if the conch is taken */
  27527. goto end_takeconch;
  27528. }
  27529. }else if( hostIdMatch
  27530. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  27531. readLen-PROXY_PATHINDEX)
  27532. ){
  27533. /* conch host and lock path match */
  27534. goto end_takeconch;
  27535. }
  27536. }
  27537. /* if the conch isn't writable and doesn't match, we can't take it */
  27538. if( (conchFile->openFlags&O_RDWR) == 0 ){
  27539. rc = SQLITE_BUSY;
  27540. goto end_takeconch;
  27541. }
  27542. /* either the conch didn't match or we need to create a new one */
  27543. if( !pCtx->lockProxyPath ){
  27544. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  27545. tempLockPath = lockPath;
  27546. /* create a copy of the lock path _only_ if the conch is taken */
  27547. }
  27548. /* update conch with host and path (this will fail if other process
  27549. ** has a shared lock already), if the host id matches, use the big
  27550. ** stick.
  27551. */
  27552. futimes(conchFile->h, NULL);
  27553. if( hostIdMatch && !createConch ){
  27554. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  27555. /* We are trying for an exclusive lock but another thread in this
  27556. ** same process is still holding a shared lock. */
  27557. rc = SQLITE_BUSY;
  27558. } else {
  27559. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  27560. }
  27561. }else{
  27562. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  27563. }
  27564. if( rc==SQLITE_OK ){
  27565. char writeBuffer[PROXY_MAXCONCHLEN];
  27566. int writeSize = 0;
  27567. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  27568. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  27569. if( pCtx->lockProxyPath!=NULL ){
  27570. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  27571. }else{
  27572. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  27573. }
  27574. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  27575. robust_ftruncate(conchFile->h, writeSize);
  27576. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  27577. fsync(conchFile->h);
  27578. /* If we created a new conch file (not just updated the contents of a
  27579. ** valid conch file), try to match the permissions of the database
  27580. */
  27581. if( rc==SQLITE_OK && createConch ){
  27582. struct stat buf;
  27583. int err = osFstat(pFile->h, &buf);
  27584. if( err==0 ){
  27585. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  27586. S_IROTH|S_IWOTH);
  27587. /* try to match the database file R/W permissions, ignore failure */
  27588. #ifndef SQLITE_PROXY_DEBUG
  27589. osFchmod(conchFile->h, cmode);
  27590. #else
  27591. do{
  27592. rc = osFchmod(conchFile->h, cmode);
  27593. }while( rc==(-1) && errno==EINTR );
  27594. if( rc!=0 ){
  27595. int code = errno;
  27596. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  27597. cmode, code, strerror(code));
  27598. } else {
  27599. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  27600. }
  27601. }else{
  27602. int code = errno;
  27603. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  27604. err, code, strerror(code));
  27605. #endif
  27606. }
  27607. }
  27608. }
  27609. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  27610. end_takeconch:
  27611. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  27612. if( rc==SQLITE_OK && pFile->openFlags ){
  27613. int fd;
  27614. if( pFile->h>=0 ){
  27615. robust_close(pFile, pFile->h, __LINE__);
  27616. }
  27617. pFile->h = -1;
  27618. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  27619. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  27620. if( fd>=0 ){
  27621. pFile->h = fd;
  27622. }else{
  27623. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  27624. during locking */
  27625. }
  27626. }
  27627. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  27628. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  27629. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  27630. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  27631. /* we couldn't create the proxy lock file with the old lock file path
  27632. ** so try again via auto-naming
  27633. */
  27634. forceNewLockPath = 1;
  27635. tryOldLockPath = 0;
  27636. continue; /* go back to the do {} while start point, try again */
  27637. }
  27638. }
  27639. if( rc==SQLITE_OK ){
  27640. /* Need to make a copy of path if we extracted the value
  27641. ** from the conch file or the path was allocated on the stack
  27642. */
  27643. if( tempLockPath ){
  27644. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  27645. if( !pCtx->lockProxyPath ){
  27646. rc = SQLITE_NOMEM;
  27647. }
  27648. }
  27649. }
  27650. if( rc==SQLITE_OK ){
  27651. pCtx->conchHeld = 1;
  27652. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  27653. afpLockingContext *afpCtx;
  27654. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  27655. afpCtx->dbPath = pCtx->lockProxyPath;
  27656. }
  27657. } else {
  27658. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  27659. }
  27660. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  27661. rc==SQLITE_OK?"ok":"failed"));
  27662. return rc;
  27663. } while (1); /* in case we need to retry the :auto: lock file -
  27664. ** we should never get here except via the 'continue' call. */
  27665. }
  27666. }
  27667. /*
  27668. ** If pFile holds a lock on a conch file, then release that lock.
  27669. */
  27670. static int proxyReleaseConch(unixFile *pFile){
  27671. int rc = SQLITE_OK; /* Subroutine return code */
  27672. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  27673. unixFile *conchFile; /* Name of the conch file */
  27674. pCtx = (proxyLockingContext *)pFile->lockingContext;
  27675. conchFile = pCtx->conchFile;
  27676. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  27677. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  27678. getpid()));
  27679. if( pCtx->conchHeld>0 ){
  27680. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  27681. }
  27682. pCtx->conchHeld = 0;
  27683. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  27684. (rc==SQLITE_OK ? "ok" : "failed")));
  27685. return rc;
  27686. }
  27687. /*
  27688. ** Given the name of a database file, compute the name of its conch file.
  27689. ** Store the conch filename in memory obtained from sqlite3_malloc().
  27690. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  27691. ** or SQLITE_NOMEM if unable to obtain memory.
  27692. **
  27693. ** The caller is responsible for ensuring that the allocated memory
  27694. ** space is eventually freed.
  27695. **
  27696. ** *pConchPath is set to NULL if a memory allocation error occurs.
  27697. */
  27698. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  27699. int i; /* Loop counter */
  27700. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  27701. char *conchPath; /* buffer in which to construct conch name */
  27702. /* Allocate space for the conch filename and initialize the name to
  27703. ** the name of the original database file. */
  27704. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  27705. if( conchPath==0 ){
  27706. return SQLITE_NOMEM;
  27707. }
  27708. memcpy(conchPath, dbPath, len+1);
  27709. /* now insert a "." before the last / character */
  27710. for( i=(len-1); i>=0; i-- ){
  27711. if( conchPath[i]=='/' ){
  27712. i++;
  27713. break;
  27714. }
  27715. }
  27716. conchPath[i]='.';
  27717. while ( i<len ){
  27718. conchPath[i+1]=dbPath[i];
  27719. i++;
  27720. }
  27721. /* append the "-conch" suffix to the file */
  27722. memcpy(&conchPath[i+1], "-conch", 7);
  27723. assert( (int)strlen(conchPath) == len+7 );
  27724. return SQLITE_OK;
  27725. }
  27726. /* Takes a fully configured proxy locking-style unix file and switches
  27727. ** the local lock file path
  27728. */
  27729. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  27730. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  27731. char *oldPath = pCtx->lockProxyPath;
  27732. int rc = SQLITE_OK;
  27733. if( pFile->eFileLock!=NO_LOCK ){
  27734. return SQLITE_BUSY;
  27735. }
  27736. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  27737. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  27738. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  27739. return SQLITE_OK;
  27740. }else{
  27741. unixFile *lockProxy = pCtx->lockProxy;
  27742. pCtx->lockProxy=NULL;
  27743. pCtx->conchHeld = 0;
  27744. if( lockProxy!=NULL ){
  27745. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  27746. if( rc ) return rc;
  27747. sqlite3_free(lockProxy);
  27748. }
  27749. sqlite3_free(oldPath);
  27750. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  27751. }
  27752. return rc;
  27753. }
  27754. /*
  27755. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  27756. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  27757. **
  27758. ** This routine find the filename associated with pFile and writes it
  27759. ** int dbPath.
  27760. */
  27761. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  27762. #if defined(__APPLE__)
  27763. if( pFile->pMethod == &afpIoMethods ){
  27764. /* afp style keeps a reference to the db path in the filePath field
  27765. ** of the struct */
  27766. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  27767. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  27768. } else
  27769. #endif
  27770. if( pFile->pMethod == &dotlockIoMethods ){
  27771. /* dot lock style uses the locking context to store the dot lock
  27772. ** file path */
  27773. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  27774. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  27775. }else{
  27776. /* all other styles use the locking context to store the db file path */
  27777. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  27778. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  27779. }
  27780. return SQLITE_OK;
  27781. }
  27782. /*
  27783. ** Takes an already filled in unix file and alters it so all file locking
  27784. ** will be performed on the local proxy lock file. The following fields
  27785. ** are preserved in the locking context so that they can be restored and
  27786. ** the unix structure properly cleaned up at close time:
  27787. ** ->lockingContext
  27788. ** ->pMethod
  27789. */
  27790. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  27791. proxyLockingContext *pCtx;
  27792. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  27793. char *lockPath=NULL;
  27794. int rc = SQLITE_OK;
  27795. if( pFile->eFileLock!=NO_LOCK ){
  27796. return SQLITE_BUSY;
  27797. }
  27798. proxyGetDbPathForUnixFile(pFile, dbPath);
  27799. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  27800. lockPath=NULL;
  27801. }else{
  27802. lockPath=(char *)path;
  27803. }
  27804. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  27805. (lockPath ? lockPath : ":auto:"), getpid()));
  27806. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  27807. if( pCtx==0 ){
  27808. return SQLITE_NOMEM;
  27809. }
  27810. memset(pCtx, 0, sizeof(*pCtx));
  27811. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  27812. if( rc==SQLITE_OK ){
  27813. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  27814. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  27815. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  27816. ** (c) the file system is read-only, then enable no-locking access.
  27817. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  27818. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  27819. */
  27820. struct statfs fsInfo;
  27821. struct stat conchInfo;
  27822. int goLockless = 0;
  27823. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  27824. int err = errno;
  27825. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  27826. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  27827. }
  27828. }
  27829. if( goLockless ){
  27830. pCtx->conchHeld = -1; /* read only FS/ lockless */
  27831. rc = SQLITE_OK;
  27832. }
  27833. }
  27834. }
  27835. if( rc==SQLITE_OK && lockPath ){
  27836. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  27837. }
  27838. if( rc==SQLITE_OK ){
  27839. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  27840. if( pCtx->dbPath==NULL ){
  27841. rc = SQLITE_NOMEM;
  27842. }
  27843. }
  27844. if( rc==SQLITE_OK ){
  27845. /* all memory is allocated, proxys are created and assigned,
  27846. ** switch the locking context and pMethod then return.
  27847. */
  27848. pCtx->oldLockingContext = pFile->lockingContext;
  27849. pFile->lockingContext = pCtx;
  27850. pCtx->pOldMethod = pFile->pMethod;
  27851. pFile->pMethod = &proxyIoMethods;
  27852. }else{
  27853. if( pCtx->conchFile ){
  27854. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  27855. sqlite3_free(pCtx->conchFile);
  27856. }
  27857. sqlite3DbFree(0, pCtx->lockProxyPath);
  27858. sqlite3_free(pCtx->conchFilePath);
  27859. sqlite3_free(pCtx);
  27860. }
  27861. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  27862. (rc==SQLITE_OK ? "ok" : "failed")));
  27863. return rc;
  27864. }
  27865. /*
  27866. ** This routine handles sqlite3_file_control() calls that are specific
  27867. ** to proxy locking.
  27868. */
  27869. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  27870. switch( op ){
  27871. case SQLITE_GET_LOCKPROXYFILE: {
  27872. unixFile *pFile = (unixFile*)id;
  27873. if( pFile->pMethod == &proxyIoMethods ){
  27874. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  27875. proxyTakeConch(pFile);
  27876. if( pCtx->lockProxyPath ){
  27877. *(const char **)pArg = pCtx->lockProxyPath;
  27878. }else{
  27879. *(const char **)pArg = ":auto: (not held)";
  27880. }
  27881. } else {
  27882. *(const char **)pArg = NULL;
  27883. }
  27884. return SQLITE_OK;
  27885. }
  27886. case SQLITE_SET_LOCKPROXYFILE: {
  27887. unixFile *pFile = (unixFile*)id;
  27888. int rc = SQLITE_OK;
  27889. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  27890. if( pArg==NULL || (const char *)pArg==0 ){
  27891. if( isProxyStyle ){
  27892. /* turn off proxy locking - not supported */
  27893. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  27894. }else{
  27895. /* turn off proxy locking - already off - NOOP */
  27896. rc = SQLITE_OK;
  27897. }
  27898. }else{
  27899. const char *proxyPath = (const char *)pArg;
  27900. if( isProxyStyle ){
  27901. proxyLockingContext *pCtx =
  27902. (proxyLockingContext*)pFile->lockingContext;
  27903. if( !strcmp(pArg, ":auto:")
  27904. || (pCtx->lockProxyPath &&
  27905. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  27906. ){
  27907. rc = SQLITE_OK;
  27908. }else{
  27909. rc = switchLockProxyPath(pFile, proxyPath);
  27910. }
  27911. }else{
  27912. /* turn on proxy file locking */
  27913. rc = proxyTransformUnixFile(pFile, proxyPath);
  27914. }
  27915. }
  27916. return rc;
  27917. }
  27918. default: {
  27919. assert( 0 ); /* The call assures that only valid opcodes are sent */
  27920. }
  27921. }
  27922. /*NOTREACHED*/
  27923. return SQLITE_ERROR;
  27924. }
  27925. /*
  27926. ** Within this division (the proxying locking implementation) the procedures
  27927. ** above this point are all utilities. The lock-related methods of the
  27928. ** proxy-locking sqlite3_io_method object follow.
  27929. */
  27930. /*
  27931. ** This routine checks if there is a RESERVED lock held on the specified
  27932. ** file by this or any other process. If such a lock is held, set *pResOut
  27933. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27934. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27935. */
  27936. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27937. unixFile *pFile = (unixFile*)id;
  27938. int rc = proxyTakeConch(pFile);
  27939. if( rc==SQLITE_OK ){
  27940. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27941. if( pCtx->conchHeld>0 ){
  27942. unixFile *proxy = pCtx->lockProxy;
  27943. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  27944. }else{ /* conchHeld < 0 is lockless */
  27945. pResOut=0;
  27946. }
  27947. }
  27948. return rc;
  27949. }
  27950. /*
  27951. ** Lock the file with the lock specified by parameter eFileLock - one
  27952. ** of the following:
  27953. **
  27954. ** (1) SHARED_LOCK
  27955. ** (2) RESERVED_LOCK
  27956. ** (3) PENDING_LOCK
  27957. ** (4) EXCLUSIVE_LOCK
  27958. **
  27959. ** Sometimes when requesting one lock state, additional lock states
  27960. ** are inserted in between. The locking might fail on one of the later
  27961. ** transitions leaving the lock state different from what it started but
  27962. ** still short of its goal. The following chart shows the allowed
  27963. ** transitions and the inserted intermediate states:
  27964. **
  27965. ** UNLOCKED -> SHARED
  27966. ** SHARED -> RESERVED
  27967. ** SHARED -> (PENDING) -> EXCLUSIVE
  27968. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27969. ** PENDING -> EXCLUSIVE
  27970. **
  27971. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27972. ** routine to lower a locking level.
  27973. */
  27974. static int proxyLock(sqlite3_file *id, int eFileLock) {
  27975. unixFile *pFile = (unixFile*)id;
  27976. int rc = proxyTakeConch(pFile);
  27977. if( rc==SQLITE_OK ){
  27978. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  27979. if( pCtx->conchHeld>0 ){
  27980. unixFile *proxy = pCtx->lockProxy;
  27981. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  27982. pFile->eFileLock = proxy->eFileLock;
  27983. }else{
  27984. /* conchHeld < 0 is lockless */
  27985. }
  27986. }
  27987. return rc;
  27988. }
  27989. /*
  27990. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27991. ** must be either NO_LOCK or SHARED_LOCK.
  27992. **
  27993. ** If the locking level of the file descriptor is already at or below
  27994. ** the requested locking level, this routine is a no-op.
  27995. */
  27996. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  27997. unixFile *pFile = (unixFile*)id;
  27998. int rc = proxyTakeConch(pFile);
  27999. if( rc==SQLITE_OK ){
  28000. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28001. if( pCtx->conchHeld>0 ){
  28002. unixFile *proxy = pCtx->lockProxy;
  28003. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  28004. pFile->eFileLock = proxy->eFileLock;
  28005. }else{
  28006. /* conchHeld < 0 is lockless */
  28007. }
  28008. }
  28009. return rc;
  28010. }
  28011. /*
  28012. ** Close a file that uses proxy locks.
  28013. */
  28014. static int proxyClose(sqlite3_file *id) {
  28015. if( id ){
  28016. unixFile *pFile = (unixFile*)id;
  28017. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28018. unixFile *lockProxy = pCtx->lockProxy;
  28019. unixFile *conchFile = pCtx->conchFile;
  28020. int rc = SQLITE_OK;
  28021. if( lockProxy ){
  28022. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  28023. if( rc ) return rc;
  28024. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  28025. if( rc ) return rc;
  28026. sqlite3_free(lockProxy);
  28027. pCtx->lockProxy = 0;
  28028. }
  28029. if( conchFile ){
  28030. if( pCtx->conchHeld ){
  28031. rc = proxyReleaseConch(pFile);
  28032. if( rc ) return rc;
  28033. }
  28034. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  28035. if( rc ) return rc;
  28036. sqlite3_free(conchFile);
  28037. }
  28038. sqlite3DbFree(0, pCtx->lockProxyPath);
  28039. sqlite3_free(pCtx->conchFilePath);
  28040. sqlite3DbFree(0, pCtx->dbPath);
  28041. /* restore the original locking context and pMethod then close it */
  28042. pFile->lockingContext = pCtx->oldLockingContext;
  28043. pFile->pMethod = pCtx->pOldMethod;
  28044. sqlite3_free(pCtx);
  28045. return pFile->pMethod->xClose(id);
  28046. }
  28047. return SQLITE_OK;
  28048. }
  28049. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28050. /*
  28051. ** The proxy locking style is intended for use with AFP filesystems.
  28052. ** And since AFP is only supported on MacOSX, the proxy locking is also
  28053. ** restricted to MacOSX.
  28054. **
  28055. **
  28056. ******************* End of the proxy lock implementation **********************
  28057. ******************************************************************************/
  28058. /*
  28059. ** Initialize the operating system interface.
  28060. **
  28061. ** This routine registers all VFS implementations for unix-like operating
  28062. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  28063. ** should be the only routines in this file that are visible from other
  28064. ** files.
  28065. **
  28066. ** This routine is called once during SQLite initialization and by a
  28067. ** single thread. The memory allocation and mutex subsystems have not
  28068. ** necessarily been initialized when this routine is called, and so they
  28069. ** should not be used.
  28070. */
  28071. SQLITE_API int sqlite3_os_init(void){
  28072. /*
  28073. ** The following macro defines an initializer for an sqlite3_vfs object.
  28074. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  28075. ** to the "finder" function. (pAppData is a pointer to a pointer because
  28076. ** silly C90 rules prohibit a void* from being cast to a function pointer
  28077. ** and so we have to go through the intermediate pointer to avoid problems
  28078. ** when compiling with -pedantic-errors on GCC.)
  28079. **
  28080. ** The FINDER parameter to this macro is the name of the pointer to the
  28081. ** finder-function. The finder-function returns a pointer to the
  28082. ** sqlite_io_methods object that implements the desired locking
  28083. ** behaviors. See the division above that contains the IOMETHODS
  28084. ** macro for addition information on finder-functions.
  28085. **
  28086. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  28087. ** object. But the "autolockIoFinder" available on MacOSX does a little
  28088. ** more than that; it looks at the filesystem type that hosts the
  28089. ** database file and tries to choose an locking method appropriate for
  28090. ** that filesystem time.
  28091. */
  28092. #define UNIXVFS(VFSNAME, FINDER) { \
  28093. 3, /* iVersion */ \
  28094. sizeof(unixFile), /* szOsFile */ \
  28095. MAX_PATHNAME, /* mxPathname */ \
  28096. 0, /* pNext */ \
  28097. VFSNAME, /* zName */ \
  28098. (void*)&FINDER, /* pAppData */ \
  28099. unixOpen, /* xOpen */ \
  28100. unixDelete, /* xDelete */ \
  28101. unixAccess, /* xAccess */ \
  28102. unixFullPathname, /* xFullPathname */ \
  28103. unixDlOpen, /* xDlOpen */ \
  28104. unixDlError, /* xDlError */ \
  28105. unixDlSym, /* xDlSym */ \
  28106. unixDlClose, /* xDlClose */ \
  28107. unixRandomness, /* xRandomness */ \
  28108. unixSleep, /* xSleep */ \
  28109. unixCurrentTime, /* xCurrentTime */ \
  28110. unixGetLastError, /* xGetLastError */ \
  28111. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  28112. unixSetSystemCall, /* xSetSystemCall */ \
  28113. unixGetSystemCall, /* xGetSystemCall */ \
  28114. unixNextSystemCall, /* xNextSystemCall */ \
  28115. }
  28116. /*
  28117. ** All default VFSes for unix are contained in the following array.
  28118. **
  28119. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  28120. ** by the SQLite core when the VFS is registered. So the following
  28121. ** array cannot be const.
  28122. */
  28123. static sqlite3_vfs aVfs[] = {
  28124. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  28125. UNIXVFS("unix", autolockIoFinder ),
  28126. #else
  28127. UNIXVFS("unix", posixIoFinder ),
  28128. #endif
  28129. UNIXVFS("unix-none", nolockIoFinder ),
  28130. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  28131. UNIXVFS("unix-excl", posixIoFinder ),
  28132. #if OS_VXWORKS
  28133. UNIXVFS("unix-namedsem", semIoFinder ),
  28134. #endif
  28135. #if SQLITE_ENABLE_LOCKING_STYLE
  28136. UNIXVFS("unix-posix", posixIoFinder ),
  28137. #if !OS_VXWORKS
  28138. UNIXVFS("unix-flock", flockIoFinder ),
  28139. #endif
  28140. #endif
  28141. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28142. UNIXVFS("unix-afp", afpIoFinder ),
  28143. UNIXVFS("unix-nfs", nfsIoFinder ),
  28144. UNIXVFS("unix-proxy", proxyIoFinder ),
  28145. #endif
  28146. };
  28147. unsigned int i; /* Loop counter */
  28148. /* Double-check that the aSyscall[] array has been constructed
  28149. ** correctly. See ticket [bb3a86e890c8e96ab] */
  28150. assert( ArraySize(aSyscall)==22 );
  28151. /* Register all VFSes defined in the aVfs[] array */
  28152. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  28153. sqlite3_vfs_register(&aVfs[i], i==0);
  28154. }
  28155. return SQLITE_OK;
  28156. }
  28157. /*
  28158. ** Shutdown the operating system interface.
  28159. **
  28160. ** Some operating systems might need to do some cleanup in this routine,
  28161. ** to release dynamically allocated objects. But not on unix.
  28162. ** This routine is a no-op for unix.
  28163. */
  28164. SQLITE_API int sqlite3_os_end(void){
  28165. return SQLITE_OK;
  28166. }
  28167. #endif /* SQLITE_OS_UNIX */
  28168. /************** End of os_unix.c *********************************************/
  28169. /************** Begin file os_win.c ******************************************/
  28170. /*
  28171. ** 2004 May 22
  28172. **
  28173. ** The author disclaims copyright to this source code. In place of
  28174. ** a legal notice, here is a blessing:
  28175. **
  28176. ** May you do good and not evil.
  28177. ** May you find forgiveness for yourself and forgive others.
  28178. ** May you share freely, never taking more than you give.
  28179. **
  28180. ******************************************************************************
  28181. **
  28182. ** This file contains code that is specific to Windows.
  28183. */
  28184. #if SQLITE_OS_WIN /* This file is used for Windows only */
  28185. #ifdef __CYGWIN__
  28186. # include <sys/cygwin.h>
  28187. #endif
  28188. /*
  28189. ** Include code that is common to all os_*.c files
  28190. */
  28191. /************** Include os_common.h in the middle of os_win.c ****************/
  28192. /************** Begin file os_common.h ***************************************/
  28193. /*
  28194. ** 2004 May 22
  28195. **
  28196. ** The author disclaims copyright to this source code. In place of
  28197. ** a legal notice, here is a blessing:
  28198. **
  28199. ** May you do good and not evil.
  28200. ** May you find forgiveness for yourself and forgive others.
  28201. ** May you share freely, never taking more than you give.
  28202. **
  28203. ******************************************************************************
  28204. **
  28205. ** This file contains macros and a little bit of code that is common to
  28206. ** all of the platform-specific files (os_*.c) and is #included into those
  28207. ** files.
  28208. **
  28209. ** This file should be #included by the os_*.c files only. It is not a
  28210. ** general purpose header file.
  28211. */
  28212. #ifndef _OS_COMMON_H_
  28213. #define _OS_COMMON_H_
  28214. /*
  28215. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28216. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28217. ** switch. The following code should catch this problem at compile-time.
  28218. */
  28219. #ifdef MEMORY_DEBUG
  28220. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28221. #endif
  28222. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28223. # ifndef SQLITE_DEBUG_OS_TRACE
  28224. # define SQLITE_DEBUG_OS_TRACE 0
  28225. # endif
  28226. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  28227. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  28228. #else
  28229. # define OSTRACE(X)
  28230. #endif
  28231. /*
  28232. ** Macros for performance tracing. Normally turned off. Only works
  28233. ** on i486 hardware.
  28234. */
  28235. #ifdef SQLITE_PERFORMANCE_TRACE
  28236. /*
  28237. ** hwtime.h contains inline assembler code for implementing
  28238. ** high-performance timing routines.
  28239. */
  28240. /************** Include hwtime.h in the middle of os_common.h ****************/
  28241. /************** Begin file hwtime.h ******************************************/
  28242. /*
  28243. ** 2008 May 27
  28244. **
  28245. ** The author disclaims copyright to this source code. In place of
  28246. ** a legal notice, here is a blessing:
  28247. **
  28248. ** May you do good and not evil.
  28249. ** May you find forgiveness for yourself and forgive others.
  28250. ** May you share freely, never taking more than you give.
  28251. **
  28252. ******************************************************************************
  28253. **
  28254. ** This file contains inline asm code for retrieving "high-performance"
  28255. ** counters for x86 class CPUs.
  28256. */
  28257. #ifndef _HWTIME_H_
  28258. #define _HWTIME_H_
  28259. /*
  28260. ** The following routine only works on pentium-class (or newer) processors.
  28261. ** It uses the RDTSC opcode to read the cycle count value out of the
  28262. ** processor and returns that value. This can be used for high-res
  28263. ** profiling.
  28264. */
  28265. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28266. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  28267. #if defined(__GNUC__)
  28268. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28269. unsigned int lo, hi;
  28270. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  28271. return (sqlite_uint64)hi << 32 | lo;
  28272. }
  28273. #elif defined(_MSC_VER)
  28274. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  28275. __asm {
  28276. rdtsc
  28277. ret ; return value at EDX:EAX
  28278. }
  28279. }
  28280. #endif
  28281. #elif (defined(__GNUC__) && defined(__x86_64__))
  28282. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28283. unsigned long val;
  28284. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  28285. return val;
  28286. }
  28287. #elif (defined(__GNUC__) && defined(__ppc__))
  28288. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28289. unsigned long long retval;
  28290. unsigned long junk;
  28291. __asm__ __volatile__ ("\n\
  28292. 1: mftbu %1\n\
  28293. mftb %L0\n\
  28294. mftbu %0\n\
  28295. cmpw %0,%1\n\
  28296. bne 1b"
  28297. : "=r" (retval), "=r" (junk));
  28298. return retval;
  28299. }
  28300. #else
  28301. #error Need implementation of sqlite3Hwtime() for your platform.
  28302. /*
  28303. ** To compile without implementing sqlite3Hwtime() for your platform,
  28304. ** you can remove the above #error and use the following
  28305. ** stub function. You will lose timing support for many
  28306. ** of the debugging and testing utilities, but it should at
  28307. ** least compile and run.
  28308. */
  28309. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  28310. #endif
  28311. #endif /* !defined(_HWTIME_H_) */
  28312. /************** End of hwtime.h **********************************************/
  28313. /************** Continuing where we left off in os_common.h ******************/
  28314. static sqlite_uint64 g_start;
  28315. static sqlite_uint64 g_elapsed;
  28316. #define TIMER_START g_start=sqlite3Hwtime()
  28317. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  28318. #define TIMER_ELAPSED g_elapsed
  28319. #else
  28320. #define TIMER_START
  28321. #define TIMER_END
  28322. #define TIMER_ELAPSED ((sqlite_uint64)0)
  28323. #endif
  28324. /*
  28325. ** If we compile with the SQLITE_TEST macro set, then the following block
  28326. ** of code will give us the ability to simulate a disk I/O error. This
  28327. ** is used for testing the I/O recovery logic.
  28328. */
  28329. #ifdef SQLITE_TEST
  28330. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  28331. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  28332. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  28333. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  28334. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  28335. SQLITE_API int sqlite3_diskfull_pending = 0;
  28336. SQLITE_API int sqlite3_diskfull = 0;
  28337. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  28338. #define SimulateIOError(CODE) \
  28339. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  28340. || sqlite3_io_error_pending-- == 1 ) \
  28341. { local_ioerr(); CODE; }
  28342. static void local_ioerr(){
  28343. IOTRACE(("IOERR\n"));
  28344. sqlite3_io_error_hit++;
  28345. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  28346. }
  28347. #define SimulateDiskfullError(CODE) \
  28348. if( sqlite3_diskfull_pending ){ \
  28349. if( sqlite3_diskfull_pending == 1 ){ \
  28350. local_ioerr(); \
  28351. sqlite3_diskfull = 1; \
  28352. sqlite3_io_error_hit = 1; \
  28353. CODE; \
  28354. }else{ \
  28355. sqlite3_diskfull_pending--; \
  28356. } \
  28357. }
  28358. #else
  28359. #define SimulateIOErrorBenign(X)
  28360. #define SimulateIOError(A)
  28361. #define SimulateDiskfullError(A)
  28362. #endif
  28363. /*
  28364. ** When testing, keep a count of the number of open files.
  28365. */
  28366. #ifdef SQLITE_TEST
  28367. SQLITE_API int sqlite3_open_file_count = 0;
  28368. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  28369. #else
  28370. #define OpenCounter(X)
  28371. #endif
  28372. #endif /* !defined(_OS_COMMON_H_) */
  28373. /************** End of os_common.h *******************************************/
  28374. /************** Continuing where we left off in os_win.c *********************/
  28375. /*
  28376. ** Compiling and using WAL mode requires several APIs that are only
  28377. ** available in Windows platforms based on the NT kernel.
  28378. */
  28379. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  28380. # error "WAL mode requires support from the Windows NT kernel, compile\
  28381. with SQLITE_OMIT_WAL."
  28382. #endif
  28383. /*
  28384. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  28385. ** based on the sub-platform)?
  28386. */
  28387. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  28388. # define SQLITE_WIN32_HAS_ANSI
  28389. #endif
  28390. /*
  28391. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  28392. ** based on the sub-platform)?
  28393. */
  28394. #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
  28395. # define SQLITE_WIN32_HAS_WIDE
  28396. #endif
  28397. /*
  28398. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  28399. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  28400. ** are not present in the header file)?
  28401. */
  28402. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  28403. /*
  28404. ** Two of the file mapping APIs are different under WinRT. Figure out which
  28405. ** set we need.
  28406. */
  28407. #if SQLITE_OS_WINRT
  28408. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  28409. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  28410. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  28411. #else
  28412. #if defined(SQLITE_WIN32_HAS_ANSI)
  28413. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  28414. DWORD, DWORD, DWORD, LPCSTR);
  28415. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  28416. #if defined(SQLITE_WIN32_HAS_WIDE)
  28417. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  28418. DWORD, DWORD, DWORD, LPCWSTR);
  28419. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  28420. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  28421. #endif /* SQLITE_OS_WINRT */
  28422. /*
  28423. ** This file mapping API is common to both Win32 and WinRT.
  28424. */
  28425. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  28426. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  28427. /*
  28428. ** Macro to find the minimum of two numeric values.
  28429. */
  28430. #ifndef MIN
  28431. # define MIN(x,y) ((x)<(y)?(x):(y))
  28432. #endif
  28433. /*
  28434. ** Some Microsoft compilers lack this definition.
  28435. */
  28436. #ifndef INVALID_FILE_ATTRIBUTES
  28437. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  28438. #endif
  28439. #ifndef FILE_FLAG_MASK
  28440. # define FILE_FLAG_MASK (0xFF3C0000)
  28441. #endif
  28442. #ifndef FILE_ATTRIBUTE_MASK
  28443. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  28444. #endif
  28445. #ifndef SQLITE_OMIT_WAL
  28446. /* Forward references */
  28447. typedef struct winShm winShm; /* A connection to shared-memory */
  28448. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  28449. #endif
  28450. /*
  28451. ** WinCE lacks native support for file locking so we have to fake it
  28452. ** with some code of our own.
  28453. */
  28454. #if SQLITE_OS_WINCE
  28455. typedef struct winceLock {
  28456. int nReaders; /* Number of reader locks obtained */
  28457. BOOL bPending; /* Indicates a pending lock has been obtained */
  28458. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  28459. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  28460. } winceLock;
  28461. #endif
  28462. /*
  28463. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  28464. ** portability layer.
  28465. */
  28466. typedef struct winFile winFile;
  28467. struct winFile {
  28468. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  28469. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  28470. HANDLE h; /* Handle for accessing the file */
  28471. u8 locktype; /* Type of lock currently held on this file */
  28472. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  28473. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  28474. DWORD lastErrno; /* The Windows errno from the last I/O error */
  28475. #ifndef SQLITE_OMIT_WAL
  28476. winShm *pShm; /* Instance of shared memory on this file */
  28477. #endif
  28478. const char *zPath; /* Full pathname of this file */
  28479. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  28480. #if SQLITE_OS_WINCE
  28481. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  28482. HANDLE hMutex; /* Mutex used to control access to shared lock */
  28483. HANDLE hShared; /* Shared memory segment used for locking */
  28484. winceLock local; /* Locks obtained by this instance of winFile */
  28485. winceLock *shared; /* Global shared lock memory for the file */
  28486. #endif
  28487. };
  28488. /*
  28489. ** Allowed values for winFile.ctrlFlags
  28490. */
  28491. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  28492. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  28493. /*
  28494. * The size of the buffer used by sqlite3_win32_write_debug().
  28495. */
  28496. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  28497. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  28498. #endif
  28499. /*
  28500. * The value used with sqlite3_win32_set_directory() to specify that
  28501. * the data directory should be changed.
  28502. */
  28503. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  28504. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  28505. #endif
  28506. /*
  28507. * The value used with sqlite3_win32_set_directory() to specify that
  28508. * the temporary directory should be changed.
  28509. */
  28510. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  28511. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  28512. #endif
  28513. /*
  28514. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  28515. * various Win32 API heap functions instead of our own.
  28516. */
  28517. #ifdef SQLITE_WIN32_MALLOC
  28518. /*
  28519. * If this is non-zero, an isolated heap will be created by the native Win32
  28520. * allocator subsystem; otherwise, the default process heap will be used. This
  28521. * setting has no effect when compiling for WinRT. By default, this is enabled
  28522. * and an isolated heap will be created to store all allocated data.
  28523. *
  28524. ******************************************************************************
  28525. * WARNING: It is important to note that when this setting is non-zero and the
  28526. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  28527. * function), all data that was allocated using the isolated heap will
  28528. * be freed immediately and any attempt to access any of that freed
  28529. * data will almost certainly result in an immediate access violation.
  28530. ******************************************************************************
  28531. */
  28532. #ifndef SQLITE_WIN32_HEAP_CREATE
  28533. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  28534. #endif
  28535. /*
  28536. * The initial size of the Win32-specific heap. This value may be zero.
  28537. */
  28538. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  28539. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  28540. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  28541. #endif
  28542. /*
  28543. * The maximum size of the Win32-specific heap. This value may be zero.
  28544. */
  28545. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  28546. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  28547. #endif
  28548. /*
  28549. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  28550. * zero for the default behavior.
  28551. */
  28552. #ifndef SQLITE_WIN32_HEAP_FLAGS
  28553. # define SQLITE_WIN32_HEAP_FLAGS (0)
  28554. #endif
  28555. /*
  28556. ** The winMemData structure stores information required by the Win32-specific
  28557. ** sqlite3_mem_methods implementation.
  28558. */
  28559. typedef struct winMemData winMemData;
  28560. struct winMemData {
  28561. #ifndef NDEBUG
  28562. u32 magic; /* Magic number to detect structure corruption. */
  28563. #endif
  28564. HANDLE hHeap; /* The handle to our heap. */
  28565. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  28566. };
  28567. #ifndef NDEBUG
  28568. #define WINMEM_MAGIC 0x42b2830b
  28569. #endif
  28570. static struct winMemData win_mem_data = {
  28571. #ifndef NDEBUG
  28572. WINMEM_MAGIC,
  28573. #endif
  28574. NULL, FALSE
  28575. };
  28576. #ifndef NDEBUG
  28577. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  28578. #else
  28579. #define winMemAssertMagic()
  28580. #endif
  28581. #define winMemGetHeap() win_mem_data.hHeap
  28582. static void *winMemMalloc(int nBytes);
  28583. static void winMemFree(void *pPrior);
  28584. static void *winMemRealloc(void *pPrior, int nBytes);
  28585. static int winMemSize(void *p);
  28586. static int winMemRoundup(int n);
  28587. static int winMemInit(void *pAppData);
  28588. static void winMemShutdown(void *pAppData);
  28589. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  28590. #endif /* SQLITE_WIN32_MALLOC */
  28591. /*
  28592. ** The following variable is (normally) set once and never changes
  28593. ** thereafter. It records whether the operating system is Win9x
  28594. ** or WinNT.
  28595. **
  28596. ** 0: Operating system unknown.
  28597. ** 1: Operating system is Win9x.
  28598. ** 2: Operating system is WinNT.
  28599. **
  28600. ** In order to facilitate testing on a WinNT system, the test fixture
  28601. ** can manually set this value to 1 to emulate Win98 behavior.
  28602. */
  28603. #ifdef SQLITE_TEST
  28604. SQLITE_API int sqlite3_os_type = 0;
  28605. #else
  28606. static int sqlite3_os_type = 0;
  28607. #endif
  28608. #ifndef SYSCALL
  28609. # define SYSCALL sqlite3_syscall_ptr
  28610. #endif
  28611. /*
  28612. ** This function is not available on Windows CE or WinRT.
  28613. */
  28614. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  28615. # define osAreFileApisANSI() 1
  28616. #endif
  28617. /*
  28618. ** Many system calls are accessed through pointer-to-functions so that
  28619. ** they may be overridden at runtime to facilitate fault injection during
  28620. ** testing and sandboxing. The following array holds the names and pointers
  28621. ** to all overrideable system calls.
  28622. */
  28623. static struct win_syscall {
  28624. const char *zName; /* Name of the sytem call */
  28625. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  28626. sqlite3_syscall_ptr pDefault; /* Default value */
  28627. } aSyscall[] = {
  28628. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  28629. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  28630. #else
  28631. { "AreFileApisANSI", (SYSCALL)0, 0 },
  28632. #endif
  28633. #ifndef osAreFileApisANSI
  28634. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  28635. #endif
  28636. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  28637. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  28638. #else
  28639. { "CharLowerW", (SYSCALL)0, 0 },
  28640. #endif
  28641. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  28642. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  28643. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  28644. #else
  28645. { "CharUpperW", (SYSCALL)0, 0 },
  28646. #endif
  28647. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  28648. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  28649. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  28650. #if defined(SQLITE_WIN32_HAS_ANSI)
  28651. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  28652. #else
  28653. { "CreateFileA", (SYSCALL)0, 0 },
  28654. #endif
  28655. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  28656. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  28657. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28658. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  28659. #else
  28660. { "CreateFileW", (SYSCALL)0, 0 },
  28661. #endif
  28662. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  28663. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  28664. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  28665. !defined(SQLITE_OMIT_WAL))
  28666. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  28667. #else
  28668. { "CreateFileMappingA", (SYSCALL)0, 0 },
  28669. #endif
  28670. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  28671. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  28672. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  28673. !defined(SQLITE_OMIT_WAL))
  28674. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  28675. #else
  28676. { "CreateFileMappingW", (SYSCALL)0, 0 },
  28677. #endif
  28678. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  28679. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  28680. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28681. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  28682. #else
  28683. { "CreateMutexW", (SYSCALL)0, 0 },
  28684. #endif
  28685. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  28686. LPCWSTR))aSyscall[8].pCurrent)
  28687. #if defined(SQLITE_WIN32_HAS_ANSI)
  28688. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  28689. #else
  28690. { "DeleteFileA", (SYSCALL)0, 0 },
  28691. #endif
  28692. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  28693. #if defined(SQLITE_WIN32_HAS_WIDE)
  28694. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  28695. #else
  28696. { "DeleteFileW", (SYSCALL)0, 0 },
  28697. #endif
  28698. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  28699. #if SQLITE_OS_WINCE
  28700. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  28701. #else
  28702. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  28703. #endif
  28704. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  28705. LPFILETIME))aSyscall[11].pCurrent)
  28706. #if SQLITE_OS_WINCE
  28707. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  28708. #else
  28709. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  28710. #endif
  28711. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  28712. LPSYSTEMTIME))aSyscall[12].pCurrent)
  28713. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  28714. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  28715. #if defined(SQLITE_WIN32_HAS_ANSI)
  28716. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  28717. #else
  28718. { "FormatMessageA", (SYSCALL)0, 0 },
  28719. #endif
  28720. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  28721. DWORD,va_list*))aSyscall[14].pCurrent)
  28722. #if defined(SQLITE_WIN32_HAS_WIDE)
  28723. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  28724. #else
  28725. { "FormatMessageW", (SYSCALL)0, 0 },
  28726. #endif
  28727. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  28728. DWORD,va_list*))aSyscall[15].pCurrent)
  28729. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  28730. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  28731. #else
  28732. { "FreeLibrary", (SYSCALL)0, 0 },
  28733. #endif
  28734. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  28735. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  28736. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  28737. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  28738. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  28739. #else
  28740. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  28741. #endif
  28742. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  28743. LPDWORD))aSyscall[18].pCurrent)
  28744. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28745. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  28746. #else
  28747. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  28748. #endif
  28749. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  28750. LPDWORD))aSyscall[19].pCurrent)
  28751. #if defined(SQLITE_WIN32_HAS_ANSI)
  28752. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  28753. #else
  28754. { "GetFileAttributesA", (SYSCALL)0, 0 },
  28755. #endif
  28756. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  28757. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28758. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  28759. #else
  28760. { "GetFileAttributesW", (SYSCALL)0, 0 },
  28761. #endif
  28762. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  28763. #if defined(SQLITE_WIN32_HAS_WIDE)
  28764. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  28765. #else
  28766. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  28767. #endif
  28768. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  28769. LPVOID))aSyscall[22].pCurrent)
  28770. #if !SQLITE_OS_WINRT
  28771. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  28772. #else
  28773. { "GetFileSize", (SYSCALL)0, 0 },
  28774. #endif
  28775. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  28776. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  28777. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  28778. #else
  28779. { "GetFullPathNameA", (SYSCALL)0, 0 },
  28780. #endif
  28781. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  28782. LPSTR*))aSyscall[24].pCurrent)
  28783. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28784. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  28785. #else
  28786. { "GetFullPathNameW", (SYSCALL)0, 0 },
  28787. #endif
  28788. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  28789. LPWSTR*))aSyscall[25].pCurrent)
  28790. { "GetLastError", (SYSCALL)GetLastError, 0 },
  28791. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  28792. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  28793. #if SQLITE_OS_WINCE
  28794. /* The GetProcAddressA() routine is only available on Windows CE. */
  28795. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  28796. #else
  28797. /* All other Windows platforms expect GetProcAddress() to take
  28798. ** an ANSI string regardless of the _UNICODE setting */
  28799. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  28800. #endif
  28801. #else
  28802. { "GetProcAddressA", (SYSCALL)0, 0 },
  28803. #endif
  28804. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  28805. LPCSTR))aSyscall[27].pCurrent)
  28806. #if !SQLITE_OS_WINRT
  28807. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  28808. #else
  28809. { "GetSystemInfo", (SYSCALL)0, 0 },
  28810. #endif
  28811. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  28812. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  28813. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  28814. #if !SQLITE_OS_WINCE
  28815. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  28816. #else
  28817. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  28818. #endif
  28819. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  28820. LPFILETIME))aSyscall[30].pCurrent)
  28821. #if defined(SQLITE_WIN32_HAS_ANSI)
  28822. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  28823. #else
  28824. { "GetTempPathA", (SYSCALL)0, 0 },
  28825. #endif
  28826. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  28827. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  28828. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  28829. #else
  28830. { "GetTempPathW", (SYSCALL)0, 0 },
  28831. #endif
  28832. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  28833. #if !SQLITE_OS_WINRT
  28834. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  28835. #else
  28836. { "GetTickCount", (SYSCALL)0, 0 },
  28837. #endif
  28838. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  28839. #if defined(SQLITE_WIN32_HAS_ANSI)
  28840. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  28841. #else
  28842. { "GetVersionExA", (SYSCALL)0, 0 },
  28843. #endif
  28844. #define osGetVersionExA ((BOOL(WINAPI*)( \
  28845. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  28846. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  28847. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  28848. SIZE_T))aSyscall[35].pCurrent)
  28849. #if !SQLITE_OS_WINRT
  28850. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  28851. #else
  28852. { "HeapCreate", (SYSCALL)0, 0 },
  28853. #endif
  28854. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  28855. SIZE_T))aSyscall[36].pCurrent)
  28856. #if !SQLITE_OS_WINRT
  28857. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  28858. #else
  28859. { "HeapDestroy", (SYSCALL)0, 0 },
  28860. #endif
  28861. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
  28862. { "HeapFree", (SYSCALL)HeapFree, 0 },
  28863. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
  28864. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  28865. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  28866. SIZE_T))aSyscall[39].pCurrent)
  28867. { "HeapSize", (SYSCALL)HeapSize, 0 },
  28868. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  28869. LPCVOID))aSyscall[40].pCurrent)
  28870. #if !SQLITE_OS_WINRT
  28871. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  28872. #else
  28873. { "HeapValidate", (SYSCALL)0, 0 },
  28874. #endif
  28875. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  28876. LPCVOID))aSyscall[41].pCurrent)
  28877. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  28878. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  28879. #else
  28880. { "LoadLibraryA", (SYSCALL)0, 0 },
  28881. #endif
  28882. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
  28883. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  28884. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  28885. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  28886. #else
  28887. { "LoadLibraryW", (SYSCALL)0, 0 },
  28888. #endif
  28889. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
  28890. #if !SQLITE_OS_WINRT
  28891. { "LocalFree", (SYSCALL)LocalFree, 0 },
  28892. #else
  28893. { "LocalFree", (SYSCALL)0, 0 },
  28894. #endif
  28895. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
  28896. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  28897. { "LockFile", (SYSCALL)LockFile, 0 },
  28898. #else
  28899. { "LockFile", (SYSCALL)0, 0 },
  28900. #endif
  28901. #ifndef osLockFile
  28902. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  28903. DWORD))aSyscall[45].pCurrent)
  28904. #endif
  28905. #if !SQLITE_OS_WINCE
  28906. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  28907. #else
  28908. { "LockFileEx", (SYSCALL)0, 0 },
  28909. #endif
  28910. #ifndef osLockFileEx
  28911. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  28912. LPOVERLAPPED))aSyscall[46].pCurrent)
  28913. #endif
  28914. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  28915. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  28916. #else
  28917. { "MapViewOfFile", (SYSCALL)0, 0 },
  28918. #endif
  28919. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  28920. SIZE_T))aSyscall[47].pCurrent)
  28921. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  28922. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  28923. int))aSyscall[48].pCurrent)
  28924. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  28925. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  28926. LARGE_INTEGER*))aSyscall[49].pCurrent)
  28927. { "ReadFile", (SYSCALL)ReadFile, 0 },
  28928. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  28929. LPOVERLAPPED))aSyscall[50].pCurrent)
  28930. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  28931. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
  28932. #if !SQLITE_OS_WINRT
  28933. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  28934. #else
  28935. { "SetFilePointer", (SYSCALL)0, 0 },
  28936. #endif
  28937. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  28938. DWORD))aSyscall[52].pCurrent)
  28939. #if !SQLITE_OS_WINRT
  28940. { "Sleep", (SYSCALL)Sleep, 0 },
  28941. #else
  28942. { "Sleep", (SYSCALL)0, 0 },
  28943. #endif
  28944. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
  28945. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  28946. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  28947. LPFILETIME))aSyscall[54].pCurrent)
  28948. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  28949. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  28950. #else
  28951. { "UnlockFile", (SYSCALL)0, 0 },
  28952. #endif
  28953. #ifndef osUnlockFile
  28954. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  28955. DWORD))aSyscall[55].pCurrent)
  28956. #endif
  28957. #if !SQLITE_OS_WINCE
  28958. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  28959. #else
  28960. { "UnlockFileEx", (SYSCALL)0, 0 },
  28961. #endif
  28962. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  28963. LPOVERLAPPED))aSyscall[56].pCurrent)
  28964. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  28965. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  28966. #else
  28967. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  28968. #endif
  28969. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
  28970. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  28971. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  28972. LPCSTR,LPBOOL))aSyscall[58].pCurrent)
  28973. { "WriteFile", (SYSCALL)WriteFile, 0 },
  28974. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  28975. LPOVERLAPPED))aSyscall[59].pCurrent)
  28976. #if SQLITE_OS_WINRT
  28977. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  28978. #else
  28979. { "CreateEventExW", (SYSCALL)0, 0 },
  28980. #endif
  28981. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  28982. DWORD,DWORD))aSyscall[60].pCurrent)
  28983. #if !SQLITE_OS_WINRT
  28984. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  28985. #else
  28986. { "WaitForSingleObject", (SYSCALL)0, 0 },
  28987. #endif
  28988. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  28989. DWORD))aSyscall[61].pCurrent)
  28990. #if SQLITE_OS_WINRT
  28991. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  28992. #else
  28993. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  28994. #endif
  28995. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  28996. BOOL))aSyscall[62].pCurrent)
  28997. #if SQLITE_OS_WINRT
  28998. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  28999. #else
  29000. { "SetFilePointerEx", (SYSCALL)0, 0 },
  29001. #endif
  29002. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  29003. PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
  29004. #if SQLITE_OS_WINRT
  29005. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  29006. #else
  29007. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  29008. #endif
  29009. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  29010. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
  29011. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29012. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  29013. #else
  29014. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  29015. #endif
  29016. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  29017. SIZE_T))aSyscall[65].pCurrent)
  29018. #if SQLITE_OS_WINRT
  29019. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  29020. #else
  29021. { "CreateFile2", (SYSCALL)0, 0 },
  29022. #endif
  29023. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  29024. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
  29025. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29026. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  29027. #else
  29028. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  29029. #endif
  29030. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  29031. DWORD))aSyscall[67].pCurrent)
  29032. #if SQLITE_OS_WINRT
  29033. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  29034. #else
  29035. { "GetTickCount64", (SYSCALL)0, 0 },
  29036. #endif
  29037. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
  29038. #if SQLITE_OS_WINRT
  29039. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  29040. #else
  29041. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  29042. #endif
  29043. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  29044. LPSYSTEM_INFO))aSyscall[69].pCurrent)
  29045. #if defined(SQLITE_WIN32_HAS_ANSI)
  29046. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  29047. #else
  29048. { "OutputDebugStringA", (SYSCALL)0, 0 },
  29049. #endif
  29050. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
  29051. #if defined(SQLITE_WIN32_HAS_WIDE)
  29052. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  29053. #else
  29054. { "OutputDebugStringW", (SYSCALL)0, 0 },
  29055. #endif
  29056. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
  29057. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  29058. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
  29059. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  29060. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  29061. #else
  29062. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  29063. #endif
  29064. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  29065. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
  29066. }; /* End of the overrideable system calls */
  29067. /*
  29068. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  29069. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  29070. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  29071. ** system call named zName.
  29072. */
  29073. static int winSetSystemCall(
  29074. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  29075. const char *zName, /* Name of system call to override */
  29076. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  29077. ){
  29078. unsigned int i;
  29079. int rc = SQLITE_NOTFOUND;
  29080. UNUSED_PARAMETER(pNotUsed);
  29081. if( zName==0 ){
  29082. /* If no zName is given, restore all system calls to their default
  29083. ** settings and return NULL
  29084. */
  29085. rc = SQLITE_OK;
  29086. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29087. if( aSyscall[i].pDefault ){
  29088. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  29089. }
  29090. }
  29091. }else{
  29092. /* If zName is specified, operate on only the one system call
  29093. ** specified.
  29094. */
  29095. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29096. if( strcmp(zName, aSyscall[i].zName)==0 ){
  29097. if( aSyscall[i].pDefault==0 ){
  29098. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  29099. }
  29100. rc = SQLITE_OK;
  29101. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  29102. aSyscall[i].pCurrent = pNewFunc;
  29103. break;
  29104. }
  29105. }
  29106. }
  29107. return rc;
  29108. }
  29109. /*
  29110. ** Return the value of a system call. Return NULL if zName is not a
  29111. ** recognized system call name. NULL is also returned if the system call
  29112. ** is currently undefined.
  29113. */
  29114. static sqlite3_syscall_ptr winGetSystemCall(
  29115. sqlite3_vfs *pNotUsed,
  29116. const char *zName
  29117. ){
  29118. unsigned int i;
  29119. UNUSED_PARAMETER(pNotUsed);
  29120. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  29121. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  29122. }
  29123. return 0;
  29124. }
  29125. /*
  29126. ** Return the name of the first system call after zName. If zName==NULL
  29127. ** then return the name of the first system call. Return NULL if zName
  29128. ** is the last system call or if zName is not the name of a valid
  29129. ** system call.
  29130. */
  29131. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  29132. int i = -1;
  29133. UNUSED_PARAMETER(p);
  29134. if( zName ){
  29135. for(i=0; i<ArraySize(aSyscall)-1; i++){
  29136. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  29137. }
  29138. }
  29139. for(i++; i<ArraySize(aSyscall); i++){
  29140. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  29141. }
  29142. return 0;
  29143. }
  29144. /*
  29145. ** This function outputs the specified (ANSI) string to the Win32 debugger
  29146. ** (if available).
  29147. */
  29148. SQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){
  29149. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  29150. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  29151. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  29152. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  29153. #if defined(SQLITE_WIN32_HAS_ANSI)
  29154. if( nMin>0 ){
  29155. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29156. memcpy(zDbgBuf, zBuf, nMin);
  29157. osOutputDebugStringA(zDbgBuf);
  29158. }else{
  29159. osOutputDebugStringA(zBuf);
  29160. }
  29161. #elif defined(SQLITE_WIN32_HAS_WIDE)
  29162. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29163. if ( osMultiByteToWideChar(
  29164. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  29165. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  29166. return;
  29167. }
  29168. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  29169. #else
  29170. if( nMin>0 ){
  29171. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  29172. memcpy(zDbgBuf, zBuf, nMin);
  29173. fprintf(stderr, "%s", zDbgBuf);
  29174. }else{
  29175. fprintf(stderr, "%s", zBuf);
  29176. }
  29177. #endif
  29178. }
  29179. /*
  29180. ** The following routine suspends the current thread for at least ms
  29181. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  29182. */
  29183. #if SQLITE_OS_WINRT
  29184. static HANDLE sleepObj = NULL;
  29185. #endif
  29186. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  29187. #if SQLITE_OS_WINRT
  29188. if ( sleepObj==NULL ){
  29189. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  29190. SYNCHRONIZE);
  29191. }
  29192. assert( sleepObj!=NULL );
  29193. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  29194. #else
  29195. osSleep(milliseconds);
  29196. #endif
  29197. }
  29198. /*
  29199. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  29200. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  29201. **
  29202. ** Here is an interesting observation: Win95, Win98, and WinME lack
  29203. ** the LockFileEx() API. But we can still statically link against that
  29204. ** API as long as we don't call it when running Win95/98/ME. A call to
  29205. ** this routine is used to determine if the host is Win95/98/ME or
  29206. ** WinNT/2K/XP so that we will know whether or not we can safely call
  29207. ** the LockFileEx() API.
  29208. */
  29209. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29210. # define isNT() (1)
  29211. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  29212. # define isNT() (0)
  29213. #else
  29214. static int isNT(void){
  29215. if( sqlite3_os_type==0 ){
  29216. OSVERSIONINFOA sInfo;
  29217. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  29218. osGetVersionExA(&sInfo);
  29219. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  29220. }
  29221. return sqlite3_os_type==2;
  29222. }
  29223. #endif
  29224. #ifdef SQLITE_WIN32_MALLOC
  29225. /*
  29226. ** Allocate nBytes of memory.
  29227. */
  29228. static void *winMemMalloc(int nBytes){
  29229. HANDLE hHeap;
  29230. void *p;
  29231. winMemAssertMagic();
  29232. hHeap = winMemGetHeap();
  29233. assert( hHeap!=0 );
  29234. assert( hHeap!=INVALID_HANDLE_VALUE );
  29235. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29236. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29237. #endif
  29238. assert( nBytes>=0 );
  29239. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  29240. if( !p ){
  29241. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
  29242. nBytes, osGetLastError(), (void*)hHeap);
  29243. }
  29244. return p;
  29245. }
  29246. /*
  29247. ** Free memory.
  29248. */
  29249. static void winMemFree(void *pPrior){
  29250. HANDLE hHeap;
  29251. winMemAssertMagic();
  29252. hHeap = winMemGetHeap();
  29253. assert( hHeap!=0 );
  29254. assert( hHeap!=INVALID_HANDLE_VALUE );
  29255. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29256. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  29257. #endif
  29258. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  29259. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  29260. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
  29261. pPrior, osGetLastError(), (void*)hHeap);
  29262. }
  29263. }
  29264. /*
  29265. ** Change the size of an existing memory allocation
  29266. */
  29267. static void *winMemRealloc(void *pPrior, int nBytes){
  29268. HANDLE hHeap;
  29269. void *p;
  29270. winMemAssertMagic();
  29271. hHeap = winMemGetHeap();
  29272. assert( hHeap!=0 );
  29273. assert( hHeap!=INVALID_HANDLE_VALUE );
  29274. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29275. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  29276. #endif
  29277. assert( nBytes>=0 );
  29278. if( !pPrior ){
  29279. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  29280. }else{
  29281. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  29282. }
  29283. if( !p ){
  29284. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
  29285. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  29286. (void*)hHeap);
  29287. }
  29288. return p;
  29289. }
  29290. /*
  29291. ** Return the size of an outstanding allocation, in bytes.
  29292. */
  29293. static int winMemSize(void *p){
  29294. HANDLE hHeap;
  29295. SIZE_T n;
  29296. winMemAssertMagic();
  29297. hHeap = winMemGetHeap();
  29298. assert( hHeap!=0 );
  29299. assert( hHeap!=INVALID_HANDLE_VALUE );
  29300. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29301. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29302. #endif
  29303. if( !p ) return 0;
  29304. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  29305. if( n==(SIZE_T)-1 ){
  29306. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
  29307. p, osGetLastError(), (void*)hHeap);
  29308. return 0;
  29309. }
  29310. return (int)n;
  29311. }
  29312. /*
  29313. ** Round up a request size to the next valid allocation size.
  29314. */
  29315. static int winMemRoundup(int n){
  29316. return n;
  29317. }
  29318. /*
  29319. ** Initialize this module.
  29320. */
  29321. static int winMemInit(void *pAppData){
  29322. winMemData *pWinMemData = (winMemData *)pAppData;
  29323. if( !pWinMemData ) return SQLITE_ERROR;
  29324. assert( pWinMemData->magic==WINMEM_MAGIC );
  29325. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  29326. if( !pWinMemData->hHeap ){
  29327. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  29328. SQLITE_WIN32_HEAP_INIT_SIZE,
  29329. SQLITE_WIN32_HEAP_MAX_SIZE);
  29330. if( !pWinMemData->hHeap ){
  29331. sqlite3_log(SQLITE_NOMEM,
  29332. "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
  29333. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  29334. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  29335. return SQLITE_NOMEM;
  29336. }
  29337. pWinMemData->bOwned = TRUE;
  29338. assert( pWinMemData->bOwned );
  29339. }
  29340. #else
  29341. pWinMemData->hHeap = osGetProcessHeap();
  29342. if( !pWinMemData->hHeap ){
  29343. sqlite3_log(SQLITE_NOMEM,
  29344. "failed to GetProcessHeap (%d)", osGetLastError());
  29345. return SQLITE_NOMEM;
  29346. }
  29347. pWinMemData->bOwned = FALSE;
  29348. assert( !pWinMemData->bOwned );
  29349. #endif
  29350. assert( pWinMemData->hHeap!=0 );
  29351. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  29352. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29353. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29354. #endif
  29355. return SQLITE_OK;
  29356. }
  29357. /*
  29358. ** Deinitialize this module.
  29359. */
  29360. static void winMemShutdown(void *pAppData){
  29361. winMemData *pWinMemData = (winMemData *)pAppData;
  29362. if( !pWinMemData ) return;
  29363. if( pWinMemData->hHeap ){
  29364. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  29365. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  29366. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  29367. #endif
  29368. if( pWinMemData->bOwned ){
  29369. if( !osHeapDestroy(pWinMemData->hHeap) ){
  29370. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
  29371. osGetLastError(), (void*)pWinMemData->hHeap);
  29372. }
  29373. pWinMemData->bOwned = FALSE;
  29374. }
  29375. pWinMemData->hHeap = NULL;
  29376. }
  29377. }
  29378. /*
  29379. ** Populate the low-level memory allocation function pointers in
  29380. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  29381. ** arguments specify the block of memory to manage.
  29382. **
  29383. ** This routine is only called by sqlite3_config(), and therefore
  29384. ** is not required to be threadsafe (it is not).
  29385. */
  29386. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  29387. static const sqlite3_mem_methods winMemMethods = {
  29388. winMemMalloc,
  29389. winMemFree,
  29390. winMemRealloc,
  29391. winMemSize,
  29392. winMemRoundup,
  29393. winMemInit,
  29394. winMemShutdown,
  29395. &win_mem_data
  29396. };
  29397. return &winMemMethods;
  29398. }
  29399. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  29400. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  29401. }
  29402. #endif /* SQLITE_WIN32_MALLOC */
  29403. /*
  29404. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  29405. **
  29406. ** Space to hold the returned string is obtained from malloc.
  29407. */
  29408. static LPWSTR utf8ToUnicode(const char *zFilename){
  29409. int nChar;
  29410. LPWSTR zWideFilename;
  29411. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  29412. if( nChar==0 ){
  29413. return 0;
  29414. }
  29415. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  29416. if( zWideFilename==0 ){
  29417. return 0;
  29418. }
  29419. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  29420. nChar);
  29421. if( nChar==0 ){
  29422. sqlite3_free(zWideFilename);
  29423. zWideFilename = 0;
  29424. }
  29425. return zWideFilename;
  29426. }
  29427. /*
  29428. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  29429. ** obtained from sqlite3_malloc().
  29430. */
  29431. static char *unicodeToUtf8(LPCWSTR zWideFilename){
  29432. int nByte;
  29433. char *zFilename;
  29434. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  29435. if( nByte == 0 ){
  29436. return 0;
  29437. }
  29438. zFilename = sqlite3MallocZero( nByte );
  29439. if( zFilename==0 ){
  29440. return 0;
  29441. }
  29442. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  29443. 0, 0);
  29444. if( nByte == 0 ){
  29445. sqlite3_free(zFilename);
  29446. zFilename = 0;
  29447. }
  29448. return zFilename;
  29449. }
  29450. /*
  29451. ** Convert an ANSI string to Microsoft Unicode, based on the
  29452. ** current codepage settings for file apis.
  29453. **
  29454. ** Space to hold the returned string is obtained
  29455. ** from sqlite3_malloc.
  29456. */
  29457. static LPWSTR mbcsToUnicode(const char *zFilename){
  29458. int nByte;
  29459. LPWSTR zMbcsFilename;
  29460. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  29461. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  29462. 0)*sizeof(WCHAR);
  29463. if( nByte==0 ){
  29464. return 0;
  29465. }
  29466. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  29467. if( zMbcsFilename==0 ){
  29468. return 0;
  29469. }
  29470. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  29471. nByte);
  29472. if( nByte==0 ){
  29473. sqlite3_free(zMbcsFilename);
  29474. zMbcsFilename = 0;
  29475. }
  29476. return zMbcsFilename;
  29477. }
  29478. /*
  29479. ** Convert Microsoft Unicode to multi-byte character string, based on the
  29480. ** user's ANSI codepage.
  29481. **
  29482. ** Space to hold the returned string is obtained from
  29483. ** sqlite3_malloc().
  29484. */
  29485. static char *unicodeToMbcs(LPCWSTR zWideFilename){
  29486. int nByte;
  29487. char *zFilename;
  29488. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  29489. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  29490. if( nByte == 0 ){
  29491. return 0;
  29492. }
  29493. zFilename = sqlite3MallocZero( nByte );
  29494. if( zFilename==0 ){
  29495. return 0;
  29496. }
  29497. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  29498. nByte, 0, 0);
  29499. if( nByte == 0 ){
  29500. sqlite3_free(zFilename);
  29501. zFilename = 0;
  29502. }
  29503. return zFilename;
  29504. }
  29505. /*
  29506. ** Convert multibyte character string to UTF-8. Space to hold the
  29507. ** returned string is obtained from sqlite3_malloc().
  29508. */
  29509. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  29510. char *zFilenameUtf8;
  29511. LPWSTR zTmpWide;
  29512. zTmpWide = mbcsToUnicode(zFilename);
  29513. if( zTmpWide==0 ){
  29514. return 0;
  29515. }
  29516. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  29517. sqlite3_free(zTmpWide);
  29518. return zFilenameUtf8;
  29519. }
  29520. /*
  29521. ** Convert UTF-8 to multibyte character string. Space to hold the
  29522. ** returned string is obtained from sqlite3_malloc().
  29523. */
  29524. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  29525. char *zFilenameMbcs;
  29526. LPWSTR zTmpWide;
  29527. zTmpWide = utf8ToUnicode(zFilename);
  29528. if( zTmpWide==0 ){
  29529. return 0;
  29530. }
  29531. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  29532. sqlite3_free(zTmpWide);
  29533. return zFilenameMbcs;
  29534. }
  29535. /*
  29536. ** This function sets the data directory or the temporary directory based on
  29537. ** the provided arguments. The type argument must be 1 in order to set the
  29538. ** data directory or 2 in order to set the temporary directory. The zValue
  29539. ** argument is the name of the directory to use. The return value will be
  29540. ** SQLITE_OK if successful.
  29541. */
  29542. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  29543. char **ppDirectory = 0;
  29544. #ifndef SQLITE_OMIT_AUTOINIT
  29545. int rc = sqlite3_initialize();
  29546. if( rc ) return rc;
  29547. #endif
  29548. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  29549. ppDirectory = &sqlite3_data_directory;
  29550. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  29551. ppDirectory = &sqlite3_temp_directory;
  29552. }
  29553. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  29554. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  29555. );
  29556. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  29557. if( ppDirectory ){
  29558. char *zValueUtf8 = 0;
  29559. if( zValue && zValue[0] ){
  29560. zValueUtf8 = unicodeToUtf8(zValue);
  29561. if ( zValueUtf8==0 ){
  29562. return SQLITE_NOMEM;
  29563. }
  29564. }
  29565. sqlite3_free(*ppDirectory);
  29566. *ppDirectory = zValueUtf8;
  29567. return SQLITE_OK;
  29568. }
  29569. return SQLITE_ERROR;
  29570. }
  29571. /*
  29572. ** The return value of getLastErrorMsg
  29573. ** is zero if the error message fits in the buffer, or non-zero
  29574. ** otherwise (if the message was truncated).
  29575. */
  29576. static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  29577. /* FormatMessage returns 0 on failure. Otherwise it
  29578. ** returns the number of TCHARs written to the output
  29579. ** buffer, excluding the terminating null char.
  29580. */
  29581. DWORD dwLen = 0;
  29582. char *zOut = 0;
  29583. if( isNT() ){
  29584. #if SQLITE_OS_WINRT
  29585. WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
  29586. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  29587. FORMAT_MESSAGE_IGNORE_INSERTS,
  29588. NULL,
  29589. lastErrno,
  29590. 0,
  29591. zTempWide,
  29592. MAX_PATH,
  29593. 0);
  29594. #else
  29595. LPWSTR zTempWide = NULL;
  29596. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  29597. FORMAT_MESSAGE_FROM_SYSTEM |
  29598. FORMAT_MESSAGE_IGNORE_INSERTS,
  29599. NULL,
  29600. lastErrno,
  29601. 0,
  29602. (LPWSTR) &zTempWide,
  29603. 0,
  29604. 0);
  29605. #endif
  29606. if( dwLen > 0 ){
  29607. /* allocate a buffer and convert to UTF8 */
  29608. sqlite3BeginBenignMalloc();
  29609. zOut = unicodeToUtf8(zTempWide);
  29610. sqlite3EndBenignMalloc();
  29611. #if !SQLITE_OS_WINRT
  29612. /* free the system buffer allocated by FormatMessage */
  29613. osLocalFree(zTempWide);
  29614. #endif
  29615. }
  29616. }
  29617. #ifdef SQLITE_WIN32_HAS_ANSI
  29618. else{
  29619. char *zTemp = NULL;
  29620. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  29621. FORMAT_MESSAGE_FROM_SYSTEM |
  29622. FORMAT_MESSAGE_IGNORE_INSERTS,
  29623. NULL,
  29624. lastErrno,
  29625. 0,
  29626. (LPSTR) &zTemp,
  29627. 0,
  29628. 0);
  29629. if( dwLen > 0 ){
  29630. /* allocate a buffer and convert to UTF8 */
  29631. sqlite3BeginBenignMalloc();
  29632. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  29633. sqlite3EndBenignMalloc();
  29634. /* free the system buffer allocated by FormatMessage */
  29635. osLocalFree(zTemp);
  29636. }
  29637. }
  29638. #endif
  29639. if( 0 == dwLen ){
  29640. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
  29641. }else{
  29642. /* copy a maximum of nBuf chars to output buffer */
  29643. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  29644. /* free the UTF8 buffer */
  29645. sqlite3_free(zOut);
  29646. }
  29647. return 0;
  29648. }
  29649. /*
  29650. **
  29651. ** This function - winLogErrorAtLine() - is only ever called via the macro
  29652. ** winLogError().
  29653. **
  29654. ** This routine is invoked after an error occurs in an OS function.
  29655. ** It logs a message using sqlite3_log() containing the current value of
  29656. ** error code and, if possible, the human-readable equivalent from
  29657. ** FormatMessage.
  29658. **
  29659. ** The first argument passed to the macro should be the error code that
  29660. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  29661. ** The two subsequent arguments should be the name of the OS function that
  29662. ** failed and the associated file-system path, if any.
  29663. */
  29664. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  29665. static int winLogErrorAtLine(
  29666. int errcode, /* SQLite error code */
  29667. DWORD lastErrno, /* Win32 last error */
  29668. const char *zFunc, /* Name of OS function that failed */
  29669. const char *zPath, /* File path associated with error */
  29670. int iLine /* Source line number where error occurred */
  29671. ){
  29672. char zMsg[500]; /* Human readable error text */
  29673. int i; /* Loop counter */
  29674. zMsg[0] = 0;
  29675. getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  29676. assert( errcode!=SQLITE_OK );
  29677. if( zPath==0 ) zPath = "";
  29678. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  29679. zMsg[i] = 0;
  29680. sqlite3_log(errcode,
  29681. "os_win.c:%d: (%d) %s(%s) - %s",
  29682. iLine, lastErrno, zFunc, zPath, zMsg
  29683. );
  29684. return errcode;
  29685. }
  29686. /*
  29687. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  29688. ** will be retried following a locking error - probably caused by
  29689. ** antivirus software. Also the initial delay before the first retry.
  29690. ** The delay increases linearly with each retry.
  29691. */
  29692. #ifndef SQLITE_WIN32_IOERR_RETRY
  29693. # define SQLITE_WIN32_IOERR_RETRY 10
  29694. #endif
  29695. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  29696. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  29697. #endif
  29698. static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  29699. static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  29700. /*
  29701. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  29702. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  29703. ** to give up with an error.
  29704. */
  29705. static int retryIoerr(int *pnRetry, DWORD *pError){
  29706. DWORD e = osGetLastError();
  29707. if( *pnRetry>=win32IoerrRetry ){
  29708. if( pError ){
  29709. *pError = e;
  29710. }
  29711. return 0;
  29712. }
  29713. if( e==ERROR_ACCESS_DENIED ||
  29714. e==ERROR_LOCK_VIOLATION ||
  29715. e==ERROR_SHARING_VIOLATION ){
  29716. sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
  29717. ++*pnRetry;
  29718. return 1;
  29719. }
  29720. if( pError ){
  29721. *pError = e;
  29722. }
  29723. return 0;
  29724. }
  29725. /*
  29726. ** Log a I/O error retry episode.
  29727. */
  29728. static void logIoerr(int nRetry){
  29729. if( nRetry ){
  29730. sqlite3_log(SQLITE_IOERR,
  29731. "delayed %dms for lock/sharing conflict",
  29732. win32IoerrRetryDelay*nRetry*(nRetry+1)/2
  29733. );
  29734. }
  29735. }
  29736. #if SQLITE_OS_WINCE
  29737. /*************************************************************************
  29738. ** This section contains code for WinCE only.
  29739. */
  29740. /*
  29741. ** Windows CE does not have a localtime() function. So create a
  29742. ** substitute.
  29743. */
  29744. /* #include <time.h> */
  29745. struct tm *__cdecl localtime(const time_t *t)
  29746. {
  29747. static struct tm y;
  29748. FILETIME uTm, lTm;
  29749. SYSTEMTIME pTm;
  29750. sqlite3_int64 t64;
  29751. t64 = *t;
  29752. t64 = (t64 + 11644473600)*10000000;
  29753. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  29754. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  29755. osFileTimeToLocalFileTime(&uTm,&lTm);
  29756. osFileTimeToSystemTime(&lTm,&pTm);
  29757. y.tm_year = pTm.wYear - 1900;
  29758. y.tm_mon = pTm.wMonth - 1;
  29759. y.tm_wday = pTm.wDayOfWeek;
  29760. y.tm_mday = pTm.wDay;
  29761. y.tm_hour = pTm.wHour;
  29762. y.tm_min = pTm.wMinute;
  29763. y.tm_sec = pTm.wSecond;
  29764. return &y;
  29765. }
  29766. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  29767. /*
  29768. ** Acquire a lock on the handle h
  29769. */
  29770. static void winceMutexAcquire(HANDLE h){
  29771. DWORD dwErr;
  29772. do {
  29773. dwErr = osWaitForSingleObject(h, INFINITE);
  29774. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  29775. }
  29776. /*
  29777. ** Release a lock acquired by winceMutexAcquire()
  29778. */
  29779. #define winceMutexRelease(h) ReleaseMutex(h)
  29780. /*
  29781. ** Create the mutex and shared memory used for locking in the file
  29782. ** descriptor pFile
  29783. */
  29784. static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  29785. LPWSTR zTok;
  29786. LPWSTR zName;
  29787. BOOL bInit = TRUE;
  29788. zName = utf8ToUnicode(zFilename);
  29789. if( zName==0 ){
  29790. /* out of memory */
  29791. return FALSE;
  29792. }
  29793. /* Initialize the local lockdata */
  29794. memset(&pFile->local, 0, sizeof(pFile->local));
  29795. /* Replace the backslashes from the filename and lowercase it
  29796. ** to derive a mutex name. */
  29797. zTok = osCharLowerW(zName);
  29798. for (;*zTok;zTok++){
  29799. if (*zTok == '\\') *zTok = '_';
  29800. }
  29801. /* Create/open the named mutex */
  29802. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  29803. if (!pFile->hMutex){
  29804. pFile->lastErrno = osGetLastError();
  29805. winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
  29806. sqlite3_free(zName);
  29807. return FALSE;
  29808. }
  29809. /* Acquire the mutex before continuing */
  29810. winceMutexAcquire(pFile->hMutex);
  29811. /* Since the names of named mutexes, semaphores, file mappings etc are
  29812. ** case-sensitive, take advantage of that by uppercasing the mutex name
  29813. ** and using that as the shared filemapping name.
  29814. */
  29815. osCharUpperW(zName);
  29816. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  29817. PAGE_READWRITE, 0, sizeof(winceLock),
  29818. zName);
  29819. /* Set a flag that indicates we're the first to create the memory so it
  29820. ** must be zero-initialized */
  29821. if (osGetLastError() == ERROR_ALREADY_EXISTS){
  29822. bInit = FALSE;
  29823. }
  29824. sqlite3_free(zName);
  29825. /* If we succeeded in making the shared memory handle, map it. */
  29826. if (pFile->hShared){
  29827. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  29828. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  29829. /* If mapping failed, close the shared memory handle and erase it */
  29830. if (!pFile->shared){
  29831. pFile->lastErrno = osGetLastError();
  29832. winLogError(SQLITE_ERROR, pFile->lastErrno,
  29833. "winceCreateLock2", zFilename);
  29834. osCloseHandle(pFile->hShared);
  29835. pFile->hShared = NULL;
  29836. }
  29837. }
  29838. /* If shared memory could not be created, then close the mutex and fail */
  29839. if (pFile->hShared == NULL){
  29840. winceMutexRelease(pFile->hMutex);
  29841. osCloseHandle(pFile->hMutex);
  29842. pFile->hMutex = NULL;
  29843. return FALSE;
  29844. }
  29845. /* Initialize the shared memory if we're supposed to */
  29846. if (bInit) {
  29847. memset(pFile->shared, 0, sizeof(winceLock));
  29848. }
  29849. winceMutexRelease(pFile->hMutex);
  29850. return TRUE;
  29851. }
  29852. /*
  29853. ** Destroy the part of winFile that deals with wince locks
  29854. */
  29855. static void winceDestroyLock(winFile *pFile){
  29856. if (pFile->hMutex){
  29857. /* Acquire the mutex */
  29858. winceMutexAcquire(pFile->hMutex);
  29859. /* The following blocks should probably assert in debug mode, but they
  29860. are to cleanup in case any locks remained open */
  29861. if (pFile->local.nReaders){
  29862. pFile->shared->nReaders --;
  29863. }
  29864. if (pFile->local.bReserved){
  29865. pFile->shared->bReserved = FALSE;
  29866. }
  29867. if (pFile->local.bPending){
  29868. pFile->shared->bPending = FALSE;
  29869. }
  29870. if (pFile->local.bExclusive){
  29871. pFile->shared->bExclusive = FALSE;
  29872. }
  29873. /* De-reference and close our copy of the shared memory handle */
  29874. osUnmapViewOfFile(pFile->shared);
  29875. osCloseHandle(pFile->hShared);
  29876. /* Done with the mutex */
  29877. winceMutexRelease(pFile->hMutex);
  29878. osCloseHandle(pFile->hMutex);
  29879. pFile->hMutex = NULL;
  29880. }
  29881. }
  29882. /*
  29883. ** An implementation of the LockFile() API of Windows for CE
  29884. */
  29885. static BOOL winceLockFile(
  29886. LPHANDLE phFile,
  29887. DWORD dwFileOffsetLow,
  29888. DWORD dwFileOffsetHigh,
  29889. DWORD nNumberOfBytesToLockLow,
  29890. DWORD nNumberOfBytesToLockHigh
  29891. ){
  29892. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  29893. BOOL bReturn = FALSE;
  29894. UNUSED_PARAMETER(dwFileOffsetHigh);
  29895. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  29896. if (!pFile->hMutex) return TRUE;
  29897. winceMutexAcquire(pFile->hMutex);
  29898. /* Wanting an exclusive lock? */
  29899. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  29900. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  29901. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  29902. pFile->shared->bExclusive = TRUE;
  29903. pFile->local.bExclusive = TRUE;
  29904. bReturn = TRUE;
  29905. }
  29906. }
  29907. /* Want a read-only lock? */
  29908. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  29909. nNumberOfBytesToLockLow == 1){
  29910. if (pFile->shared->bExclusive == 0){
  29911. pFile->local.nReaders ++;
  29912. if (pFile->local.nReaders == 1){
  29913. pFile->shared->nReaders ++;
  29914. }
  29915. bReturn = TRUE;
  29916. }
  29917. }
  29918. /* Want a pending lock? */
  29919. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
  29920. /* If no pending lock has been acquired, then acquire it */
  29921. if (pFile->shared->bPending == 0) {
  29922. pFile->shared->bPending = TRUE;
  29923. pFile->local.bPending = TRUE;
  29924. bReturn = TRUE;
  29925. }
  29926. }
  29927. /* Want a reserved lock? */
  29928. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
  29929. if (pFile->shared->bReserved == 0) {
  29930. pFile->shared->bReserved = TRUE;
  29931. pFile->local.bReserved = TRUE;
  29932. bReturn = TRUE;
  29933. }
  29934. }
  29935. winceMutexRelease(pFile->hMutex);
  29936. return bReturn;
  29937. }
  29938. /*
  29939. ** An implementation of the UnlockFile API of Windows for CE
  29940. */
  29941. static BOOL winceUnlockFile(
  29942. LPHANDLE phFile,
  29943. DWORD dwFileOffsetLow,
  29944. DWORD dwFileOffsetHigh,
  29945. DWORD nNumberOfBytesToUnlockLow,
  29946. DWORD nNumberOfBytesToUnlockHigh
  29947. ){
  29948. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  29949. BOOL bReturn = FALSE;
  29950. UNUSED_PARAMETER(dwFileOffsetHigh);
  29951. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  29952. if (!pFile->hMutex) return TRUE;
  29953. winceMutexAcquire(pFile->hMutex);
  29954. /* Releasing a reader lock or an exclusive lock */
  29955. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  29956. /* Did we have an exclusive lock? */
  29957. if (pFile->local.bExclusive){
  29958. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  29959. pFile->local.bExclusive = FALSE;
  29960. pFile->shared->bExclusive = FALSE;
  29961. bReturn = TRUE;
  29962. }
  29963. /* Did we just have a reader lock? */
  29964. else if (pFile->local.nReaders){
  29965. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
  29966. pFile->local.nReaders --;
  29967. if (pFile->local.nReaders == 0)
  29968. {
  29969. pFile->shared->nReaders --;
  29970. }
  29971. bReturn = TRUE;
  29972. }
  29973. }
  29974. /* Releasing a pending lock */
  29975. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
  29976. if (pFile->local.bPending){
  29977. pFile->local.bPending = FALSE;
  29978. pFile->shared->bPending = FALSE;
  29979. bReturn = TRUE;
  29980. }
  29981. }
  29982. /* Releasing a reserved lock */
  29983. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
  29984. if (pFile->local.bReserved) {
  29985. pFile->local.bReserved = FALSE;
  29986. pFile->shared->bReserved = FALSE;
  29987. bReturn = TRUE;
  29988. }
  29989. }
  29990. winceMutexRelease(pFile->hMutex);
  29991. return bReturn;
  29992. }
  29993. /*
  29994. ** End of the special code for wince
  29995. *****************************************************************************/
  29996. #endif /* SQLITE_OS_WINCE */
  29997. /*
  29998. ** Lock a file region.
  29999. */
  30000. static BOOL winLockFile(
  30001. LPHANDLE phFile,
  30002. DWORD flags,
  30003. DWORD offsetLow,
  30004. DWORD offsetHigh,
  30005. DWORD numBytesLow,
  30006. DWORD numBytesHigh
  30007. ){
  30008. #if SQLITE_OS_WINCE
  30009. /*
  30010. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30011. ** API LockFile.
  30012. */
  30013. return winceLockFile(phFile, offsetLow, offsetHigh,
  30014. numBytesLow, numBytesHigh);
  30015. #else
  30016. if( isNT() ){
  30017. OVERLAPPED ovlp;
  30018. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30019. ovlp.Offset = offsetLow;
  30020. ovlp.OffsetHigh = offsetHigh;
  30021. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  30022. }else{
  30023. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30024. numBytesHigh);
  30025. }
  30026. #endif
  30027. }
  30028. /*
  30029. ** Unlock a file region.
  30030. */
  30031. static BOOL winUnlockFile(
  30032. LPHANDLE phFile,
  30033. DWORD offsetLow,
  30034. DWORD offsetHigh,
  30035. DWORD numBytesLow,
  30036. DWORD numBytesHigh
  30037. ){
  30038. #if SQLITE_OS_WINCE
  30039. /*
  30040. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30041. ** API UnlockFile.
  30042. */
  30043. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  30044. numBytesLow, numBytesHigh);
  30045. #else
  30046. if( isNT() ){
  30047. OVERLAPPED ovlp;
  30048. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30049. ovlp.Offset = offsetLow;
  30050. ovlp.OffsetHigh = offsetHigh;
  30051. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  30052. }else{
  30053. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  30054. numBytesHigh);
  30055. }
  30056. #endif
  30057. }
  30058. /*****************************************************************************
  30059. ** The next group of routines implement the I/O methods specified
  30060. ** by the sqlite3_io_methods object.
  30061. ******************************************************************************/
  30062. /*
  30063. ** Some Microsoft compilers lack this definition.
  30064. */
  30065. #ifndef INVALID_SET_FILE_POINTER
  30066. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  30067. #endif
  30068. /*
  30069. ** Move the current position of the file handle passed as the first
  30070. ** argument to offset iOffset within the file. If successful, return 0.
  30071. ** Otherwise, set pFile->lastErrno and return non-zero.
  30072. */
  30073. static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
  30074. #if !SQLITE_OS_WINRT
  30075. LONG upperBits; /* Most sig. 32 bits of new offset */
  30076. LONG lowerBits; /* Least sig. 32 bits of new offset */
  30077. DWORD dwRet; /* Value returned by SetFilePointer() */
  30078. DWORD lastErrno; /* Value returned by GetLastError() */
  30079. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  30080. lowerBits = (LONG)(iOffset & 0xffffffff);
  30081. /* API oddity: If successful, SetFilePointer() returns a dword
  30082. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  30083. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  30084. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  30085. ** whether an error has actually occured, it is also necessary to call
  30086. ** GetLastError().
  30087. */
  30088. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  30089. if( (dwRet==INVALID_SET_FILE_POINTER
  30090. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  30091. pFile->lastErrno = lastErrno;
  30092. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30093. "seekWinFile", pFile->zPath);
  30094. return 1;
  30095. }
  30096. return 0;
  30097. #else
  30098. /*
  30099. ** Same as above, except that this implementation works for WinRT.
  30100. */
  30101. LARGE_INTEGER x; /* The new offset */
  30102. BOOL bRet; /* Value returned by SetFilePointerEx() */
  30103. x.QuadPart = iOffset;
  30104. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  30105. if(!bRet){
  30106. pFile->lastErrno = osGetLastError();
  30107. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  30108. "seekWinFile", pFile->zPath);
  30109. return 1;
  30110. }
  30111. return 0;
  30112. #endif
  30113. }
  30114. /*
  30115. ** Close a file.
  30116. **
  30117. ** It is reported that an attempt to close a handle might sometimes
  30118. ** fail. This is a very unreasonable result, but Windows is notorious
  30119. ** for being unreasonable so I do not doubt that it might happen. If
  30120. ** the close fails, we pause for 100 milliseconds and try again. As
  30121. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  30122. ** giving up and returning an error.
  30123. */
  30124. #define MX_CLOSE_ATTEMPT 3
  30125. static int winClose(sqlite3_file *id){
  30126. int rc, cnt = 0;
  30127. winFile *pFile = (winFile*)id;
  30128. assert( id!=0 );
  30129. #ifndef SQLITE_OMIT_WAL
  30130. assert( pFile->pShm==0 );
  30131. #endif
  30132. OSTRACE(("CLOSE %d\n", pFile->h));
  30133. do{
  30134. rc = osCloseHandle(pFile->h);
  30135. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  30136. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  30137. #if SQLITE_OS_WINCE
  30138. #define WINCE_DELETION_ATTEMPTS 3
  30139. winceDestroyLock(pFile);
  30140. if( pFile->zDeleteOnClose ){
  30141. int cnt = 0;
  30142. while(
  30143. osDeleteFileW(pFile->zDeleteOnClose)==0
  30144. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  30145. && cnt++ < WINCE_DELETION_ATTEMPTS
  30146. ){
  30147. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  30148. }
  30149. sqlite3_free(pFile->zDeleteOnClose);
  30150. }
  30151. #endif
  30152. OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
  30153. if( rc ){
  30154. pFile->h = NULL;
  30155. }
  30156. OpenCounter(-1);
  30157. return rc ? SQLITE_OK
  30158. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  30159. "winClose", pFile->zPath);
  30160. }
  30161. /*
  30162. ** Read data from a file into a buffer. Return SQLITE_OK if all
  30163. ** bytes were read successfully and SQLITE_IOERR if anything goes
  30164. ** wrong.
  30165. */
  30166. static int winRead(
  30167. sqlite3_file *id, /* File to read from */
  30168. void *pBuf, /* Write content into this buffer */
  30169. int amt, /* Number of bytes to read */
  30170. sqlite3_int64 offset /* Begin reading at this offset */
  30171. ){
  30172. #if !SQLITE_OS_WINCE
  30173. OVERLAPPED overlapped; /* The offset for ReadFile. */
  30174. #endif
  30175. winFile *pFile = (winFile*)id; /* file handle */
  30176. DWORD nRead; /* Number of bytes actually read from file */
  30177. int nRetry = 0; /* Number of retrys */
  30178. assert( id!=0 );
  30179. SimulateIOError(return SQLITE_IOERR_READ);
  30180. OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
  30181. #if SQLITE_OS_WINCE
  30182. if( seekWinFile(pFile, offset) ){
  30183. return SQLITE_FULL;
  30184. }
  30185. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  30186. #else
  30187. memset(&overlapped, 0, sizeof(OVERLAPPED));
  30188. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30189. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30190. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  30191. osGetLastError()!=ERROR_HANDLE_EOF ){
  30192. #endif
  30193. DWORD lastErrno;
  30194. if( retryIoerr(&nRetry, &lastErrno) ) continue;
  30195. pFile->lastErrno = lastErrno;
  30196. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  30197. "winRead", pFile->zPath);
  30198. }
  30199. logIoerr(nRetry);
  30200. if( nRead<(DWORD)amt ){
  30201. /* Unread parts of the buffer must be zero-filled */
  30202. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  30203. return SQLITE_IOERR_SHORT_READ;
  30204. }
  30205. return SQLITE_OK;
  30206. }
  30207. /*
  30208. ** Write data from a buffer into a file. Return SQLITE_OK on success
  30209. ** or some other error code on failure.
  30210. */
  30211. static int winWrite(
  30212. sqlite3_file *id, /* File to write into */
  30213. const void *pBuf, /* The bytes to be written */
  30214. int amt, /* Number of bytes to write */
  30215. sqlite3_int64 offset /* Offset into the file to begin writing at */
  30216. ){
  30217. int rc = 0; /* True if error has occured, else false */
  30218. winFile *pFile = (winFile*)id; /* File handle */
  30219. int nRetry = 0; /* Number of retries */
  30220. assert( amt>0 );
  30221. assert( pFile );
  30222. SimulateIOError(return SQLITE_IOERR_WRITE);
  30223. SimulateDiskfullError(return SQLITE_FULL);
  30224. OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
  30225. #if SQLITE_OS_WINCE
  30226. rc = seekWinFile(pFile, offset);
  30227. if( rc==0 ){
  30228. #else
  30229. {
  30230. #endif
  30231. #if !SQLITE_OS_WINCE
  30232. OVERLAPPED overlapped; /* The offset for WriteFile. */
  30233. #endif
  30234. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  30235. int nRem = amt; /* Number of bytes yet to be written */
  30236. DWORD nWrite; /* Bytes written by each WriteFile() call */
  30237. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  30238. #if !SQLITE_OS_WINCE
  30239. memset(&overlapped, 0, sizeof(OVERLAPPED));
  30240. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30241. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30242. #endif
  30243. while( nRem>0 ){
  30244. #if SQLITE_OS_WINCE
  30245. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  30246. #else
  30247. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  30248. #endif
  30249. if( retryIoerr(&nRetry, &lastErrno) ) continue;
  30250. break;
  30251. }
  30252. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  30253. if( nWrite==0 || nWrite>(DWORD)nRem ){
  30254. lastErrno = osGetLastError();
  30255. break;
  30256. }
  30257. #if !SQLITE_OS_WINCE
  30258. offset += nWrite;
  30259. overlapped.Offset = (LONG)(offset & 0xffffffff);
  30260. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  30261. #endif
  30262. aRem += nWrite;
  30263. nRem -= nWrite;
  30264. }
  30265. if( nRem>0 ){
  30266. pFile->lastErrno = lastErrno;
  30267. rc = 1;
  30268. }
  30269. }
  30270. if( rc ){
  30271. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  30272. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  30273. return SQLITE_FULL;
  30274. }
  30275. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  30276. "winWrite", pFile->zPath);
  30277. }else{
  30278. logIoerr(nRetry);
  30279. }
  30280. return SQLITE_OK;
  30281. }
  30282. /*
  30283. ** Truncate an open file to a specified size
  30284. */
  30285. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  30286. winFile *pFile = (winFile*)id; /* File handle object */
  30287. int rc = SQLITE_OK; /* Return code for this function */
  30288. assert( pFile );
  30289. OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
  30290. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  30291. /* If the user has configured a chunk-size for this file, truncate the
  30292. ** file so that it consists of an integer number of chunks (i.e. the
  30293. ** actual file size after the operation may be larger than the requested
  30294. ** size).
  30295. */
  30296. if( pFile->szChunk>0 ){
  30297. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  30298. }
  30299. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  30300. if( seekWinFile(pFile, nByte) ){
  30301. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  30302. "winTruncate1", pFile->zPath);
  30303. }else if( 0==osSetEndOfFile(pFile->h) ){
  30304. pFile->lastErrno = osGetLastError();
  30305. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  30306. "winTruncate2", pFile->zPath);
  30307. }
  30308. OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
  30309. return rc;
  30310. }
  30311. #ifdef SQLITE_TEST
  30312. /*
  30313. ** Count the number of fullsyncs and normal syncs. This is used to test
  30314. ** that syncs and fullsyncs are occuring at the right times.
  30315. */
  30316. SQLITE_API int sqlite3_sync_count = 0;
  30317. SQLITE_API int sqlite3_fullsync_count = 0;
  30318. #endif
  30319. /*
  30320. ** Make sure all writes to a particular file are committed to disk.
  30321. */
  30322. static int winSync(sqlite3_file *id, int flags){
  30323. #ifndef SQLITE_NO_SYNC
  30324. /*
  30325. ** Used only when SQLITE_NO_SYNC is not defined.
  30326. */
  30327. BOOL rc;
  30328. #endif
  30329. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  30330. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  30331. /*
  30332. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  30333. ** OSTRACE() macros.
  30334. */
  30335. winFile *pFile = (winFile*)id;
  30336. #else
  30337. UNUSED_PARAMETER(id);
  30338. #endif
  30339. assert( pFile );
  30340. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  30341. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  30342. || (flags&0x0F)==SQLITE_SYNC_FULL
  30343. );
  30344. OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
  30345. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  30346. ** line is to test that doing so does not cause any problems.
  30347. */
  30348. SimulateDiskfullError( return SQLITE_FULL );
  30349. #ifndef SQLITE_TEST
  30350. UNUSED_PARAMETER(flags);
  30351. #else
  30352. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  30353. sqlite3_fullsync_count++;
  30354. }
  30355. sqlite3_sync_count++;
  30356. #endif
  30357. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  30358. ** no-op
  30359. */
  30360. #ifdef SQLITE_NO_SYNC
  30361. return SQLITE_OK;
  30362. #else
  30363. rc = osFlushFileBuffers(pFile->h);
  30364. SimulateIOError( rc=FALSE );
  30365. if( rc ){
  30366. return SQLITE_OK;
  30367. }else{
  30368. pFile->lastErrno = osGetLastError();
  30369. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  30370. "winSync", pFile->zPath);
  30371. }
  30372. #endif
  30373. }
  30374. /*
  30375. ** Determine the current size of a file in bytes
  30376. */
  30377. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  30378. winFile *pFile = (winFile*)id;
  30379. int rc = SQLITE_OK;
  30380. assert( id!=0 );
  30381. SimulateIOError(return SQLITE_IOERR_FSTAT);
  30382. #if SQLITE_OS_WINRT
  30383. {
  30384. FILE_STANDARD_INFO info;
  30385. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  30386. &info, sizeof(info)) ){
  30387. *pSize = info.EndOfFile.QuadPart;
  30388. }else{
  30389. pFile->lastErrno = osGetLastError();
  30390. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  30391. "winFileSize", pFile->zPath);
  30392. }
  30393. }
  30394. #else
  30395. {
  30396. DWORD upperBits;
  30397. DWORD lowerBits;
  30398. DWORD lastErrno;
  30399. lowerBits = osGetFileSize(pFile->h, &upperBits);
  30400. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  30401. if( (lowerBits == INVALID_FILE_SIZE)
  30402. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  30403. pFile->lastErrno = lastErrno;
  30404. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  30405. "winFileSize", pFile->zPath);
  30406. }
  30407. }
  30408. #endif
  30409. return rc;
  30410. }
  30411. /*
  30412. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  30413. */
  30414. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  30415. # define LOCKFILE_FAIL_IMMEDIATELY 1
  30416. #endif
  30417. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  30418. # define LOCKFILE_EXCLUSIVE_LOCK 2
  30419. #endif
  30420. /*
  30421. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  30422. ** When the LockFile function was used, it was always expected to fail
  30423. ** immediately if the lock could not be obtained. Also, it always expected to
  30424. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  30425. ** and reflect those expectations; therefore, they should not be changed.
  30426. */
  30427. #ifndef SQLITE_LOCKFILE_FLAGS
  30428. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  30429. LOCKFILE_EXCLUSIVE_LOCK)
  30430. #endif
  30431. /*
  30432. ** Currently, SQLite never calls the LockFileEx function without wanting the
  30433. ** call to fail immediately if the lock cannot be obtained.
  30434. */
  30435. #ifndef SQLITE_LOCKFILEEX_FLAGS
  30436. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  30437. #endif
  30438. /*
  30439. ** Acquire a reader lock.
  30440. ** Different API routines are called depending on whether or not this
  30441. ** is Win9x or WinNT.
  30442. */
  30443. static int getReadLock(winFile *pFile){
  30444. int res;
  30445. if( isNT() ){
  30446. #if SQLITE_OS_WINCE
  30447. /*
  30448. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  30449. ** API LockFileEx.
  30450. */
  30451. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  30452. #else
  30453. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  30454. SHARED_SIZE, 0);
  30455. #endif
  30456. }
  30457. #ifdef SQLITE_WIN32_HAS_ANSI
  30458. else{
  30459. int lk;
  30460. sqlite3_randomness(sizeof(lk), &lk);
  30461. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  30462. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  30463. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  30464. }
  30465. #endif
  30466. if( res == 0 ){
  30467. pFile->lastErrno = osGetLastError();
  30468. /* No need to log a failure to lock */
  30469. }
  30470. return res;
  30471. }
  30472. /*
  30473. ** Undo a readlock
  30474. */
  30475. static int unlockReadLock(winFile *pFile){
  30476. int res;
  30477. DWORD lastErrno;
  30478. if( isNT() ){
  30479. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  30480. }
  30481. #ifdef SQLITE_WIN32_HAS_ANSI
  30482. else{
  30483. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  30484. }
  30485. #endif
  30486. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  30487. pFile->lastErrno = lastErrno;
  30488. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  30489. "unlockReadLock", pFile->zPath);
  30490. }
  30491. return res;
  30492. }
  30493. /*
  30494. ** Lock the file with the lock specified by parameter locktype - one
  30495. ** of the following:
  30496. **
  30497. ** (1) SHARED_LOCK
  30498. ** (2) RESERVED_LOCK
  30499. ** (3) PENDING_LOCK
  30500. ** (4) EXCLUSIVE_LOCK
  30501. **
  30502. ** Sometimes when requesting one lock state, additional lock states
  30503. ** are inserted in between. The locking might fail on one of the later
  30504. ** transitions leaving the lock state different from what it started but
  30505. ** still short of its goal. The following chart shows the allowed
  30506. ** transitions and the inserted intermediate states:
  30507. **
  30508. ** UNLOCKED -> SHARED
  30509. ** SHARED -> RESERVED
  30510. ** SHARED -> (PENDING) -> EXCLUSIVE
  30511. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30512. ** PENDING -> EXCLUSIVE
  30513. **
  30514. ** This routine will only increase a lock. The winUnlock() routine
  30515. ** erases all locks at once and returns us immediately to locking level 0.
  30516. ** It is not possible to lower the locking level one step at a time. You
  30517. ** must go straight to locking level 0.
  30518. */
  30519. static int winLock(sqlite3_file *id, int locktype){
  30520. int rc = SQLITE_OK; /* Return code from subroutines */
  30521. int res = 1; /* Result of a Windows lock call */
  30522. int newLocktype; /* Set pFile->locktype to this value before exiting */
  30523. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  30524. winFile *pFile = (winFile*)id;
  30525. DWORD lastErrno = NO_ERROR;
  30526. assert( id!=0 );
  30527. OSTRACE(("LOCK %d %d was %d(%d)\n",
  30528. pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
  30529. /* If there is already a lock of this type or more restrictive on the
  30530. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  30531. ** sqlite3OsEnterMutex() hasn't been called yet.
  30532. */
  30533. if( pFile->locktype>=locktype ){
  30534. return SQLITE_OK;
  30535. }
  30536. /* Make sure the locking sequence is correct
  30537. */
  30538. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  30539. assert( locktype!=PENDING_LOCK );
  30540. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  30541. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  30542. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  30543. ** the PENDING_LOCK byte is temporary.
  30544. */
  30545. newLocktype = pFile->locktype;
  30546. if( (pFile->locktype==NO_LOCK)
  30547. || ( (locktype==EXCLUSIVE_LOCK)
  30548. && (pFile->locktype==RESERVED_LOCK))
  30549. ){
  30550. int cnt = 3;
  30551. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  30552. PENDING_BYTE, 0, 1, 0))==0 ){
  30553. /* Try 3 times to get the pending lock. This is needed to work
  30554. ** around problems caused by indexing and/or anti-virus software on
  30555. ** Windows systems.
  30556. ** If you are using this code as a model for alternative VFSes, do not
  30557. ** copy this retry logic. It is a hack intended for Windows only.
  30558. */
  30559. OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
  30560. if( cnt ) sqlite3_win32_sleep(1);
  30561. }
  30562. gotPendingLock = res;
  30563. if( !res ){
  30564. lastErrno = osGetLastError();
  30565. }
  30566. }
  30567. /* Acquire a shared lock
  30568. */
  30569. if( locktype==SHARED_LOCK && res ){
  30570. assert( pFile->locktype==NO_LOCK );
  30571. res = getReadLock(pFile);
  30572. if( res ){
  30573. newLocktype = SHARED_LOCK;
  30574. }else{
  30575. lastErrno = osGetLastError();
  30576. }
  30577. }
  30578. /* Acquire a RESERVED lock
  30579. */
  30580. if( locktype==RESERVED_LOCK && res ){
  30581. assert( pFile->locktype==SHARED_LOCK );
  30582. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  30583. if( res ){
  30584. newLocktype = RESERVED_LOCK;
  30585. }else{
  30586. lastErrno = osGetLastError();
  30587. }
  30588. }
  30589. /* Acquire a PENDING lock
  30590. */
  30591. if( locktype==EXCLUSIVE_LOCK && res ){
  30592. newLocktype = PENDING_LOCK;
  30593. gotPendingLock = 0;
  30594. }
  30595. /* Acquire an EXCLUSIVE lock
  30596. */
  30597. if( locktype==EXCLUSIVE_LOCK && res ){
  30598. assert( pFile->locktype>=SHARED_LOCK );
  30599. res = unlockReadLock(pFile);
  30600. OSTRACE(("unreadlock = %d\n", res));
  30601. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  30602. SHARED_SIZE, 0);
  30603. if( res ){
  30604. newLocktype = EXCLUSIVE_LOCK;
  30605. }else{
  30606. lastErrno = osGetLastError();
  30607. OSTRACE(("error-code = %d\n", lastErrno));
  30608. getReadLock(pFile);
  30609. }
  30610. }
  30611. /* If we are holding a PENDING lock that ought to be released, then
  30612. ** release it now.
  30613. */
  30614. if( gotPendingLock && locktype==SHARED_LOCK ){
  30615. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  30616. }
  30617. /* Update the state of the lock has held in the file descriptor then
  30618. ** return the appropriate result code.
  30619. */
  30620. if( res ){
  30621. rc = SQLITE_OK;
  30622. }else{
  30623. OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  30624. locktype, newLocktype));
  30625. pFile->lastErrno = lastErrno;
  30626. rc = SQLITE_BUSY;
  30627. }
  30628. pFile->locktype = (u8)newLocktype;
  30629. return rc;
  30630. }
  30631. /*
  30632. ** This routine checks if there is a RESERVED lock held on the specified
  30633. ** file by this or any other process. If such a lock is held, return
  30634. ** non-zero, otherwise zero.
  30635. */
  30636. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  30637. int rc;
  30638. winFile *pFile = (winFile*)id;
  30639. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30640. assert( id!=0 );
  30641. if( pFile->locktype>=RESERVED_LOCK ){
  30642. rc = 1;
  30643. OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
  30644. }else{
  30645. rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  30646. if( rc ){
  30647. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  30648. }
  30649. rc = !rc;
  30650. OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
  30651. }
  30652. *pResOut = rc;
  30653. return SQLITE_OK;
  30654. }
  30655. /*
  30656. ** Lower the locking level on file descriptor id to locktype. locktype
  30657. ** must be either NO_LOCK or SHARED_LOCK.
  30658. **
  30659. ** If the locking level of the file descriptor is already at or below
  30660. ** the requested locking level, this routine is a no-op.
  30661. **
  30662. ** It is not possible for this routine to fail if the second argument
  30663. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  30664. ** might return SQLITE_IOERR;
  30665. */
  30666. static int winUnlock(sqlite3_file *id, int locktype){
  30667. int type;
  30668. winFile *pFile = (winFile*)id;
  30669. int rc = SQLITE_OK;
  30670. assert( pFile!=0 );
  30671. assert( locktype<=SHARED_LOCK );
  30672. OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  30673. pFile->locktype, pFile->sharedLockByte));
  30674. type = pFile->locktype;
  30675. if( type>=EXCLUSIVE_LOCK ){
  30676. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  30677. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  30678. /* This should never happen. We should always be able to
  30679. ** reacquire the read lock */
  30680. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  30681. "winUnlock", pFile->zPath);
  30682. }
  30683. }
  30684. if( type>=RESERVED_LOCK ){
  30685. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  30686. }
  30687. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  30688. unlockReadLock(pFile);
  30689. }
  30690. if( type>=PENDING_LOCK ){
  30691. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  30692. }
  30693. pFile->locktype = (u8)locktype;
  30694. return rc;
  30695. }
  30696. /*
  30697. ** If *pArg is inititially negative then this is a query. Set *pArg to
  30698. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  30699. **
  30700. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  30701. */
  30702. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  30703. if( *pArg<0 ){
  30704. *pArg = (pFile->ctrlFlags & mask)!=0;
  30705. }else if( (*pArg)==0 ){
  30706. pFile->ctrlFlags &= ~mask;
  30707. }else{
  30708. pFile->ctrlFlags |= mask;
  30709. }
  30710. }
  30711. /* Forward declaration */
  30712. static int getTempname(int nBuf, char *zBuf);
  30713. /*
  30714. ** Control and query of the open file handle.
  30715. */
  30716. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  30717. winFile *pFile = (winFile*)id;
  30718. switch( op ){
  30719. case SQLITE_FCNTL_LOCKSTATE: {
  30720. *(int*)pArg = pFile->locktype;
  30721. return SQLITE_OK;
  30722. }
  30723. case SQLITE_LAST_ERRNO: {
  30724. *(int*)pArg = (int)pFile->lastErrno;
  30725. return SQLITE_OK;
  30726. }
  30727. case SQLITE_FCNTL_CHUNK_SIZE: {
  30728. pFile->szChunk = *(int *)pArg;
  30729. return SQLITE_OK;
  30730. }
  30731. case SQLITE_FCNTL_SIZE_HINT: {
  30732. if( pFile->szChunk>0 ){
  30733. sqlite3_int64 oldSz;
  30734. int rc = winFileSize(id, &oldSz);
  30735. if( rc==SQLITE_OK ){
  30736. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  30737. if( newSz>oldSz ){
  30738. SimulateIOErrorBenign(1);
  30739. rc = winTruncate(id, newSz);
  30740. SimulateIOErrorBenign(0);
  30741. }
  30742. }
  30743. return rc;
  30744. }
  30745. return SQLITE_OK;
  30746. }
  30747. case SQLITE_FCNTL_PERSIST_WAL: {
  30748. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  30749. return SQLITE_OK;
  30750. }
  30751. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  30752. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  30753. return SQLITE_OK;
  30754. }
  30755. case SQLITE_FCNTL_VFSNAME: {
  30756. *(char**)pArg = sqlite3_mprintf("win32");
  30757. return SQLITE_OK;
  30758. }
  30759. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  30760. int *a = (int*)pArg;
  30761. if( a[0]>0 ){
  30762. win32IoerrRetry = a[0];
  30763. }else{
  30764. a[0] = win32IoerrRetry;
  30765. }
  30766. if( a[1]>0 ){
  30767. win32IoerrRetryDelay = a[1];
  30768. }else{
  30769. a[1] = win32IoerrRetryDelay;
  30770. }
  30771. return SQLITE_OK;
  30772. }
  30773. case SQLITE_FCNTL_TEMPFILENAME: {
  30774. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  30775. if( zTFile ){
  30776. getTempname(pFile->pVfs->mxPathname, zTFile);
  30777. *(char**)pArg = zTFile;
  30778. }
  30779. return SQLITE_OK;
  30780. }
  30781. }
  30782. return SQLITE_NOTFOUND;
  30783. }
  30784. /*
  30785. ** Return the sector size in bytes of the underlying block device for
  30786. ** the specified file. This is almost always 512 bytes, but may be
  30787. ** larger for some devices.
  30788. **
  30789. ** SQLite code assumes this function cannot fail. It also assumes that
  30790. ** if two files are created in the same file-system directory (i.e.
  30791. ** a database and its journal file) that the sector size will be the
  30792. ** same for both.
  30793. */
  30794. static int winSectorSize(sqlite3_file *id){
  30795. (void)id;
  30796. return SQLITE_DEFAULT_SECTOR_SIZE;
  30797. }
  30798. /*
  30799. ** Return a vector of device characteristics.
  30800. */
  30801. static int winDeviceCharacteristics(sqlite3_file *id){
  30802. winFile *p = (winFile*)id;
  30803. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  30804. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  30805. }
  30806. #ifndef SQLITE_OMIT_WAL
  30807. /*
  30808. ** Windows will only let you create file view mappings
  30809. ** on allocation size granularity boundaries.
  30810. ** During sqlite3_os_init() we do a GetSystemInfo()
  30811. ** to get the granularity size.
  30812. */
  30813. SYSTEM_INFO winSysInfo;
  30814. /*
  30815. ** Helper functions to obtain and relinquish the global mutex. The
  30816. ** global mutex is used to protect the winLockInfo objects used by
  30817. ** this file, all of which may be shared by multiple threads.
  30818. **
  30819. ** Function winShmMutexHeld() is used to assert() that the global mutex
  30820. ** is held when required. This function is only used as part of assert()
  30821. ** statements. e.g.
  30822. **
  30823. ** winShmEnterMutex()
  30824. ** assert( winShmMutexHeld() );
  30825. ** winShmLeaveMutex()
  30826. */
  30827. static void winShmEnterMutex(void){
  30828. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30829. }
  30830. static void winShmLeaveMutex(void){
  30831. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30832. }
  30833. #ifdef SQLITE_DEBUG
  30834. static int winShmMutexHeld(void) {
  30835. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30836. }
  30837. #endif
  30838. /*
  30839. ** Object used to represent a single file opened and mmapped to provide
  30840. ** shared memory. When multiple threads all reference the same
  30841. ** log-summary, each thread has its own winFile object, but they all
  30842. ** point to a single instance of this object. In other words, each
  30843. ** log-summary is opened only once per process.
  30844. **
  30845. ** winShmMutexHeld() must be true when creating or destroying
  30846. ** this object or while reading or writing the following fields:
  30847. **
  30848. ** nRef
  30849. ** pNext
  30850. **
  30851. ** The following fields are read-only after the object is created:
  30852. **
  30853. ** fid
  30854. ** zFilename
  30855. **
  30856. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  30857. ** winShmMutexHeld() is true when reading or writing any other field
  30858. ** in this structure.
  30859. **
  30860. */
  30861. struct winShmNode {
  30862. sqlite3_mutex *mutex; /* Mutex to access this object */
  30863. char *zFilename; /* Name of the file */
  30864. winFile hFile; /* File handle from winOpen */
  30865. int szRegion; /* Size of shared-memory regions */
  30866. int nRegion; /* Size of array apRegion */
  30867. struct ShmRegion {
  30868. HANDLE hMap; /* File handle from CreateFileMapping */
  30869. void *pMap;
  30870. } *aRegion;
  30871. DWORD lastErrno; /* The Windows errno from the last I/O error */
  30872. int nRef; /* Number of winShm objects pointing to this */
  30873. winShm *pFirst; /* All winShm objects pointing to this */
  30874. winShmNode *pNext; /* Next in list of all winShmNode objects */
  30875. #ifdef SQLITE_DEBUG
  30876. u8 nextShmId; /* Next available winShm.id value */
  30877. #endif
  30878. };
  30879. /*
  30880. ** A global array of all winShmNode objects.
  30881. **
  30882. ** The winShmMutexHeld() must be true while reading or writing this list.
  30883. */
  30884. static winShmNode *winShmNodeList = 0;
  30885. /*
  30886. ** Structure used internally by this VFS to record the state of an
  30887. ** open shared memory connection.
  30888. **
  30889. ** The following fields are initialized when this object is created and
  30890. ** are read-only thereafter:
  30891. **
  30892. ** winShm.pShmNode
  30893. ** winShm.id
  30894. **
  30895. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  30896. ** while accessing any read/write fields.
  30897. */
  30898. struct winShm {
  30899. winShmNode *pShmNode; /* The underlying winShmNode object */
  30900. winShm *pNext; /* Next winShm with the same winShmNode */
  30901. u8 hasMutex; /* True if holding the winShmNode mutex */
  30902. u16 sharedMask; /* Mask of shared locks held */
  30903. u16 exclMask; /* Mask of exclusive locks held */
  30904. #ifdef SQLITE_DEBUG
  30905. u8 id; /* Id of this connection with its winShmNode */
  30906. #endif
  30907. };
  30908. /*
  30909. ** Constants used for locking
  30910. */
  30911. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  30912. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  30913. /*
  30914. ** Apply advisory locks for all n bytes beginning at ofst.
  30915. */
  30916. #define _SHM_UNLCK 1
  30917. #define _SHM_RDLCK 2
  30918. #define _SHM_WRLCK 3
  30919. static int winShmSystemLock(
  30920. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  30921. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  30922. int ofst, /* Offset to first byte to be locked/unlocked */
  30923. int nByte /* Number of bytes to lock or unlock */
  30924. ){
  30925. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  30926. /* Access to the winShmNode object is serialized by the caller */
  30927. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  30928. /* Release/Acquire the system-level lock */
  30929. if( lockType==_SHM_UNLCK ){
  30930. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  30931. }else{
  30932. /* Initialize the locking parameters */
  30933. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  30934. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  30935. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  30936. }
  30937. if( rc!= 0 ){
  30938. rc = SQLITE_OK;
  30939. }else{
  30940. pFile->lastErrno = osGetLastError();
  30941. rc = SQLITE_BUSY;
  30942. }
  30943. OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
  30944. pFile->hFile.h,
  30945. rc==SQLITE_OK ? "ok" : "failed",
  30946. lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
  30947. pFile->lastErrno));
  30948. return rc;
  30949. }
  30950. /* Forward references to VFS methods */
  30951. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  30952. static int winDelete(sqlite3_vfs *,const char*,int);
  30953. /*
  30954. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  30955. **
  30956. ** This is not a VFS shared-memory method; it is a utility function called
  30957. ** by VFS shared-memory methods.
  30958. */
  30959. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  30960. winShmNode **pp;
  30961. winShmNode *p;
  30962. BOOL bRc;
  30963. assert( winShmMutexHeld() );
  30964. pp = &winShmNodeList;
  30965. while( (p = *pp)!=0 ){
  30966. if( p->nRef==0 ){
  30967. int i;
  30968. if( p->mutex ) sqlite3_mutex_free(p->mutex);
  30969. for(i=0; i<p->nRegion; i++){
  30970. bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  30971. OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
  30972. (int)osGetCurrentProcessId(), i,
  30973. bRc ? "ok" : "failed"));
  30974. bRc = osCloseHandle(p->aRegion[i].hMap);
  30975. OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
  30976. (int)osGetCurrentProcessId(), i,
  30977. bRc ? "ok" : "failed"));
  30978. }
  30979. if( p->hFile.h != INVALID_HANDLE_VALUE ){
  30980. SimulateIOErrorBenign(1);
  30981. winClose((sqlite3_file *)&p->hFile);
  30982. SimulateIOErrorBenign(0);
  30983. }
  30984. if( deleteFlag ){
  30985. SimulateIOErrorBenign(1);
  30986. sqlite3BeginBenignMalloc();
  30987. winDelete(pVfs, p->zFilename, 0);
  30988. sqlite3EndBenignMalloc();
  30989. SimulateIOErrorBenign(0);
  30990. }
  30991. *pp = p->pNext;
  30992. sqlite3_free(p->aRegion);
  30993. sqlite3_free(p);
  30994. }else{
  30995. pp = &p->pNext;
  30996. }
  30997. }
  30998. }
  30999. /*
  31000. ** Open the shared-memory area associated with database file pDbFd.
  31001. **
  31002. ** When opening a new shared-memory file, if no other instances of that
  31003. ** file are currently open, in this process or in other processes, then
  31004. ** the file must be truncated to zero length or have its header cleared.
  31005. */
  31006. static int winOpenSharedMemory(winFile *pDbFd){
  31007. struct winShm *p; /* The connection to be opened */
  31008. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  31009. int rc; /* Result code */
  31010. struct winShmNode *pNew; /* Newly allocated winShmNode */
  31011. int nName; /* Size of zName in bytes */
  31012. assert( pDbFd->pShm==0 ); /* Not previously opened */
  31013. /* Allocate space for the new sqlite3_shm object. Also speculatively
  31014. ** allocate space for a new winShmNode and filename.
  31015. */
  31016. p = sqlite3MallocZero( sizeof(*p) );
  31017. if( p==0 ) return SQLITE_IOERR_NOMEM;
  31018. nName = sqlite3Strlen30(pDbFd->zPath);
  31019. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  31020. if( pNew==0 ){
  31021. sqlite3_free(p);
  31022. return SQLITE_IOERR_NOMEM;
  31023. }
  31024. pNew->zFilename = (char*)&pNew[1];
  31025. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  31026. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  31027. /* Look to see if there is an existing winShmNode that can be used.
  31028. ** If no matching winShmNode currently exists, create a new one.
  31029. */
  31030. winShmEnterMutex();
  31031. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  31032. /* TBD need to come up with better match here. Perhaps
  31033. ** use FILE_ID_BOTH_DIR_INFO Structure.
  31034. */
  31035. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  31036. }
  31037. if( pShmNode ){
  31038. sqlite3_free(pNew);
  31039. }else{
  31040. pShmNode = pNew;
  31041. pNew = 0;
  31042. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  31043. pShmNode->pNext = winShmNodeList;
  31044. winShmNodeList = pShmNode;
  31045. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  31046. if( pShmNode->mutex==0 ){
  31047. rc = SQLITE_IOERR_NOMEM;
  31048. goto shm_open_err;
  31049. }
  31050. rc = winOpen(pDbFd->pVfs,
  31051. pShmNode->zFilename, /* Name of the file (UTF-8) */
  31052. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  31053. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
  31054. 0);
  31055. if( SQLITE_OK!=rc ){
  31056. goto shm_open_err;
  31057. }
  31058. /* Check to see if another process is holding the dead-man switch.
  31059. ** If not, truncate the file to zero length.
  31060. */
  31061. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  31062. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  31063. if( rc!=SQLITE_OK ){
  31064. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  31065. "winOpenShm", pDbFd->zPath);
  31066. }
  31067. }
  31068. if( rc==SQLITE_OK ){
  31069. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31070. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  31071. }
  31072. if( rc ) goto shm_open_err;
  31073. }
  31074. /* Make the new connection a child of the winShmNode */
  31075. p->pShmNode = pShmNode;
  31076. #ifdef SQLITE_DEBUG
  31077. p->id = pShmNode->nextShmId++;
  31078. #endif
  31079. pShmNode->nRef++;
  31080. pDbFd->pShm = p;
  31081. winShmLeaveMutex();
  31082. /* The reference count on pShmNode has already been incremented under
  31083. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  31084. ** new (struct winShm) object to the pShmNode has been set. All that is
  31085. ** left to do is to link the new object into the linked list starting
  31086. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  31087. ** mutex.
  31088. */
  31089. sqlite3_mutex_enter(pShmNode->mutex);
  31090. p->pNext = pShmNode->pFirst;
  31091. pShmNode->pFirst = p;
  31092. sqlite3_mutex_leave(pShmNode->mutex);
  31093. return SQLITE_OK;
  31094. /* Jump here on any error */
  31095. shm_open_err:
  31096. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  31097. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  31098. sqlite3_free(p);
  31099. sqlite3_free(pNew);
  31100. winShmLeaveMutex();
  31101. return rc;
  31102. }
  31103. /*
  31104. ** Close a connection to shared-memory. Delete the underlying
  31105. ** storage if deleteFlag is true.
  31106. */
  31107. static int winShmUnmap(
  31108. sqlite3_file *fd, /* Database holding shared memory */
  31109. int deleteFlag /* Delete after closing if true */
  31110. ){
  31111. winFile *pDbFd; /* Database holding shared-memory */
  31112. winShm *p; /* The connection to be closed */
  31113. winShmNode *pShmNode; /* The underlying shared-memory file */
  31114. winShm **pp; /* For looping over sibling connections */
  31115. pDbFd = (winFile*)fd;
  31116. p = pDbFd->pShm;
  31117. if( p==0 ) return SQLITE_OK;
  31118. pShmNode = p->pShmNode;
  31119. /* Remove connection p from the set of connections associated
  31120. ** with pShmNode */
  31121. sqlite3_mutex_enter(pShmNode->mutex);
  31122. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  31123. *pp = p->pNext;
  31124. /* Free the connection p */
  31125. sqlite3_free(p);
  31126. pDbFd->pShm = 0;
  31127. sqlite3_mutex_leave(pShmNode->mutex);
  31128. /* If pShmNode->nRef has reached 0, then close the underlying
  31129. ** shared-memory file, too */
  31130. winShmEnterMutex();
  31131. assert( pShmNode->nRef>0 );
  31132. pShmNode->nRef--;
  31133. if( pShmNode->nRef==0 ){
  31134. winShmPurge(pDbFd->pVfs, deleteFlag);
  31135. }
  31136. winShmLeaveMutex();
  31137. return SQLITE_OK;
  31138. }
  31139. /*
  31140. ** Change the lock state for a shared-memory segment.
  31141. */
  31142. static int winShmLock(
  31143. sqlite3_file *fd, /* Database file holding the shared memory */
  31144. int ofst, /* First lock to acquire or release */
  31145. int n, /* Number of locks to acquire or release */
  31146. int flags /* What to do with the lock */
  31147. ){
  31148. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  31149. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  31150. winShm *pX; /* For looping over all siblings */
  31151. winShmNode *pShmNode = p->pShmNode;
  31152. int rc = SQLITE_OK; /* Result code */
  31153. u16 mask; /* Mask of locks to take or release */
  31154. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  31155. assert( n>=1 );
  31156. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  31157. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  31158. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  31159. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  31160. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  31161. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  31162. assert( n>1 || mask==(1<<ofst) );
  31163. sqlite3_mutex_enter(pShmNode->mutex);
  31164. if( flags & SQLITE_SHM_UNLOCK ){
  31165. u16 allMask = 0; /* Mask of locks held by siblings */
  31166. /* See if any siblings hold this same lock */
  31167. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31168. if( pX==p ) continue;
  31169. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  31170. allMask |= pX->sharedMask;
  31171. }
  31172. /* Unlock the system-level locks */
  31173. if( (mask & allMask)==0 ){
  31174. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  31175. }else{
  31176. rc = SQLITE_OK;
  31177. }
  31178. /* Undo the local locks */
  31179. if( rc==SQLITE_OK ){
  31180. p->exclMask &= ~mask;
  31181. p->sharedMask &= ~mask;
  31182. }
  31183. }else if( flags & SQLITE_SHM_SHARED ){
  31184. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  31185. /* Find out which shared locks are already held by sibling connections.
  31186. ** If any sibling already holds an exclusive lock, go ahead and return
  31187. ** SQLITE_BUSY.
  31188. */
  31189. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31190. if( (pX->exclMask & mask)!=0 ){
  31191. rc = SQLITE_BUSY;
  31192. break;
  31193. }
  31194. allShared |= pX->sharedMask;
  31195. }
  31196. /* Get shared locks at the system level, if necessary */
  31197. if( rc==SQLITE_OK ){
  31198. if( (allShared & mask)==0 ){
  31199. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  31200. }else{
  31201. rc = SQLITE_OK;
  31202. }
  31203. }
  31204. /* Get the local shared locks */
  31205. if( rc==SQLITE_OK ){
  31206. p->sharedMask |= mask;
  31207. }
  31208. }else{
  31209. /* Make sure no sibling connections hold locks that will block this
  31210. ** lock. If any do, return SQLITE_BUSY right away.
  31211. */
  31212. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  31213. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  31214. rc = SQLITE_BUSY;
  31215. break;
  31216. }
  31217. }
  31218. /* Get the exclusive locks at the system level. Then if successful
  31219. ** also mark the local connection as being locked.
  31220. */
  31221. if( rc==SQLITE_OK ){
  31222. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  31223. if( rc==SQLITE_OK ){
  31224. assert( (p->sharedMask & mask)==0 );
  31225. p->exclMask |= mask;
  31226. }
  31227. }
  31228. }
  31229. sqlite3_mutex_leave(pShmNode->mutex);
  31230. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
  31231. p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
  31232. rc ? "failed" : "ok"));
  31233. return rc;
  31234. }
  31235. /*
  31236. ** Implement a memory barrier or memory fence on shared memory.
  31237. **
  31238. ** All loads and stores begun before the barrier must complete before
  31239. ** any load or store begun after the barrier.
  31240. */
  31241. static void winShmBarrier(
  31242. sqlite3_file *fd /* Database holding the shared memory */
  31243. ){
  31244. UNUSED_PARAMETER(fd);
  31245. /* MemoryBarrier(); // does not work -- do not know why not */
  31246. winShmEnterMutex();
  31247. winShmLeaveMutex();
  31248. }
  31249. /*
  31250. ** This function is called to obtain a pointer to region iRegion of the
  31251. ** shared-memory associated with the database file fd. Shared-memory regions
  31252. ** are numbered starting from zero. Each shared-memory region is szRegion
  31253. ** bytes in size.
  31254. **
  31255. ** If an error occurs, an error code is returned and *pp is set to NULL.
  31256. **
  31257. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  31258. ** region has not been allocated (by any client, including one running in a
  31259. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  31260. ** isWrite is non-zero and the requested shared-memory region has not yet
  31261. ** been allocated, it is allocated by this function.
  31262. **
  31263. ** If the shared-memory region has already been allocated or is allocated by
  31264. ** this call as described above, then it is mapped into this processes
  31265. ** address space (if it is not already), *pp is set to point to the mapped
  31266. ** memory and SQLITE_OK returned.
  31267. */
  31268. static int winShmMap(
  31269. sqlite3_file *fd, /* Handle open on database file */
  31270. int iRegion, /* Region to retrieve */
  31271. int szRegion, /* Size of regions */
  31272. int isWrite, /* True to extend file if necessary */
  31273. void volatile **pp /* OUT: Mapped memory */
  31274. ){
  31275. winFile *pDbFd = (winFile*)fd;
  31276. winShm *p = pDbFd->pShm;
  31277. winShmNode *pShmNode;
  31278. int rc = SQLITE_OK;
  31279. if( !p ){
  31280. rc = winOpenSharedMemory(pDbFd);
  31281. if( rc!=SQLITE_OK ) return rc;
  31282. p = pDbFd->pShm;
  31283. }
  31284. pShmNode = p->pShmNode;
  31285. sqlite3_mutex_enter(pShmNode->mutex);
  31286. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  31287. if( pShmNode->nRegion<=iRegion ){
  31288. struct ShmRegion *apNew; /* New aRegion[] array */
  31289. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  31290. sqlite3_int64 sz; /* Current size of wal-index file */
  31291. pShmNode->szRegion = szRegion;
  31292. /* The requested region is not mapped into this processes address space.
  31293. ** Check to see if it has been allocated (i.e. if the wal-index file is
  31294. ** large enough to contain the requested region).
  31295. */
  31296. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  31297. if( rc!=SQLITE_OK ){
  31298. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  31299. "winShmMap1", pDbFd->zPath);
  31300. goto shmpage_out;
  31301. }
  31302. if( sz<nByte ){
  31303. /* The requested memory region does not exist. If isWrite is set to
  31304. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  31305. **
  31306. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  31307. ** the requested memory region.
  31308. */
  31309. if( !isWrite ) goto shmpage_out;
  31310. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  31311. if( rc!=SQLITE_OK ){
  31312. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  31313. "winShmMap2", pDbFd->zPath);
  31314. goto shmpage_out;
  31315. }
  31316. }
  31317. /* Map the requested memory region into this processes address space. */
  31318. apNew = (struct ShmRegion *)sqlite3_realloc(
  31319. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  31320. );
  31321. if( !apNew ){
  31322. rc = SQLITE_IOERR_NOMEM;
  31323. goto shmpage_out;
  31324. }
  31325. pShmNode->aRegion = apNew;
  31326. while( pShmNode->nRegion<=iRegion ){
  31327. HANDLE hMap = NULL; /* file-mapping handle */
  31328. void *pMap = 0; /* Mapped memory region */
  31329. #if SQLITE_OS_WINRT
  31330. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  31331. NULL, PAGE_READWRITE, nByte, NULL
  31332. );
  31333. #elif defined(SQLITE_WIN32_HAS_WIDE)
  31334. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  31335. NULL, PAGE_READWRITE, 0, nByte, NULL
  31336. );
  31337. #elif defined(SQLITE_WIN32_HAS_ANSI)
  31338. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  31339. NULL, PAGE_READWRITE, 0, nByte, NULL
  31340. );
  31341. #endif
  31342. OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
  31343. (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  31344. hMap ? "ok" : "failed"));
  31345. if( hMap ){
  31346. int iOffset = pShmNode->nRegion*szRegion;
  31347. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  31348. #if SQLITE_OS_WINRT
  31349. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  31350. iOffset - iOffsetShift, szRegion + iOffsetShift
  31351. );
  31352. #else
  31353. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  31354. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  31355. );
  31356. #endif
  31357. OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
  31358. (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  31359. szRegion, pMap ? "ok" : "failed"));
  31360. }
  31361. if( !pMap ){
  31362. pShmNode->lastErrno = osGetLastError();
  31363. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  31364. "winShmMap3", pDbFd->zPath);
  31365. if( hMap ) osCloseHandle(hMap);
  31366. goto shmpage_out;
  31367. }
  31368. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  31369. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  31370. pShmNode->nRegion++;
  31371. }
  31372. }
  31373. shmpage_out:
  31374. if( pShmNode->nRegion>iRegion ){
  31375. int iOffset = iRegion*szRegion;
  31376. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  31377. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  31378. *pp = (void *)&p[iOffsetShift];
  31379. }else{
  31380. *pp = 0;
  31381. }
  31382. sqlite3_mutex_leave(pShmNode->mutex);
  31383. return rc;
  31384. }
  31385. #else
  31386. # define winShmMap 0
  31387. # define winShmLock 0
  31388. # define winShmBarrier 0
  31389. # define winShmUnmap 0
  31390. #endif /* #ifndef SQLITE_OMIT_WAL */
  31391. /*
  31392. ** Here ends the implementation of all sqlite3_file methods.
  31393. **
  31394. ********************** End sqlite3_file Methods *******************************
  31395. ******************************************************************************/
  31396. /*
  31397. ** This vector defines all the methods that can operate on an
  31398. ** sqlite3_file for win32.
  31399. */
  31400. static const sqlite3_io_methods winIoMethod = {
  31401. 2, /* iVersion */
  31402. winClose, /* xClose */
  31403. winRead, /* xRead */
  31404. winWrite, /* xWrite */
  31405. winTruncate, /* xTruncate */
  31406. winSync, /* xSync */
  31407. winFileSize, /* xFileSize */
  31408. winLock, /* xLock */
  31409. winUnlock, /* xUnlock */
  31410. winCheckReservedLock, /* xCheckReservedLock */
  31411. winFileControl, /* xFileControl */
  31412. winSectorSize, /* xSectorSize */
  31413. winDeviceCharacteristics, /* xDeviceCharacteristics */
  31414. winShmMap, /* xShmMap */
  31415. winShmLock, /* xShmLock */
  31416. winShmBarrier, /* xShmBarrier */
  31417. winShmUnmap /* xShmUnmap */
  31418. };
  31419. /****************************************************************************
  31420. **************************** sqlite3_vfs methods ****************************
  31421. **
  31422. ** This division contains the implementation of methods on the
  31423. ** sqlite3_vfs object.
  31424. */
  31425. /*
  31426. ** Convert a UTF-8 filename into whatever form the underlying
  31427. ** operating system wants filenames in. Space to hold the result
  31428. ** is obtained from malloc and must be freed by the calling
  31429. ** function.
  31430. */
  31431. static void *convertUtf8Filename(const char *zFilename){
  31432. void *zConverted = 0;
  31433. if( isNT() ){
  31434. zConverted = utf8ToUnicode(zFilename);
  31435. }
  31436. #ifdef SQLITE_WIN32_HAS_ANSI
  31437. else{
  31438. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  31439. }
  31440. #endif
  31441. /* caller will handle out of memory */
  31442. return zConverted;
  31443. }
  31444. /*
  31445. ** Create a temporary file name in zBuf. zBuf must be big enough to
  31446. ** hold at pVfs->mxPathname characters.
  31447. */
  31448. static int getTempname(int nBuf, char *zBuf){
  31449. static char zChars[] =
  31450. "abcdefghijklmnopqrstuvwxyz"
  31451. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  31452. "0123456789";
  31453. size_t i, j;
  31454. int nTempPath;
  31455. char zTempPath[MAX_PATH+2];
  31456. /* It's odd to simulate an io-error here, but really this is just
  31457. ** using the io-error infrastructure to test that SQLite handles this
  31458. ** function failing.
  31459. */
  31460. SimulateIOError( return SQLITE_IOERR );
  31461. memset(zTempPath, 0, MAX_PATH+2);
  31462. if( sqlite3_temp_directory ){
  31463. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  31464. }
  31465. #if !SQLITE_OS_WINRT
  31466. else if( isNT() ){
  31467. char *zMulti;
  31468. WCHAR zWidePath[MAX_PATH];
  31469. osGetTempPathW(MAX_PATH-30, zWidePath);
  31470. zMulti = unicodeToUtf8(zWidePath);
  31471. if( zMulti ){
  31472. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  31473. sqlite3_free(zMulti);
  31474. }else{
  31475. return SQLITE_IOERR_NOMEM;
  31476. }
  31477. }
  31478. #ifdef SQLITE_WIN32_HAS_ANSI
  31479. else{
  31480. char *zUtf8;
  31481. char zMbcsPath[MAX_PATH];
  31482. osGetTempPathA(MAX_PATH-30, zMbcsPath);
  31483. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  31484. if( zUtf8 ){
  31485. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  31486. sqlite3_free(zUtf8);
  31487. }else{
  31488. return SQLITE_IOERR_NOMEM;
  31489. }
  31490. }
  31491. #endif
  31492. #endif
  31493. /* Check that the output buffer is large enough for the temporary file
  31494. ** name. If it is not, return SQLITE_ERROR.
  31495. */
  31496. nTempPath = sqlite3Strlen30(zTempPath);
  31497. if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  31498. return SQLITE_ERROR;
  31499. }
  31500. for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
  31501. zTempPath[i] = 0;
  31502. sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
  31503. "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
  31504. zTempPath);
  31505. j = sqlite3Strlen30(zBuf);
  31506. sqlite3_randomness(15, &zBuf[j]);
  31507. for(i=0; i<15; i++, j++){
  31508. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  31509. }
  31510. zBuf[j] = 0;
  31511. zBuf[j+1] = 0;
  31512. OSTRACE(("TEMP FILENAME: %s\n", zBuf));
  31513. return SQLITE_OK;
  31514. }
  31515. /*
  31516. ** Return TRUE if the named file is really a directory. Return false if
  31517. ** it is something other than a directory, or if there is any kind of memory
  31518. ** allocation failure.
  31519. */
  31520. static int winIsDir(const void *zConverted){
  31521. DWORD attr;
  31522. int rc = 0;
  31523. DWORD lastErrno;
  31524. if( isNT() ){
  31525. int cnt = 0;
  31526. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  31527. memset(&sAttrData, 0, sizeof(sAttrData));
  31528. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  31529. GetFileExInfoStandard,
  31530. &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
  31531. if( !rc ){
  31532. return 0; /* Invalid name? */
  31533. }
  31534. attr = sAttrData.dwFileAttributes;
  31535. #if SQLITE_OS_WINCE==0
  31536. }else{
  31537. attr = osGetFileAttributesA((char*)zConverted);
  31538. #endif
  31539. }
  31540. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  31541. }
  31542. /*
  31543. ** Open a file.
  31544. */
  31545. static int winOpen(
  31546. sqlite3_vfs *pVfs, /* Not used */
  31547. const char *zName, /* Name of the file (UTF-8) */
  31548. sqlite3_file *id, /* Write the SQLite file handle here */
  31549. int flags, /* Open mode flags */
  31550. int *pOutFlags /* Status return flags */
  31551. ){
  31552. HANDLE h;
  31553. DWORD lastErrno;
  31554. DWORD dwDesiredAccess;
  31555. DWORD dwShareMode;
  31556. DWORD dwCreationDisposition;
  31557. DWORD dwFlagsAndAttributes = 0;
  31558. #if SQLITE_OS_WINCE
  31559. int isTemp = 0;
  31560. #endif
  31561. winFile *pFile = (winFile*)id;
  31562. void *zConverted; /* Filename in OS encoding */
  31563. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  31564. int cnt = 0;
  31565. /* If argument zPath is a NULL pointer, this function is required to open
  31566. ** a temporary file. Use this buffer to store the file name in.
  31567. */
  31568. char zTmpname[MAX_PATH+2]; /* Buffer used to create temp filename */
  31569. int rc = SQLITE_OK; /* Function Return Code */
  31570. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  31571. int eType = flags&0xFFFFFF00; /* Type of file to open */
  31572. #endif
  31573. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  31574. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  31575. int isCreate = (flags & SQLITE_OPEN_CREATE);
  31576. #ifndef NDEBUG
  31577. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  31578. #endif
  31579. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  31580. #ifndef NDEBUG
  31581. int isOpenJournal = (isCreate && (
  31582. eType==SQLITE_OPEN_MASTER_JOURNAL
  31583. || eType==SQLITE_OPEN_MAIN_JOURNAL
  31584. || eType==SQLITE_OPEN_WAL
  31585. ));
  31586. #endif
  31587. /* Check the following statements are true:
  31588. **
  31589. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  31590. ** (b) if CREATE is set, then READWRITE must also be set, and
  31591. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  31592. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  31593. */
  31594. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  31595. assert(isCreate==0 || isReadWrite);
  31596. assert(isExclusive==0 || isCreate);
  31597. assert(isDelete==0 || isCreate);
  31598. /* The main DB, main journal, WAL file and master journal are never
  31599. ** automatically deleted. Nor are they ever temporary files. */
  31600. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  31601. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  31602. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  31603. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  31604. /* Assert that the upper layer has set one of the "file-type" flags. */
  31605. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  31606. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  31607. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  31608. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  31609. );
  31610. assert( id!=0 );
  31611. UNUSED_PARAMETER(pVfs);
  31612. #if SQLITE_OS_WINRT
  31613. if( !sqlite3_temp_directory ){
  31614. sqlite3_log(SQLITE_ERROR,
  31615. "sqlite3_temp_directory variable should be set for WinRT");
  31616. }
  31617. #endif
  31618. pFile->h = INVALID_HANDLE_VALUE;
  31619. /* If the second argument to this function is NULL, generate a
  31620. ** temporary file name to use
  31621. */
  31622. if( !zUtf8Name ){
  31623. assert(isDelete && !isOpenJournal);
  31624. rc = getTempname(MAX_PATH+2, zTmpname);
  31625. if( rc!=SQLITE_OK ){
  31626. return rc;
  31627. }
  31628. zUtf8Name = zTmpname;
  31629. }
  31630. /* Database filenames are double-zero terminated if they are not
  31631. ** URIs with parameters. Hence, they can always be passed into
  31632. ** sqlite3_uri_parameter().
  31633. */
  31634. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  31635. zUtf8Name[strlen(zUtf8Name)+1]==0 );
  31636. /* Convert the filename to the system encoding. */
  31637. zConverted = convertUtf8Filename(zUtf8Name);
  31638. if( zConverted==0 ){
  31639. return SQLITE_IOERR_NOMEM;
  31640. }
  31641. if( winIsDir(zConverted) ){
  31642. sqlite3_free(zConverted);
  31643. return SQLITE_CANTOPEN_ISDIR;
  31644. }
  31645. if( isReadWrite ){
  31646. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  31647. }else{
  31648. dwDesiredAccess = GENERIC_READ;
  31649. }
  31650. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  31651. ** created. SQLite doesn't use it to indicate "exclusive access"
  31652. ** as it is usually understood.
  31653. */
  31654. if( isExclusive ){
  31655. /* Creates a new file, only if it does not already exist. */
  31656. /* If the file exists, it fails. */
  31657. dwCreationDisposition = CREATE_NEW;
  31658. }else if( isCreate ){
  31659. /* Open existing file, or create if it doesn't exist */
  31660. dwCreationDisposition = OPEN_ALWAYS;
  31661. }else{
  31662. /* Opens a file, only if it exists. */
  31663. dwCreationDisposition = OPEN_EXISTING;
  31664. }
  31665. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  31666. if( isDelete ){
  31667. #if SQLITE_OS_WINCE
  31668. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  31669. isTemp = 1;
  31670. #else
  31671. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  31672. | FILE_ATTRIBUTE_HIDDEN
  31673. | FILE_FLAG_DELETE_ON_CLOSE;
  31674. #endif
  31675. }else{
  31676. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  31677. }
  31678. /* Reports from the internet are that performance is always
  31679. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  31680. #if SQLITE_OS_WINCE
  31681. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  31682. #endif
  31683. if( isNT() ){
  31684. #if SQLITE_OS_WINRT
  31685. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  31686. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  31687. extendedParameters.dwFileAttributes =
  31688. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  31689. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  31690. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  31691. extendedParameters.lpSecurityAttributes = NULL;
  31692. extendedParameters.hTemplateFile = NULL;
  31693. while( (h = osCreateFile2((LPCWSTR)zConverted,
  31694. dwDesiredAccess,
  31695. dwShareMode,
  31696. dwCreationDisposition,
  31697. &extendedParameters))==INVALID_HANDLE_VALUE &&
  31698. retryIoerr(&cnt, &lastErrno) ){
  31699. /* Noop */
  31700. }
  31701. #else
  31702. while( (h = osCreateFileW((LPCWSTR)zConverted,
  31703. dwDesiredAccess,
  31704. dwShareMode, NULL,
  31705. dwCreationDisposition,
  31706. dwFlagsAndAttributes,
  31707. NULL))==INVALID_HANDLE_VALUE &&
  31708. retryIoerr(&cnt, &lastErrno) ){
  31709. /* Noop */
  31710. }
  31711. #endif
  31712. }
  31713. #ifdef SQLITE_WIN32_HAS_ANSI
  31714. else{
  31715. while( (h = osCreateFileA((LPCSTR)zConverted,
  31716. dwDesiredAccess,
  31717. dwShareMode, NULL,
  31718. dwCreationDisposition,
  31719. dwFlagsAndAttributes,
  31720. NULL))==INVALID_HANDLE_VALUE &&
  31721. retryIoerr(&cnt, &lastErrno) ){
  31722. /* Noop */
  31723. }
  31724. }
  31725. #endif
  31726. logIoerr(cnt);
  31727. OSTRACE(("OPEN %d %s 0x%lx %s\n",
  31728. h, zName, dwDesiredAccess,
  31729. h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
  31730. if( h==INVALID_HANDLE_VALUE ){
  31731. pFile->lastErrno = lastErrno;
  31732. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  31733. sqlite3_free(zConverted);
  31734. if( isReadWrite && !isExclusive ){
  31735. return winOpen(pVfs, zName, id,
  31736. ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
  31737. }else{
  31738. return SQLITE_CANTOPEN_BKPT;
  31739. }
  31740. }
  31741. if( pOutFlags ){
  31742. if( isReadWrite ){
  31743. *pOutFlags = SQLITE_OPEN_READWRITE;
  31744. }else{
  31745. *pOutFlags = SQLITE_OPEN_READONLY;
  31746. }
  31747. }
  31748. memset(pFile, 0, sizeof(*pFile));
  31749. pFile->pMethod = &winIoMethod;
  31750. pFile->h = h;
  31751. pFile->lastErrno = NO_ERROR;
  31752. pFile->pVfs = pVfs;
  31753. #ifndef SQLITE_OMIT_WAL
  31754. pFile->pShm = 0;
  31755. #endif
  31756. pFile->zPath = zName;
  31757. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  31758. pFile->ctrlFlags |= WINFILE_PSOW;
  31759. }
  31760. #if SQLITE_OS_WINCE
  31761. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  31762. && !winceCreateLock(zName, pFile)
  31763. ){
  31764. osCloseHandle(h);
  31765. sqlite3_free(zConverted);
  31766. return SQLITE_CANTOPEN_BKPT;
  31767. }
  31768. if( isTemp ){
  31769. pFile->zDeleteOnClose = zConverted;
  31770. }else
  31771. #endif
  31772. {
  31773. sqlite3_free(zConverted);
  31774. }
  31775. OpenCounter(+1);
  31776. return rc;
  31777. }
  31778. /*
  31779. ** Delete the named file.
  31780. **
  31781. ** Note that Windows does not allow a file to be deleted if some other
  31782. ** process has it open. Sometimes a virus scanner or indexing program
  31783. ** will open a journal file shortly after it is created in order to do
  31784. ** whatever it does. While this other process is holding the
  31785. ** file open, we will be unable to delete it. To work around this
  31786. ** problem, we delay 100 milliseconds and try to delete again. Up
  31787. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  31788. ** up and returning an error.
  31789. */
  31790. static int winDelete(
  31791. sqlite3_vfs *pVfs, /* Not used on win32 */
  31792. const char *zFilename, /* Name of file to delete */
  31793. int syncDir /* Not used on win32 */
  31794. ){
  31795. int cnt = 0;
  31796. int rc;
  31797. DWORD attr;
  31798. DWORD lastErrno;
  31799. void *zConverted;
  31800. UNUSED_PARAMETER(pVfs);
  31801. UNUSED_PARAMETER(syncDir);
  31802. SimulateIOError(return SQLITE_IOERR_DELETE);
  31803. zConverted = convertUtf8Filename(zFilename);
  31804. if( zConverted==0 ){
  31805. return SQLITE_IOERR_NOMEM;
  31806. }
  31807. if( isNT() ){
  31808. do {
  31809. #if SQLITE_OS_WINRT
  31810. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  31811. memset(&sAttrData, 0, sizeof(sAttrData));
  31812. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  31813. &sAttrData) ){
  31814. attr = sAttrData.dwFileAttributes;
  31815. }else{
  31816. lastErrno = osGetLastError();
  31817. if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
  31818. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  31819. }else{
  31820. rc = SQLITE_ERROR;
  31821. }
  31822. break;
  31823. }
  31824. #else
  31825. attr = osGetFileAttributesW(zConverted);
  31826. #endif
  31827. if ( attr==INVALID_FILE_ATTRIBUTES ){
  31828. lastErrno = osGetLastError();
  31829. if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
  31830. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  31831. }else{
  31832. rc = SQLITE_ERROR;
  31833. }
  31834. break;
  31835. }
  31836. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  31837. rc = SQLITE_ERROR; /* Files only. */
  31838. break;
  31839. }
  31840. if ( osDeleteFileW(zConverted) ){
  31841. rc = SQLITE_OK; /* Deleted OK. */
  31842. break;
  31843. }
  31844. if ( !retryIoerr(&cnt, &lastErrno) ){
  31845. rc = SQLITE_ERROR; /* No more retries. */
  31846. break;
  31847. }
  31848. } while(1);
  31849. }
  31850. #ifdef SQLITE_WIN32_HAS_ANSI
  31851. else{
  31852. do {
  31853. attr = osGetFileAttributesA(zConverted);
  31854. if ( attr==INVALID_FILE_ATTRIBUTES ){
  31855. lastErrno = osGetLastError();
  31856. if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
  31857. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  31858. }else{
  31859. rc = SQLITE_ERROR;
  31860. }
  31861. break;
  31862. }
  31863. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  31864. rc = SQLITE_ERROR; /* Files only. */
  31865. break;
  31866. }
  31867. if ( osDeleteFileA(zConverted) ){
  31868. rc = SQLITE_OK; /* Deleted OK. */
  31869. break;
  31870. }
  31871. if ( !retryIoerr(&cnt, &lastErrno) ){
  31872. rc = SQLITE_ERROR; /* No more retries. */
  31873. break;
  31874. }
  31875. } while(1);
  31876. }
  31877. #endif
  31878. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  31879. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
  31880. "winDelete", zFilename);
  31881. }else{
  31882. logIoerr(cnt);
  31883. }
  31884. sqlite3_free(zConverted);
  31885. OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
  31886. return rc;
  31887. }
  31888. /*
  31889. ** Check the existance and status of a file.
  31890. */
  31891. static int winAccess(
  31892. sqlite3_vfs *pVfs, /* Not used on win32 */
  31893. const char *zFilename, /* Name of file to check */
  31894. int flags, /* Type of test to make on this file */
  31895. int *pResOut /* OUT: Result */
  31896. ){
  31897. DWORD attr;
  31898. int rc = 0;
  31899. DWORD lastErrno;
  31900. void *zConverted;
  31901. UNUSED_PARAMETER(pVfs);
  31902. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  31903. zConverted = convertUtf8Filename(zFilename);
  31904. if( zConverted==0 ){
  31905. return SQLITE_IOERR_NOMEM;
  31906. }
  31907. if( isNT() ){
  31908. int cnt = 0;
  31909. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  31910. memset(&sAttrData, 0, sizeof(sAttrData));
  31911. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  31912. GetFileExInfoStandard,
  31913. &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
  31914. if( rc ){
  31915. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  31916. ** as if it does not exist.
  31917. */
  31918. if( flags==SQLITE_ACCESS_EXISTS
  31919. && sAttrData.nFileSizeHigh==0
  31920. && sAttrData.nFileSizeLow==0 ){
  31921. attr = INVALID_FILE_ATTRIBUTES;
  31922. }else{
  31923. attr = sAttrData.dwFileAttributes;
  31924. }
  31925. }else{
  31926. logIoerr(cnt);
  31927. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  31928. winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
  31929. sqlite3_free(zConverted);
  31930. return SQLITE_IOERR_ACCESS;
  31931. }else{
  31932. attr = INVALID_FILE_ATTRIBUTES;
  31933. }
  31934. }
  31935. }
  31936. #ifdef SQLITE_WIN32_HAS_ANSI
  31937. else{
  31938. attr = osGetFileAttributesA((char*)zConverted);
  31939. }
  31940. #endif
  31941. sqlite3_free(zConverted);
  31942. switch( flags ){
  31943. case SQLITE_ACCESS_READ:
  31944. case SQLITE_ACCESS_EXISTS:
  31945. rc = attr!=INVALID_FILE_ATTRIBUTES;
  31946. break;
  31947. case SQLITE_ACCESS_READWRITE:
  31948. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  31949. (attr & FILE_ATTRIBUTE_READONLY)==0;
  31950. break;
  31951. default:
  31952. assert(!"Invalid flags argument");
  31953. }
  31954. *pResOut = rc;
  31955. return SQLITE_OK;
  31956. }
  31957. /*
  31958. ** Returns non-zero if the specified path name should be used verbatim. If
  31959. ** non-zero is returned from this function, the calling function must simply
  31960. ** use the provided path name verbatim -OR- resolve it into a full path name
  31961. ** using the GetFullPathName Win32 API function (if available).
  31962. */
  31963. static BOOL winIsVerbatimPathname(
  31964. const char *zPathname
  31965. ){
  31966. /*
  31967. ** If the path name starts with a forward slash or a backslash, it is either
  31968. ** a legal UNC name, a volume relative path, or an absolute path name in the
  31969. ** "Unix" format on Windows. There is no easy way to differentiate between
  31970. ** the final two cases; therefore, we return the safer return value of TRUE
  31971. ** so that callers of this function will simply use it verbatim.
  31972. */
  31973. if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
  31974. return TRUE;
  31975. }
  31976. /*
  31977. ** If the path name starts with a letter and a colon it is either a volume
  31978. ** relative path or an absolute path. Callers of this function must not
  31979. ** attempt to treat it as a relative path name (i.e. they should simply use
  31980. ** it verbatim).
  31981. */
  31982. if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
  31983. return TRUE;
  31984. }
  31985. /*
  31986. ** If we get to this point, the path name should almost certainly be a purely
  31987. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  31988. */
  31989. return FALSE;
  31990. }
  31991. /*
  31992. ** Turn a relative pathname into a full pathname. Write the full
  31993. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  31994. ** bytes in size.
  31995. */
  31996. static int winFullPathname(
  31997. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  31998. const char *zRelative, /* Possibly relative input path */
  31999. int nFull, /* Size of output buffer in bytes */
  32000. char *zFull /* Output buffer */
  32001. ){
  32002. #if defined(__CYGWIN__)
  32003. SimulateIOError( return SQLITE_ERROR );
  32004. UNUSED_PARAMETER(nFull);
  32005. assert( pVfs->mxPathname>=MAX_PATH );
  32006. assert( nFull>=pVfs->mxPathname );
  32007. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32008. /*
  32009. ** NOTE: We are dealing with a relative path name and the data
  32010. ** directory has been set. Therefore, use it as the basis
  32011. ** for converting the relative path name to an absolute
  32012. ** one by prepending the data directory and a slash.
  32013. */
  32014. char zOut[MAX_PATH+1];
  32015. memset(zOut, 0, MAX_PATH+1);
  32016. cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */
  32017. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  32018. sqlite3_data_directory, zOut);
  32019. }else{
  32020. /*
  32021. ** NOTE: The Cygwin docs state that the maximum length needed
  32022. ** for the buffer passed to cygwin_conv_to_full_win32_path
  32023. ** is MAX_PATH.
  32024. */
  32025. cygwin_conv_to_full_win32_path(zRelative, zFull);
  32026. }
  32027. return SQLITE_OK;
  32028. #endif
  32029. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  32030. SimulateIOError( return SQLITE_ERROR );
  32031. /* WinCE has no concept of a relative pathname, or so I am told. */
  32032. /* WinRT has no way to convert a relative path to an absolute one. */
  32033. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32034. /*
  32035. ** NOTE: We are dealing with a relative path name and the data
  32036. ** directory has been set. Therefore, use it as the basis
  32037. ** for converting the relative path name to an absolute
  32038. ** one by prepending the data directory and a backslash.
  32039. */
  32040. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  32041. sqlite3_data_directory, zRelative);
  32042. }else{
  32043. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  32044. }
  32045. return SQLITE_OK;
  32046. #endif
  32047. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  32048. DWORD nByte;
  32049. void *zConverted;
  32050. char *zOut;
  32051. /* If this path name begins with "/X:", where "X" is any alphabetic
  32052. ** character, discard the initial "/" from the pathname.
  32053. */
  32054. if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
  32055. zRelative++;
  32056. }
  32057. /* It's odd to simulate an io-error here, but really this is just
  32058. ** using the io-error infrastructure to test that SQLite handles this
  32059. ** function failing. This function could fail if, for example, the
  32060. ** current working directory has been unlinked.
  32061. */
  32062. SimulateIOError( return SQLITE_ERROR );
  32063. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  32064. /*
  32065. ** NOTE: We are dealing with a relative path name and the data
  32066. ** directory has been set. Therefore, use it as the basis
  32067. ** for converting the relative path name to an absolute
  32068. ** one by prepending the data directory and a backslash.
  32069. */
  32070. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  32071. sqlite3_data_directory, zRelative);
  32072. return SQLITE_OK;
  32073. }
  32074. zConverted = convertUtf8Filename(zRelative);
  32075. if( zConverted==0 ){
  32076. return SQLITE_IOERR_NOMEM;
  32077. }
  32078. if( isNT() ){
  32079. LPWSTR zTemp;
  32080. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  32081. if( nByte==0 ){
  32082. winLogError(SQLITE_ERROR, osGetLastError(),
  32083. "GetFullPathNameW1", zConverted);
  32084. sqlite3_free(zConverted);
  32085. return SQLITE_CANTOPEN_FULLPATH;
  32086. }
  32087. nByte += 3;
  32088. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  32089. if( zTemp==0 ){
  32090. sqlite3_free(zConverted);
  32091. return SQLITE_IOERR_NOMEM;
  32092. }
  32093. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  32094. if( nByte==0 ){
  32095. winLogError(SQLITE_ERROR, osGetLastError(),
  32096. "GetFullPathNameW2", zConverted);
  32097. sqlite3_free(zConverted);
  32098. sqlite3_free(zTemp);
  32099. return SQLITE_CANTOPEN_FULLPATH;
  32100. }
  32101. sqlite3_free(zConverted);
  32102. zOut = unicodeToUtf8(zTemp);
  32103. sqlite3_free(zTemp);
  32104. }
  32105. #ifdef SQLITE_WIN32_HAS_ANSI
  32106. else{
  32107. char *zTemp;
  32108. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  32109. if( nByte==0 ){
  32110. winLogError(SQLITE_ERROR, osGetLastError(),
  32111. "GetFullPathNameA1", zConverted);
  32112. sqlite3_free(zConverted);
  32113. return SQLITE_CANTOPEN_FULLPATH;
  32114. }
  32115. nByte += 3;
  32116. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  32117. if( zTemp==0 ){
  32118. sqlite3_free(zConverted);
  32119. return SQLITE_IOERR_NOMEM;
  32120. }
  32121. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  32122. if( nByte==0 ){
  32123. winLogError(SQLITE_ERROR, osGetLastError(),
  32124. "GetFullPathNameA2", zConverted);
  32125. sqlite3_free(zConverted);
  32126. sqlite3_free(zTemp);
  32127. return SQLITE_CANTOPEN_FULLPATH;
  32128. }
  32129. sqlite3_free(zConverted);
  32130. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  32131. sqlite3_free(zTemp);
  32132. }
  32133. #endif
  32134. if( zOut ){
  32135. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  32136. sqlite3_free(zOut);
  32137. return SQLITE_OK;
  32138. }else{
  32139. return SQLITE_IOERR_NOMEM;
  32140. }
  32141. #endif
  32142. }
  32143. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  32144. /*
  32145. ** Interfaces for opening a shared library, finding entry points
  32146. ** within the shared library, and closing the shared library.
  32147. */
  32148. /*
  32149. ** Interfaces for opening a shared library, finding entry points
  32150. ** within the shared library, and closing the shared library.
  32151. */
  32152. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  32153. HANDLE h;
  32154. void *zConverted = convertUtf8Filename(zFilename);
  32155. UNUSED_PARAMETER(pVfs);
  32156. if( zConverted==0 ){
  32157. return 0;
  32158. }
  32159. if( isNT() ){
  32160. #if SQLITE_OS_WINRT
  32161. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  32162. #else
  32163. h = osLoadLibraryW((LPCWSTR)zConverted);
  32164. #endif
  32165. }
  32166. #ifdef SQLITE_WIN32_HAS_ANSI
  32167. else{
  32168. h = osLoadLibraryA((char*)zConverted);
  32169. }
  32170. #endif
  32171. sqlite3_free(zConverted);
  32172. return (void*)h;
  32173. }
  32174. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  32175. UNUSED_PARAMETER(pVfs);
  32176. getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  32177. }
  32178. static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  32179. UNUSED_PARAMETER(pVfs);
  32180. return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
  32181. }
  32182. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  32183. UNUSED_PARAMETER(pVfs);
  32184. osFreeLibrary((HANDLE)pHandle);
  32185. }
  32186. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  32187. #define winDlOpen 0
  32188. #define winDlError 0
  32189. #define winDlSym 0
  32190. #define winDlClose 0
  32191. #endif
  32192. /*
  32193. ** Write up to nBuf bytes of randomness into zBuf.
  32194. */
  32195. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  32196. int n = 0;
  32197. UNUSED_PARAMETER(pVfs);
  32198. #if defined(SQLITE_TEST)
  32199. n = nBuf;
  32200. memset(zBuf, 0, nBuf);
  32201. #else
  32202. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  32203. SYSTEMTIME x;
  32204. osGetSystemTime(&x);
  32205. memcpy(&zBuf[n], &x, sizeof(x));
  32206. n += sizeof(x);
  32207. }
  32208. if( sizeof(DWORD)<=nBuf-n ){
  32209. DWORD pid = osGetCurrentProcessId();
  32210. memcpy(&zBuf[n], &pid, sizeof(pid));
  32211. n += sizeof(pid);
  32212. }
  32213. #if SQLITE_OS_WINRT
  32214. if( sizeof(ULONGLONG)<=nBuf-n ){
  32215. ULONGLONG cnt = osGetTickCount64();
  32216. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  32217. n += sizeof(cnt);
  32218. }
  32219. #else
  32220. if( sizeof(DWORD)<=nBuf-n ){
  32221. DWORD cnt = osGetTickCount();
  32222. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  32223. n += sizeof(cnt);
  32224. }
  32225. #endif
  32226. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  32227. LARGE_INTEGER i;
  32228. osQueryPerformanceCounter(&i);
  32229. memcpy(&zBuf[n], &i, sizeof(i));
  32230. n += sizeof(i);
  32231. }
  32232. #endif
  32233. return n;
  32234. }
  32235. /*
  32236. ** Sleep for a little while. Return the amount of time slept.
  32237. */
  32238. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  32239. sqlite3_win32_sleep((microsec+999)/1000);
  32240. UNUSED_PARAMETER(pVfs);
  32241. return ((microsec+999)/1000)*1000;
  32242. }
  32243. /*
  32244. ** The following variable, if set to a non-zero value, is interpreted as
  32245. ** the number of seconds since 1970 and is used to set the result of
  32246. ** sqlite3OsCurrentTime() during testing.
  32247. */
  32248. #ifdef SQLITE_TEST
  32249. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  32250. #endif
  32251. /*
  32252. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  32253. ** the current time and date as a Julian Day number times 86_400_000. In
  32254. ** other words, write into *piNow the number of milliseconds since the Julian
  32255. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  32256. ** proleptic Gregorian calendar.
  32257. **
  32258. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  32259. ** cannot be found.
  32260. */
  32261. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  32262. /* FILETIME structure is a 64-bit value representing the number of
  32263. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  32264. */
  32265. FILETIME ft;
  32266. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  32267. #ifdef SQLITE_TEST
  32268. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  32269. #endif
  32270. /* 2^32 - to avoid use of LL and warnings in gcc */
  32271. static const sqlite3_int64 max32BitValue =
  32272. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
  32273. #if SQLITE_OS_WINCE
  32274. SYSTEMTIME time;
  32275. osGetSystemTime(&time);
  32276. /* if SystemTimeToFileTime() fails, it returns zero. */
  32277. if (!osSystemTimeToFileTime(&time,&ft)){
  32278. return SQLITE_ERROR;
  32279. }
  32280. #else
  32281. osGetSystemTimeAsFileTime( &ft );
  32282. #endif
  32283. *piNow = winFiletimeEpoch +
  32284. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  32285. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  32286. #ifdef SQLITE_TEST
  32287. if( sqlite3_current_time ){
  32288. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  32289. }
  32290. #endif
  32291. UNUSED_PARAMETER(pVfs);
  32292. return SQLITE_OK;
  32293. }
  32294. /*
  32295. ** Find the current time (in Universal Coordinated Time). Write the
  32296. ** current time and date as a Julian Day number into *prNow and
  32297. ** return 0. Return 1 if the time and date cannot be found.
  32298. */
  32299. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  32300. int rc;
  32301. sqlite3_int64 i;
  32302. rc = winCurrentTimeInt64(pVfs, &i);
  32303. if( !rc ){
  32304. *prNow = i/86400000.0;
  32305. }
  32306. return rc;
  32307. }
  32308. /*
  32309. ** The idea is that this function works like a combination of
  32310. ** GetLastError() and FormatMessage() on Windows (or errno and
  32311. ** strerror_r() on Unix). After an error is returned by an OS
  32312. ** function, SQLite calls this function with zBuf pointing to
  32313. ** a buffer of nBuf bytes. The OS layer should populate the
  32314. ** buffer with a nul-terminated UTF-8 encoded error message
  32315. ** describing the last IO error to have occurred within the calling
  32316. ** thread.
  32317. **
  32318. ** If the error message is too large for the supplied buffer,
  32319. ** it should be truncated. The return value of xGetLastError
  32320. ** is zero if the error message fits in the buffer, or non-zero
  32321. ** otherwise (if the message was truncated). If non-zero is returned,
  32322. ** then it is not necessary to include the nul-terminator character
  32323. ** in the output buffer.
  32324. **
  32325. ** Not supplying an error message will have no adverse effect
  32326. ** on SQLite. It is fine to have an implementation that never
  32327. ** returns an error message:
  32328. **
  32329. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  32330. ** assert(zBuf[0]=='\0');
  32331. ** return 0;
  32332. ** }
  32333. **
  32334. ** However if an error message is supplied, it will be incorporated
  32335. ** by sqlite into the error message available to the user using
  32336. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  32337. */
  32338. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  32339. UNUSED_PARAMETER(pVfs);
  32340. return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
  32341. }
  32342. /*
  32343. ** Initialize and deinitialize the operating system interface.
  32344. */
  32345. SQLITE_API int sqlite3_os_init(void){
  32346. static sqlite3_vfs winVfs = {
  32347. 3, /* iVersion */
  32348. sizeof(winFile), /* szOsFile */
  32349. MAX_PATH, /* mxPathname */
  32350. 0, /* pNext */
  32351. "win32", /* zName */
  32352. 0, /* pAppData */
  32353. winOpen, /* xOpen */
  32354. winDelete, /* xDelete */
  32355. winAccess, /* xAccess */
  32356. winFullPathname, /* xFullPathname */
  32357. winDlOpen, /* xDlOpen */
  32358. winDlError, /* xDlError */
  32359. winDlSym, /* xDlSym */
  32360. winDlClose, /* xDlClose */
  32361. winRandomness, /* xRandomness */
  32362. winSleep, /* xSleep */
  32363. winCurrentTime, /* xCurrentTime */
  32364. winGetLastError, /* xGetLastError */
  32365. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  32366. winSetSystemCall, /* xSetSystemCall */
  32367. winGetSystemCall, /* xGetSystemCall */
  32368. winNextSystemCall, /* xNextSystemCall */
  32369. };
  32370. /* Double-check that the aSyscall[] array has been constructed
  32371. ** correctly. See ticket [bb3a86e890c8e96ab] */
  32372. assert( ArraySize(aSyscall)==74 );
  32373. #ifndef SQLITE_OMIT_WAL
  32374. /* get memory map allocation granularity */
  32375. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  32376. #if SQLITE_OS_WINRT
  32377. osGetNativeSystemInfo(&winSysInfo);
  32378. #else
  32379. osGetSystemInfo(&winSysInfo);
  32380. #endif
  32381. assert(winSysInfo.dwAllocationGranularity > 0);
  32382. #endif
  32383. sqlite3_vfs_register(&winVfs, 1);
  32384. return SQLITE_OK;
  32385. }
  32386. SQLITE_API int sqlite3_os_end(void){
  32387. #if SQLITE_OS_WINRT
  32388. if( sleepObj!=NULL ){
  32389. osCloseHandle(sleepObj);
  32390. sleepObj = NULL;
  32391. }
  32392. #endif
  32393. return SQLITE_OK;
  32394. }
  32395. #endif /* SQLITE_OS_WIN */
  32396. /************** End of os_win.c **********************************************/
  32397. /************** Begin file bitvec.c ******************************************/
  32398. /*
  32399. ** 2008 February 16
  32400. **
  32401. ** The author disclaims copyright to this source code. In place of
  32402. ** a legal notice, here is a blessing:
  32403. **
  32404. ** May you do good and not evil.
  32405. ** May you find forgiveness for yourself and forgive others.
  32406. ** May you share freely, never taking more than you give.
  32407. **
  32408. *************************************************************************
  32409. ** This file implements an object that represents a fixed-length
  32410. ** bitmap. Bits are numbered starting with 1.
  32411. **
  32412. ** A bitmap is used to record which pages of a database file have been
  32413. ** journalled during a transaction, or which pages have the "dont-write"
  32414. ** property. Usually only a few pages are meet either condition.
  32415. ** So the bitmap is usually sparse and has low cardinality.
  32416. ** But sometimes (for example when during a DROP of a large table) most
  32417. ** or all of the pages in a database can get journalled. In those cases,
  32418. ** the bitmap becomes dense with high cardinality. The algorithm needs
  32419. ** to handle both cases well.
  32420. **
  32421. ** The size of the bitmap is fixed when the object is created.
  32422. **
  32423. ** All bits are clear when the bitmap is created. Individual bits
  32424. ** may be set or cleared one at a time.
  32425. **
  32426. ** Test operations are about 100 times more common that set operations.
  32427. ** Clear operations are exceedingly rare. There are usually between
  32428. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  32429. ** sometimes grow into tens of thousands or larger. The size of the
  32430. ** Bitvec object is the number of pages in the database file at the
  32431. ** start of a transaction, and is thus usually less than a few thousand,
  32432. ** but can be as large as 2 billion for a really big database.
  32433. */
  32434. /* Size of the Bitvec structure in bytes. */
  32435. #define BITVEC_SZ 512
  32436. /* Round the union size down to the nearest pointer boundary, since that's how
  32437. ** it will be aligned within the Bitvec struct. */
  32438. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  32439. /* Type of the array "element" for the bitmap representation.
  32440. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  32441. ** Setting this to the "natural word" size of your CPU may improve
  32442. ** performance. */
  32443. #define BITVEC_TELEM u8
  32444. /* Size, in bits, of the bitmap element. */
  32445. #define BITVEC_SZELEM 8
  32446. /* Number of elements in a bitmap array. */
  32447. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  32448. /* Number of bits in the bitmap array. */
  32449. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  32450. /* Number of u32 values in hash table. */
  32451. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  32452. /* Maximum number of entries in hash table before
  32453. ** sub-dividing and re-hashing. */
  32454. #define BITVEC_MXHASH (BITVEC_NINT/2)
  32455. /* Hashing function for the aHash representation.
  32456. ** Empirical testing showed that the *37 multiplier
  32457. ** (an arbitrary prime)in the hash function provided
  32458. ** no fewer collisions than the no-op *1. */
  32459. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  32460. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  32461. /*
  32462. ** A bitmap is an instance of the following structure.
  32463. **
  32464. ** This bitmap records the existance of zero or more bits
  32465. ** with values between 1 and iSize, inclusive.
  32466. **
  32467. ** There are three possible representations of the bitmap.
  32468. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  32469. ** bitmap. The least significant bit is bit 1.
  32470. **
  32471. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  32472. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  32473. **
  32474. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  32475. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  32476. ** handles up to iDivisor separate values of i. apSub[0] holds
  32477. ** values between 1 and iDivisor. apSub[1] holds values between
  32478. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  32479. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  32480. ** to hold deal with values between 1 and iDivisor.
  32481. */
  32482. struct Bitvec {
  32483. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  32484. u32 nSet; /* Number of bits that are set - only valid for aHash
  32485. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  32486. ** this would be 125. */
  32487. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  32488. /* Should >=0 for apSub element. */
  32489. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  32490. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  32491. union {
  32492. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  32493. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  32494. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  32495. } u;
  32496. };
  32497. /*
  32498. ** Create a new bitmap object able to handle bits between 0 and iSize,
  32499. ** inclusive. Return a pointer to the new object. Return NULL if
  32500. ** malloc fails.
  32501. */
  32502. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  32503. Bitvec *p;
  32504. assert( sizeof(*p)==BITVEC_SZ );
  32505. p = sqlite3MallocZero( sizeof(*p) );
  32506. if( p ){
  32507. p->iSize = iSize;
  32508. }
  32509. return p;
  32510. }
  32511. /*
  32512. ** Check to see if the i-th bit is set. Return true or false.
  32513. ** If p is NULL (if the bitmap has not been created) or if
  32514. ** i is out of range, then return false.
  32515. */
  32516. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  32517. if( p==0 ) return 0;
  32518. if( i>p->iSize || i==0 ) return 0;
  32519. i--;
  32520. while( p->iDivisor ){
  32521. u32 bin = i/p->iDivisor;
  32522. i = i%p->iDivisor;
  32523. p = p->u.apSub[bin];
  32524. if (!p) {
  32525. return 0;
  32526. }
  32527. }
  32528. if( p->iSize<=BITVEC_NBIT ){
  32529. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  32530. } else{
  32531. u32 h = BITVEC_HASH(i++);
  32532. while( p->u.aHash[h] ){
  32533. if( p->u.aHash[h]==i ) return 1;
  32534. h = (h+1) % BITVEC_NINT;
  32535. }
  32536. return 0;
  32537. }
  32538. }
  32539. /*
  32540. ** Set the i-th bit. Return 0 on success and an error code if
  32541. ** anything goes wrong.
  32542. **
  32543. ** This routine might cause sub-bitmaps to be allocated. Failing
  32544. ** to get the memory needed to hold the sub-bitmap is the only
  32545. ** that can go wrong with an insert, assuming p and i are valid.
  32546. **
  32547. ** The calling function must ensure that p is a valid Bitvec object
  32548. ** and that the value for "i" is within range of the Bitvec object.
  32549. ** Otherwise the behavior is undefined.
  32550. */
  32551. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  32552. u32 h;
  32553. if( p==0 ) return SQLITE_OK;
  32554. assert( i>0 );
  32555. assert( i<=p->iSize );
  32556. i--;
  32557. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  32558. u32 bin = i/p->iDivisor;
  32559. i = i%p->iDivisor;
  32560. if( p->u.apSub[bin]==0 ){
  32561. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  32562. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  32563. }
  32564. p = p->u.apSub[bin];
  32565. }
  32566. if( p->iSize<=BITVEC_NBIT ){
  32567. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  32568. return SQLITE_OK;
  32569. }
  32570. h = BITVEC_HASH(i++);
  32571. /* if there wasn't a hash collision, and this doesn't */
  32572. /* completely fill the hash, then just add it without */
  32573. /* worring about sub-dividing and re-hashing. */
  32574. if( !p->u.aHash[h] ){
  32575. if (p->nSet<(BITVEC_NINT-1)) {
  32576. goto bitvec_set_end;
  32577. } else {
  32578. goto bitvec_set_rehash;
  32579. }
  32580. }
  32581. /* there was a collision, check to see if it's already */
  32582. /* in hash, if not, try to find a spot for it */
  32583. do {
  32584. if( p->u.aHash[h]==i ) return SQLITE_OK;
  32585. h++;
  32586. if( h>=BITVEC_NINT ) h = 0;
  32587. } while( p->u.aHash[h] );
  32588. /* we didn't find it in the hash. h points to the first */
  32589. /* available free spot. check to see if this is going to */
  32590. /* make our hash too "full". */
  32591. bitvec_set_rehash:
  32592. if( p->nSet>=BITVEC_MXHASH ){
  32593. unsigned int j;
  32594. int rc;
  32595. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  32596. if( aiValues==0 ){
  32597. return SQLITE_NOMEM;
  32598. }else{
  32599. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  32600. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  32601. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  32602. rc = sqlite3BitvecSet(p, i);
  32603. for(j=0; j<BITVEC_NINT; j++){
  32604. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  32605. }
  32606. sqlite3StackFree(0, aiValues);
  32607. return rc;
  32608. }
  32609. }
  32610. bitvec_set_end:
  32611. p->nSet++;
  32612. p->u.aHash[h] = i;
  32613. return SQLITE_OK;
  32614. }
  32615. /*
  32616. ** Clear the i-th bit.
  32617. **
  32618. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  32619. ** that BitvecClear can use to rebuilt its hash table.
  32620. */
  32621. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  32622. if( p==0 ) return;
  32623. assert( i>0 );
  32624. i--;
  32625. while( p->iDivisor ){
  32626. u32 bin = i/p->iDivisor;
  32627. i = i%p->iDivisor;
  32628. p = p->u.apSub[bin];
  32629. if (!p) {
  32630. return;
  32631. }
  32632. }
  32633. if( p->iSize<=BITVEC_NBIT ){
  32634. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  32635. }else{
  32636. unsigned int j;
  32637. u32 *aiValues = pBuf;
  32638. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  32639. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  32640. p->nSet = 0;
  32641. for(j=0; j<BITVEC_NINT; j++){
  32642. if( aiValues[j] && aiValues[j]!=(i+1) ){
  32643. u32 h = BITVEC_HASH(aiValues[j]-1);
  32644. p->nSet++;
  32645. while( p->u.aHash[h] ){
  32646. h++;
  32647. if( h>=BITVEC_NINT ) h = 0;
  32648. }
  32649. p->u.aHash[h] = aiValues[j];
  32650. }
  32651. }
  32652. }
  32653. }
  32654. /*
  32655. ** Destroy a bitmap object. Reclaim all memory used.
  32656. */
  32657. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  32658. if( p==0 ) return;
  32659. if( p->iDivisor ){
  32660. unsigned int i;
  32661. for(i=0; i<BITVEC_NPTR; i++){
  32662. sqlite3BitvecDestroy(p->u.apSub[i]);
  32663. }
  32664. }
  32665. sqlite3_free(p);
  32666. }
  32667. /*
  32668. ** Return the value of the iSize parameter specified when Bitvec *p
  32669. ** was created.
  32670. */
  32671. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  32672. return p->iSize;
  32673. }
  32674. #ifndef SQLITE_OMIT_BUILTIN_TEST
  32675. /*
  32676. ** Let V[] be an array of unsigned characters sufficient to hold
  32677. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  32678. ** Then the following macros can be used to set, clear, or test
  32679. ** individual bits within V.
  32680. */
  32681. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  32682. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  32683. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  32684. /*
  32685. ** This routine runs an extensive test of the Bitvec code.
  32686. **
  32687. ** The input is an array of integers that acts as a program
  32688. ** to test the Bitvec. The integers are opcodes followed
  32689. ** by 0, 1, or 3 operands, depending on the opcode. Another
  32690. ** opcode follows immediately after the last operand.
  32691. **
  32692. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  32693. ** "halt" opcode and causes the test to end.
  32694. **
  32695. ** 0 Halt and return the number of errors
  32696. ** 1 N S X Set N bits beginning with S and incrementing by X
  32697. ** 2 N S X Clear N bits beginning with S and incrementing by X
  32698. ** 3 N Set N randomly chosen bits
  32699. ** 4 N Clear N randomly chosen bits
  32700. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  32701. **
  32702. ** The opcodes 1 through 4 perform set and clear operations are performed
  32703. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  32704. ** Opcode 5 works on the linear array only, not on the Bitvec.
  32705. ** Opcode 5 is used to deliberately induce a fault in order to
  32706. ** confirm that error detection works.
  32707. **
  32708. ** At the conclusion of the test the linear array is compared
  32709. ** against the Bitvec object. If there are any differences,
  32710. ** an error is returned. If they are the same, zero is returned.
  32711. **
  32712. ** If a memory allocation error occurs, return -1.
  32713. */
  32714. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  32715. Bitvec *pBitvec = 0;
  32716. unsigned char *pV = 0;
  32717. int rc = -1;
  32718. int i, nx, pc, op;
  32719. void *pTmpSpace;
  32720. /* Allocate the Bitvec to be tested and a linear array of
  32721. ** bits to act as the reference */
  32722. pBitvec = sqlite3BitvecCreate( sz );
  32723. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  32724. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  32725. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  32726. /* NULL pBitvec tests */
  32727. sqlite3BitvecSet(0, 1);
  32728. sqlite3BitvecClear(0, 1, pTmpSpace);
  32729. /* Run the program */
  32730. pc = 0;
  32731. while( (op = aOp[pc])!=0 ){
  32732. switch( op ){
  32733. case 1:
  32734. case 2:
  32735. case 5: {
  32736. nx = 4;
  32737. i = aOp[pc+2] - 1;
  32738. aOp[pc+2] += aOp[pc+3];
  32739. break;
  32740. }
  32741. case 3:
  32742. case 4:
  32743. default: {
  32744. nx = 2;
  32745. sqlite3_randomness(sizeof(i), &i);
  32746. break;
  32747. }
  32748. }
  32749. if( (--aOp[pc+1]) > 0 ) nx = 0;
  32750. pc += nx;
  32751. i = (i & 0x7fffffff)%sz;
  32752. if( (op & 1)!=0 ){
  32753. SETBIT(pV, (i+1));
  32754. if( op!=5 ){
  32755. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  32756. }
  32757. }else{
  32758. CLEARBIT(pV, (i+1));
  32759. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  32760. }
  32761. }
  32762. /* Test to make sure the linear array exactly matches the
  32763. ** Bitvec object. Start with the assumption that they do
  32764. ** match (rc==0). Change rc to non-zero if a discrepancy
  32765. ** is found.
  32766. */
  32767. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  32768. + sqlite3BitvecTest(pBitvec, 0)
  32769. + (sqlite3BitvecSize(pBitvec) - sz);
  32770. for(i=1; i<=sz; i++){
  32771. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  32772. rc = i;
  32773. break;
  32774. }
  32775. }
  32776. /* Free allocated structure */
  32777. bitvec_end:
  32778. sqlite3_free(pTmpSpace);
  32779. sqlite3_free(pV);
  32780. sqlite3BitvecDestroy(pBitvec);
  32781. return rc;
  32782. }
  32783. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  32784. /************** End of bitvec.c **********************************************/
  32785. /************** Begin file pcache.c ******************************************/
  32786. /*
  32787. ** 2008 August 05
  32788. **
  32789. ** The author disclaims copyright to this source code. In place of
  32790. ** a legal notice, here is a blessing:
  32791. **
  32792. ** May you do good and not evil.
  32793. ** May you find forgiveness for yourself and forgive others.
  32794. ** May you share freely, never taking more than you give.
  32795. **
  32796. *************************************************************************
  32797. ** This file implements that page cache.
  32798. */
  32799. /*
  32800. ** A complete page cache is an instance of this structure.
  32801. */
  32802. struct PCache {
  32803. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  32804. PgHdr *pSynced; /* Last synced page in dirty page list */
  32805. int nRef; /* Number of referenced pages */
  32806. int szCache; /* Configured cache size */
  32807. int szPage; /* Size of every page in this cache */
  32808. int szExtra; /* Size of extra space for each page */
  32809. int bPurgeable; /* True if pages are on backing store */
  32810. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  32811. void *pStress; /* Argument to xStress */
  32812. sqlite3_pcache *pCache; /* Pluggable cache module */
  32813. PgHdr *pPage1; /* Reference to page 1 */
  32814. };
  32815. /*
  32816. ** Some of the assert() macros in this code are too expensive to run
  32817. ** even during normal debugging. Use them only rarely on long-running
  32818. ** tests. Enable the expensive asserts using the
  32819. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  32820. */
  32821. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  32822. # define expensive_assert(X) assert(X)
  32823. #else
  32824. # define expensive_assert(X)
  32825. #endif
  32826. /********************************** Linked List Management ********************/
  32827. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  32828. /*
  32829. ** Check that the pCache->pSynced variable is set correctly. If it
  32830. ** is not, either fail an assert or return zero. Otherwise, return
  32831. ** non-zero. This is only used in debugging builds, as follows:
  32832. **
  32833. ** expensive_assert( pcacheCheckSynced(pCache) );
  32834. */
  32835. static int pcacheCheckSynced(PCache *pCache){
  32836. PgHdr *p;
  32837. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  32838. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  32839. }
  32840. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  32841. }
  32842. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  32843. /*
  32844. ** Remove page pPage from the list of dirty pages.
  32845. */
  32846. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  32847. PCache *p = pPage->pCache;
  32848. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  32849. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  32850. /* Update the PCache1.pSynced variable if necessary. */
  32851. if( p->pSynced==pPage ){
  32852. PgHdr *pSynced = pPage->pDirtyPrev;
  32853. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  32854. pSynced = pSynced->pDirtyPrev;
  32855. }
  32856. p->pSynced = pSynced;
  32857. }
  32858. if( pPage->pDirtyNext ){
  32859. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  32860. }else{
  32861. assert( pPage==p->pDirtyTail );
  32862. p->pDirtyTail = pPage->pDirtyPrev;
  32863. }
  32864. if( pPage->pDirtyPrev ){
  32865. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  32866. }else{
  32867. assert( pPage==p->pDirty );
  32868. p->pDirty = pPage->pDirtyNext;
  32869. }
  32870. pPage->pDirtyNext = 0;
  32871. pPage->pDirtyPrev = 0;
  32872. expensive_assert( pcacheCheckSynced(p) );
  32873. }
  32874. /*
  32875. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  32876. ** pPage).
  32877. */
  32878. static void pcacheAddToDirtyList(PgHdr *pPage){
  32879. PCache *p = pPage->pCache;
  32880. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  32881. pPage->pDirtyNext = p->pDirty;
  32882. if( pPage->pDirtyNext ){
  32883. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  32884. pPage->pDirtyNext->pDirtyPrev = pPage;
  32885. }
  32886. p->pDirty = pPage;
  32887. if( !p->pDirtyTail ){
  32888. p->pDirtyTail = pPage;
  32889. }
  32890. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  32891. p->pSynced = pPage;
  32892. }
  32893. expensive_assert( pcacheCheckSynced(p) );
  32894. }
  32895. /*
  32896. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  32897. ** being used for an in-memory database, this function is a no-op.
  32898. */
  32899. static void pcacheUnpin(PgHdr *p){
  32900. PCache *pCache = p->pCache;
  32901. if( pCache->bPurgeable ){
  32902. if( p->pgno==1 ){
  32903. pCache->pPage1 = 0;
  32904. }
  32905. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  32906. }
  32907. }
  32908. /*************************************************** General Interfaces ******
  32909. **
  32910. ** Initialize and shutdown the page cache subsystem. Neither of these
  32911. ** functions are threadsafe.
  32912. */
  32913. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  32914. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  32915. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  32916. ** built-in default page cache is used instead of the application defined
  32917. ** page cache. */
  32918. sqlite3PCacheSetDefault();
  32919. }
  32920. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  32921. }
  32922. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  32923. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  32924. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  32925. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  32926. }
  32927. }
  32928. /*
  32929. ** Return the size in bytes of a PCache object.
  32930. */
  32931. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  32932. /*
  32933. ** Create a new PCache object. Storage space to hold the object
  32934. ** has already been allocated and is passed in as the p pointer.
  32935. ** The caller discovers how much space needs to be allocated by
  32936. ** calling sqlite3PcacheSize().
  32937. */
  32938. SQLITE_PRIVATE void sqlite3PcacheOpen(
  32939. int szPage, /* Size of every page */
  32940. int szExtra, /* Extra space associated with each page */
  32941. int bPurgeable, /* True if pages are on backing store */
  32942. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  32943. void *pStress, /* Argument to xStress */
  32944. PCache *p /* Preallocated space for the PCache */
  32945. ){
  32946. memset(p, 0, sizeof(PCache));
  32947. p->szPage = szPage;
  32948. p->szExtra = szExtra;
  32949. p->bPurgeable = bPurgeable;
  32950. p->xStress = xStress;
  32951. p->pStress = pStress;
  32952. p->szCache = 100;
  32953. }
  32954. /*
  32955. ** Change the page size for PCache object. The caller must ensure that there
  32956. ** are no outstanding page references when this function is called.
  32957. */
  32958. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  32959. assert( pCache->nRef==0 && pCache->pDirty==0 );
  32960. if( pCache->pCache ){
  32961. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  32962. pCache->pCache = 0;
  32963. pCache->pPage1 = 0;
  32964. }
  32965. pCache->szPage = szPage;
  32966. }
  32967. /*
  32968. ** Compute the number of pages of cache requested.
  32969. */
  32970. static int numberOfCachePages(PCache *p){
  32971. if( p->szCache>=0 ){
  32972. return p->szCache;
  32973. }else{
  32974. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  32975. }
  32976. }
  32977. /*
  32978. ** Try to obtain a page from the cache.
  32979. */
  32980. SQLITE_PRIVATE int sqlite3PcacheFetch(
  32981. PCache *pCache, /* Obtain the page from this cache */
  32982. Pgno pgno, /* Page number to obtain */
  32983. int createFlag, /* If true, create page if it does not exist already */
  32984. PgHdr **ppPage /* Write the page here */
  32985. ){
  32986. sqlite3_pcache_page *pPage = 0;
  32987. PgHdr *pPgHdr = 0;
  32988. int eCreate;
  32989. assert( pCache!=0 );
  32990. assert( createFlag==1 || createFlag==0 );
  32991. assert( pgno>0 );
  32992. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  32993. ** allocate it now.
  32994. */
  32995. if( !pCache->pCache && createFlag ){
  32996. sqlite3_pcache *p;
  32997. p = sqlite3GlobalConfig.pcache2.xCreate(
  32998. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  32999. );
  33000. if( !p ){
  33001. return SQLITE_NOMEM;
  33002. }
  33003. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  33004. pCache->pCache = p;
  33005. }
  33006. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  33007. if( pCache->pCache ){
  33008. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  33009. }
  33010. if( !pPage && eCreate==1 ){
  33011. PgHdr *pPg;
  33012. /* Find a dirty page to write-out and recycle. First try to find a
  33013. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  33014. ** cleared), but if that is not possible settle for any other
  33015. ** unreferenced dirty page.
  33016. */
  33017. expensive_assert( pcacheCheckSynced(pCache) );
  33018. for(pPg=pCache->pSynced;
  33019. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  33020. pPg=pPg->pDirtyPrev
  33021. );
  33022. pCache->pSynced = pPg;
  33023. if( !pPg ){
  33024. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  33025. }
  33026. if( pPg ){
  33027. int rc;
  33028. #ifdef SQLITE_LOG_CACHE_SPILL
  33029. sqlite3_log(SQLITE_FULL,
  33030. "spill page %d making room for %d - cache used: %d/%d",
  33031. pPg->pgno, pgno,
  33032. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  33033. numberOfCachePages(pCache));
  33034. #endif
  33035. rc = pCache->xStress(pCache->pStress, pPg);
  33036. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  33037. return rc;
  33038. }
  33039. }
  33040. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  33041. }
  33042. if( pPage ){
  33043. pPgHdr = (PgHdr *)pPage->pExtra;
  33044. if( !pPgHdr->pPage ){
  33045. memset(pPgHdr, 0, sizeof(PgHdr));
  33046. pPgHdr->pPage = pPage;
  33047. pPgHdr->pData = pPage->pBuf;
  33048. pPgHdr->pExtra = (void *)&pPgHdr[1];
  33049. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  33050. pPgHdr->pCache = pCache;
  33051. pPgHdr->pgno = pgno;
  33052. }
  33053. assert( pPgHdr->pCache==pCache );
  33054. assert( pPgHdr->pgno==pgno );
  33055. assert( pPgHdr->pData==pPage->pBuf );
  33056. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  33057. if( 0==pPgHdr->nRef ){
  33058. pCache->nRef++;
  33059. }
  33060. pPgHdr->nRef++;
  33061. if( pgno==1 ){
  33062. pCache->pPage1 = pPgHdr;
  33063. }
  33064. }
  33065. *ppPage = pPgHdr;
  33066. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  33067. }
  33068. /*
  33069. ** Decrement the reference count on a page. If the page is clean and the
  33070. ** reference count drops to 0, then it is made elible for recycling.
  33071. */
  33072. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  33073. assert( p->nRef>0 );
  33074. p->nRef--;
  33075. if( p->nRef==0 ){
  33076. PCache *pCache = p->pCache;
  33077. pCache->nRef--;
  33078. if( (p->flags&PGHDR_DIRTY)==0 ){
  33079. pcacheUnpin(p);
  33080. }else{
  33081. /* Move the page to the head of the dirty list. */
  33082. pcacheRemoveFromDirtyList(p);
  33083. pcacheAddToDirtyList(p);
  33084. }
  33085. }
  33086. }
  33087. /*
  33088. ** Increase the reference count of a supplied page by 1.
  33089. */
  33090. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  33091. assert(p->nRef>0);
  33092. p->nRef++;
  33093. }
  33094. /*
  33095. ** Drop a page from the cache. There must be exactly one reference to the
  33096. ** page. This function deletes that reference, so after it returns the
  33097. ** page pointed to by p is invalid.
  33098. */
  33099. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  33100. PCache *pCache;
  33101. assert( p->nRef==1 );
  33102. if( p->flags&PGHDR_DIRTY ){
  33103. pcacheRemoveFromDirtyList(p);
  33104. }
  33105. pCache = p->pCache;
  33106. pCache->nRef--;
  33107. if( p->pgno==1 ){
  33108. pCache->pPage1 = 0;
  33109. }
  33110. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  33111. }
  33112. /*
  33113. ** Make sure the page is marked as dirty. If it isn't dirty already,
  33114. ** make it so.
  33115. */
  33116. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  33117. p->flags &= ~PGHDR_DONT_WRITE;
  33118. assert( p->nRef>0 );
  33119. if( 0==(p->flags & PGHDR_DIRTY) ){
  33120. p->flags |= PGHDR_DIRTY;
  33121. pcacheAddToDirtyList( p);
  33122. }
  33123. }
  33124. /*
  33125. ** Make sure the page is marked as clean. If it isn't clean already,
  33126. ** make it so.
  33127. */
  33128. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  33129. if( (p->flags & PGHDR_DIRTY) ){
  33130. pcacheRemoveFromDirtyList(p);
  33131. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  33132. if( p->nRef==0 ){
  33133. pcacheUnpin(p);
  33134. }
  33135. }
  33136. }
  33137. /*
  33138. ** Make every page in the cache clean.
  33139. */
  33140. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  33141. PgHdr *p;
  33142. while( (p = pCache->pDirty)!=0 ){
  33143. sqlite3PcacheMakeClean(p);
  33144. }
  33145. }
  33146. /*
  33147. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  33148. */
  33149. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  33150. PgHdr *p;
  33151. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  33152. p->flags &= ~PGHDR_NEED_SYNC;
  33153. }
  33154. pCache->pSynced = pCache->pDirtyTail;
  33155. }
  33156. /*
  33157. ** Change the page number of page p to newPgno.
  33158. */
  33159. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  33160. PCache *pCache = p->pCache;
  33161. assert( p->nRef>0 );
  33162. assert( newPgno>0 );
  33163. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  33164. p->pgno = newPgno;
  33165. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  33166. pcacheRemoveFromDirtyList(p);
  33167. pcacheAddToDirtyList(p);
  33168. }
  33169. }
  33170. /*
  33171. ** Drop every cache entry whose page number is greater than "pgno". The
  33172. ** caller must ensure that there are no outstanding references to any pages
  33173. ** other than page 1 with a page number greater than pgno.
  33174. **
  33175. ** If there is a reference to page 1 and the pgno parameter passed to this
  33176. ** function is 0, then the data area associated with page 1 is zeroed, but
  33177. ** the page object is not dropped.
  33178. */
  33179. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  33180. if( pCache->pCache ){
  33181. PgHdr *p;
  33182. PgHdr *pNext;
  33183. for(p=pCache->pDirty; p; p=pNext){
  33184. pNext = p->pDirtyNext;
  33185. /* This routine never gets call with a positive pgno except right
  33186. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  33187. ** it must be that pgno==0.
  33188. */
  33189. assert( p->pgno>0 );
  33190. if( ALWAYS(p->pgno>pgno) ){
  33191. assert( p->flags&PGHDR_DIRTY );
  33192. sqlite3PcacheMakeClean(p);
  33193. }
  33194. }
  33195. if( pgno==0 && pCache->pPage1 ){
  33196. memset(pCache->pPage1->pData, 0, pCache->szPage);
  33197. pgno = 1;
  33198. }
  33199. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  33200. }
  33201. }
  33202. /*
  33203. ** Close a cache.
  33204. */
  33205. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  33206. if( pCache->pCache ){
  33207. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  33208. }
  33209. }
  33210. /*
  33211. ** Discard the contents of the cache.
  33212. */
  33213. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  33214. sqlite3PcacheTruncate(pCache, 0);
  33215. }
  33216. /*
  33217. ** Merge two lists of pages connected by pDirty and in pgno order.
  33218. ** Do not both fixing the pDirtyPrev pointers.
  33219. */
  33220. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  33221. PgHdr result, *pTail;
  33222. pTail = &result;
  33223. while( pA && pB ){
  33224. if( pA->pgno<pB->pgno ){
  33225. pTail->pDirty = pA;
  33226. pTail = pA;
  33227. pA = pA->pDirty;
  33228. }else{
  33229. pTail->pDirty = pB;
  33230. pTail = pB;
  33231. pB = pB->pDirty;
  33232. }
  33233. }
  33234. if( pA ){
  33235. pTail->pDirty = pA;
  33236. }else if( pB ){
  33237. pTail->pDirty = pB;
  33238. }else{
  33239. pTail->pDirty = 0;
  33240. }
  33241. return result.pDirty;
  33242. }
  33243. /*
  33244. ** Sort the list of pages in accending order by pgno. Pages are
  33245. ** connected by pDirty pointers. The pDirtyPrev pointers are
  33246. ** corrupted by this sort.
  33247. **
  33248. ** Since there cannot be more than 2^31 distinct pages in a database,
  33249. ** there cannot be more than 31 buckets required by the merge sorter.
  33250. ** One extra bucket is added to catch overflow in case something
  33251. ** ever changes to make the previous sentence incorrect.
  33252. */
  33253. #define N_SORT_BUCKET 32
  33254. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  33255. PgHdr *a[N_SORT_BUCKET], *p;
  33256. int i;
  33257. memset(a, 0, sizeof(a));
  33258. while( pIn ){
  33259. p = pIn;
  33260. pIn = p->pDirty;
  33261. p->pDirty = 0;
  33262. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  33263. if( a[i]==0 ){
  33264. a[i] = p;
  33265. break;
  33266. }else{
  33267. p = pcacheMergeDirtyList(a[i], p);
  33268. a[i] = 0;
  33269. }
  33270. }
  33271. if( NEVER(i==N_SORT_BUCKET-1) ){
  33272. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  33273. ** the input list. But that is impossible.
  33274. */
  33275. a[i] = pcacheMergeDirtyList(a[i], p);
  33276. }
  33277. }
  33278. p = a[0];
  33279. for(i=1; i<N_SORT_BUCKET; i++){
  33280. p = pcacheMergeDirtyList(p, a[i]);
  33281. }
  33282. return p;
  33283. }
  33284. /*
  33285. ** Return a list of all dirty pages in the cache, sorted by page number.
  33286. */
  33287. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  33288. PgHdr *p;
  33289. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  33290. p->pDirty = p->pDirtyNext;
  33291. }
  33292. return pcacheSortDirtyList(pCache->pDirty);
  33293. }
  33294. /*
  33295. ** Return the total number of referenced pages held by the cache.
  33296. */
  33297. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  33298. return pCache->nRef;
  33299. }
  33300. /*
  33301. ** Return the number of references to the page supplied as an argument.
  33302. */
  33303. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  33304. return p->nRef;
  33305. }
  33306. /*
  33307. ** Return the total number of pages in the cache.
  33308. */
  33309. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  33310. int nPage = 0;
  33311. if( pCache->pCache ){
  33312. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  33313. }
  33314. return nPage;
  33315. }
  33316. #ifdef SQLITE_TEST
  33317. /*
  33318. ** Get the suggested cache-size value.
  33319. */
  33320. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  33321. return numberOfCachePages(pCache);
  33322. }
  33323. #endif
  33324. /*
  33325. ** Set the suggested cache-size value.
  33326. */
  33327. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  33328. pCache->szCache = mxPage;
  33329. if( pCache->pCache ){
  33330. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  33331. numberOfCachePages(pCache));
  33332. }
  33333. }
  33334. /*
  33335. ** Free up as much memory as possible from the page cache.
  33336. */
  33337. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  33338. if( pCache->pCache ){
  33339. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  33340. }
  33341. }
  33342. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  33343. /*
  33344. ** For all dirty pages currently in the cache, invoke the specified
  33345. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  33346. ** defined.
  33347. */
  33348. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  33349. PgHdr *pDirty;
  33350. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  33351. xIter(pDirty);
  33352. }
  33353. }
  33354. #endif
  33355. /************** End of pcache.c **********************************************/
  33356. /************** Begin file pcache1.c *****************************************/
  33357. /*
  33358. ** 2008 November 05
  33359. **
  33360. ** The author disclaims copyright to this source code. In place of
  33361. ** a legal notice, here is a blessing:
  33362. **
  33363. ** May you do good and not evil.
  33364. ** May you find forgiveness for yourself and forgive others.
  33365. ** May you share freely, never taking more than you give.
  33366. **
  33367. *************************************************************************
  33368. **
  33369. ** This file implements the default page cache implementation (the
  33370. ** sqlite3_pcache interface). It also contains part of the implementation
  33371. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  33372. ** If the default page cache implementation is overriden, then neither of
  33373. ** these two features are available.
  33374. */
  33375. typedef struct PCache1 PCache1;
  33376. typedef struct PgHdr1 PgHdr1;
  33377. typedef struct PgFreeslot PgFreeslot;
  33378. typedef struct PGroup PGroup;
  33379. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  33380. ** of one or more PCaches that are able to recycle each others unpinned
  33381. ** pages when they are under memory pressure. A PGroup is an instance of
  33382. ** the following object.
  33383. **
  33384. ** This page cache implementation works in one of two modes:
  33385. **
  33386. ** (1) Every PCache is the sole member of its own PGroup. There is
  33387. ** one PGroup per PCache.
  33388. **
  33389. ** (2) There is a single global PGroup that all PCaches are a member
  33390. ** of.
  33391. **
  33392. ** Mode 1 uses more memory (since PCache instances are not able to rob
  33393. ** unused pages from other PCaches) but it also operates without a mutex,
  33394. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  33395. ** threadsafe, but recycles pages more efficiently.
  33396. **
  33397. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  33398. ** PGroup which is the pcache1.grp global variable and its mutex is
  33399. ** SQLITE_MUTEX_STATIC_LRU.
  33400. */
  33401. struct PGroup {
  33402. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  33403. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  33404. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  33405. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  33406. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  33407. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  33408. };
  33409. /* Each page cache is an instance of the following object. Every
  33410. ** open database file (including each in-memory database and each
  33411. ** temporary or transient database) has a single page cache which
  33412. ** is an instance of this object.
  33413. **
  33414. ** Pointers to structures of this type are cast and returned as
  33415. ** opaque sqlite3_pcache* handles.
  33416. */
  33417. struct PCache1 {
  33418. /* Cache configuration parameters. Page size (szPage) and the purgeable
  33419. ** flag (bPurgeable) are set when the cache is created. nMax may be
  33420. ** modified at any time by a call to the pcache1Cachesize() method.
  33421. ** The PGroup mutex must be held when accessing nMax.
  33422. */
  33423. PGroup *pGroup; /* PGroup this cache belongs to */
  33424. int szPage; /* Size of allocated pages in bytes */
  33425. int szExtra; /* Size of extra space in bytes */
  33426. int bPurgeable; /* True if cache is purgeable */
  33427. unsigned int nMin; /* Minimum number of pages reserved */
  33428. unsigned int nMax; /* Configured "cache_size" value */
  33429. unsigned int n90pct; /* nMax*9/10 */
  33430. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  33431. /* Hash table of all pages. The following variables may only be accessed
  33432. ** when the accessor is holding the PGroup mutex.
  33433. */
  33434. unsigned int nRecyclable; /* Number of pages in the LRU list */
  33435. unsigned int nPage; /* Total number of pages in apHash */
  33436. unsigned int nHash; /* Number of slots in apHash[] */
  33437. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  33438. };
  33439. /*
  33440. ** Each cache entry is represented by an instance of the following
  33441. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  33442. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  33443. ** in memory.
  33444. */
  33445. struct PgHdr1 {
  33446. sqlite3_pcache_page page;
  33447. unsigned int iKey; /* Key value (page number) */
  33448. PgHdr1 *pNext; /* Next in hash table chain */
  33449. PCache1 *pCache; /* Cache that currently owns this page */
  33450. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  33451. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  33452. };
  33453. /*
  33454. ** Free slots in the allocator used to divide up the buffer provided using
  33455. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  33456. */
  33457. struct PgFreeslot {
  33458. PgFreeslot *pNext; /* Next free slot */
  33459. };
  33460. /*
  33461. ** Global data used by this cache.
  33462. */
  33463. static SQLITE_WSD struct PCacheGlobal {
  33464. PGroup grp; /* The global PGroup for mode (2) */
  33465. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  33466. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  33467. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  33468. ** The nFreeSlot and pFree values do require mutex protection.
  33469. */
  33470. int isInit; /* True if initialized */
  33471. int szSlot; /* Size of each free slot */
  33472. int nSlot; /* The number of pcache slots */
  33473. int nReserve; /* Try to keep nFreeSlot above this */
  33474. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  33475. /* Above requires no mutex. Use mutex below for variable that follow. */
  33476. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  33477. PgFreeslot *pFree; /* Free page blocks */
  33478. int nFreeSlot; /* Number of unused pcache slots */
  33479. /* The following value requires a mutex to change. We skip the mutex on
  33480. ** reading because (1) most platforms read a 32-bit integer atomically and
  33481. ** (2) even if an incorrect value is read, no great harm is done since this
  33482. ** is really just an optimization. */
  33483. int bUnderPressure; /* True if low on PAGECACHE memory */
  33484. } pcache1_g;
  33485. /*
  33486. ** All code in this file should access the global structure above via the
  33487. ** alias "pcache1". This ensures that the WSD emulation is used when
  33488. ** compiling for systems that do not support real WSD.
  33489. */
  33490. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  33491. /*
  33492. ** Macros to enter and leave the PCache LRU mutex.
  33493. */
  33494. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  33495. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  33496. /******************************************************************************/
  33497. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  33498. /*
  33499. ** This function is called during initialization if a static buffer is
  33500. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  33501. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  33502. ** enough to contain 'n' buffers of 'sz' bytes each.
  33503. **
  33504. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  33505. ** to be serialized already. There is no need for further mutexing.
  33506. */
  33507. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  33508. if( pcache1.isInit ){
  33509. PgFreeslot *p;
  33510. sz = ROUNDDOWN8(sz);
  33511. pcache1.szSlot = sz;
  33512. pcache1.nSlot = pcache1.nFreeSlot = n;
  33513. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  33514. pcache1.pStart = pBuf;
  33515. pcache1.pFree = 0;
  33516. pcache1.bUnderPressure = 0;
  33517. while( n-- ){
  33518. p = (PgFreeslot*)pBuf;
  33519. p->pNext = pcache1.pFree;
  33520. pcache1.pFree = p;
  33521. pBuf = (void*)&((char*)pBuf)[sz];
  33522. }
  33523. pcache1.pEnd = pBuf;
  33524. }
  33525. }
  33526. /*
  33527. ** Malloc function used within this file to allocate space from the buffer
  33528. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  33529. ** such buffer exists or there is no space left in it, this function falls
  33530. ** back to sqlite3Malloc().
  33531. **
  33532. ** Multiple threads can run this routine at the same time. Global variables
  33533. ** in pcache1 need to be protected via mutex.
  33534. */
  33535. static void *pcache1Alloc(int nByte){
  33536. void *p = 0;
  33537. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  33538. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  33539. if( nByte<=pcache1.szSlot ){
  33540. sqlite3_mutex_enter(pcache1.mutex);
  33541. p = (PgHdr1 *)pcache1.pFree;
  33542. if( p ){
  33543. pcache1.pFree = pcache1.pFree->pNext;
  33544. pcache1.nFreeSlot--;
  33545. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  33546. assert( pcache1.nFreeSlot>=0 );
  33547. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  33548. }
  33549. sqlite3_mutex_leave(pcache1.mutex);
  33550. }
  33551. if( p==0 ){
  33552. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  33553. ** it from sqlite3Malloc instead.
  33554. */
  33555. p = sqlite3Malloc(nByte);
  33556. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  33557. if( p ){
  33558. int sz = sqlite3MallocSize(p);
  33559. sqlite3_mutex_enter(pcache1.mutex);
  33560. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  33561. sqlite3_mutex_leave(pcache1.mutex);
  33562. }
  33563. #endif
  33564. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  33565. }
  33566. return p;
  33567. }
  33568. /*
  33569. ** Free an allocated buffer obtained from pcache1Alloc().
  33570. */
  33571. static int pcache1Free(void *p){
  33572. int nFreed = 0;
  33573. if( p==0 ) return 0;
  33574. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  33575. PgFreeslot *pSlot;
  33576. sqlite3_mutex_enter(pcache1.mutex);
  33577. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  33578. pSlot = (PgFreeslot*)p;
  33579. pSlot->pNext = pcache1.pFree;
  33580. pcache1.pFree = pSlot;
  33581. pcache1.nFreeSlot++;
  33582. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  33583. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  33584. sqlite3_mutex_leave(pcache1.mutex);
  33585. }else{
  33586. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  33587. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  33588. nFreed = sqlite3MallocSize(p);
  33589. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  33590. sqlite3_mutex_enter(pcache1.mutex);
  33591. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  33592. sqlite3_mutex_leave(pcache1.mutex);
  33593. #endif
  33594. sqlite3_free(p);
  33595. }
  33596. return nFreed;
  33597. }
  33598. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  33599. /*
  33600. ** Return the size of a pcache allocation
  33601. */
  33602. static int pcache1MemSize(void *p){
  33603. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  33604. return pcache1.szSlot;
  33605. }else{
  33606. int iSize;
  33607. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  33608. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  33609. iSize = sqlite3MallocSize(p);
  33610. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  33611. return iSize;
  33612. }
  33613. }
  33614. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  33615. /*
  33616. ** Allocate a new page object initially associated with cache pCache.
  33617. */
  33618. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  33619. PgHdr1 *p = 0;
  33620. void *pPg;
  33621. /* The group mutex must be released before pcache1Alloc() is called. This
  33622. ** is because it may call sqlite3_release_memory(), which assumes that
  33623. ** this mutex is not held. */
  33624. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  33625. pcache1LeaveMutex(pCache->pGroup);
  33626. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  33627. pPg = pcache1Alloc(pCache->szPage);
  33628. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  33629. if( !pPg || !p ){
  33630. pcache1Free(pPg);
  33631. sqlite3_free(p);
  33632. pPg = 0;
  33633. }
  33634. #else
  33635. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  33636. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  33637. #endif
  33638. pcache1EnterMutex(pCache->pGroup);
  33639. if( pPg ){
  33640. p->page.pBuf = pPg;
  33641. p->page.pExtra = &p[1];
  33642. if( pCache->bPurgeable ){
  33643. pCache->pGroup->nCurrentPage++;
  33644. }
  33645. return p;
  33646. }
  33647. return 0;
  33648. }
  33649. /*
  33650. ** Free a page object allocated by pcache1AllocPage().
  33651. **
  33652. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  33653. ** that the current implementation happens to never call this routine
  33654. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  33655. */
  33656. static void pcache1FreePage(PgHdr1 *p){
  33657. if( ALWAYS(p) ){
  33658. PCache1 *pCache = p->pCache;
  33659. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  33660. pcache1Free(p->page.pBuf);
  33661. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  33662. sqlite3_free(p);
  33663. #endif
  33664. if( pCache->bPurgeable ){
  33665. pCache->pGroup->nCurrentPage--;
  33666. }
  33667. }
  33668. }
  33669. /*
  33670. ** Malloc function used by SQLite to obtain space from the buffer configured
  33671. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  33672. ** exists, this function falls back to sqlite3Malloc().
  33673. */
  33674. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  33675. return pcache1Alloc(sz);
  33676. }
  33677. /*
  33678. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  33679. */
  33680. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  33681. pcache1Free(p);
  33682. }
  33683. /*
  33684. ** Return true if it desirable to avoid allocating a new page cache
  33685. ** entry.
  33686. **
  33687. ** If memory was allocated specifically to the page cache using
  33688. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  33689. ** it is desirable to avoid allocating a new page cache entry because
  33690. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  33691. ** for all page cache needs and we should not need to spill the
  33692. ** allocation onto the heap.
  33693. **
  33694. ** Or, the heap is used for all page cache memory but the heap is
  33695. ** under memory pressure, then again it is desirable to avoid
  33696. ** allocating a new page cache entry in order to avoid stressing
  33697. ** the heap even further.
  33698. */
  33699. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  33700. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  33701. return pcache1.bUnderPressure;
  33702. }else{
  33703. return sqlite3HeapNearlyFull();
  33704. }
  33705. }
  33706. /******************************************************************************/
  33707. /******** General Implementation Functions ************************************/
  33708. /*
  33709. ** This function is used to resize the hash table used by the cache passed
  33710. ** as the first argument.
  33711. **
  33712. ** The PCache mutex must be held when this function is called.
  33713. */
  33714. static int pcache1ResizeHash(PCache1 *p){
  33715. PgHdr1 **apNew;
  33716. unsigned int nNew;
  33717. unsigned int i;
  33718. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  33719. nNew = p->nHash*2;
  33720. if( nNew<256 ){
  33721. nNew = 256;
  33722. }
  33723. pcache1LeaveMutex(p->pGroup);
  33724. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  33725. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  33726. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  33727. pcache1EnterMutex(p->pGroup);
  33728. if( apNew ){
  33729. for(i=0; i<p->nHash; i++){
  33730. PgHdr1 *pPage;
  33731. PgHdr1 *pNext = p->apHash[i];
  33732. while( (pPage = pNext)!=0 ){
  33733. unsigned int h = pPage->iKey % nNew;
  33734. pNext = pPage->pNext;
  33735. pPage->pNext = apNew[h];
  33736. apNew[h] = pPage;
  33737. }
  33738. }
  33739. sqlite3_free(p->apHash);
  33740. p->apHash = apNew;
  33741. p->nHash = nNew;
  33742. }
  33743. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  33744. }
  33745. /*
  33746. ** This function is used internally to remove the page pPage from the
  33747. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  33748. ** LRU list, then this function is a no-op.
  33749. **
  33750. ** The PGroup mutex must be held when this function is called.
  33751. **
  33752. ** If pPage is NULL then this routine is a no-op.
  33753. */
  33754. static void pcache1PinPage(PgHdr1 *pPage){
  33755. PCache1 *pCache;
  33756. PGroup *pGroup;
  33757. if( pPage==0 ) return;
  33758. pCache = pPage->pCache;
  33759. pGroup = pCache->pGroup;
  33760. assert( sqlite3_mutex_held(pGroup->mutex) );
  33761. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  33762. if( pPage->pLruPrev ){
  33763. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  33764. }
  33765. if( pPage->pLruNext ){
  33766. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  33767. }
  33768. if( pGroup->pLruHead==pPage ){
  33769. pGroup->pLruHead = pPage->pLruNext;
  33770. }
  33771. if( pGroup->pLruTail==pPage ){
  33772. pGroup->pLruTail = pPage->pLruPrev;
  33773. }
  33774. pPage->pLruNext = 0;
  33775. pPage->pLruPrev = 0;
  33776. pPage->pCache->nRecyclable--;
  33777. }
  33778. }
  33779. /*
  33780. ** Remove the page supplied as an argument from the hash table
  33781. ** (PCache1.apHash structure) that it is currently stored in.
  33782. **
  33783. ** The PGroup mutex must be held when this function is called.
  33784. */
  33785. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  33786. unsigned int h;
  33787. PCache1 *pCache = pPage->pCache;
  33788. PgHdr1 **pp;
  33789. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  33790. h = pPage->iKey % pCache->nHash;
  33791. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  33792. *pp = (*pp)->pNext;
  33793. pCache->nPage--;
  33794. }
  33795. /*
  33796. ** If there are currently more than nMaxPage pages allocated, try
  33797. ** to recycle pages to reduce the number allocated to nMaxPage.
  33798. */
  33799. static void pcache1EnforceMaxPage(PGroup *pGroup){
  33800. assert( sqlite3_mutex_held(pGroup->mutex) );
  33801. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  33802. PgHdr1 *p = pGroup->pLruTail;
  33803. assert( p->pCache->pGroup==pGroup );
  33804. pcache1PinPage(p);
  33805. pcache1RemoveFromHash(p);
  33806. pcache1FreePage(p);
  33807. }
  33808. }
  33809. /*
  33810. ** Discard all pages from cache pCache with a page number (key value)
  33811. ** greater than or equal to iLimit. Any pinned pages that meet this
  33812. ** criteria are unpinned before they are discarded.
  33813. **
  33814. ** The PCache mutex must be held when this function is called.
  33815. */
  33816. static void pcache1TruncateUnsafe(
  33817. PCache1 *pCache, /* The cache to truncate */
  33818. unsigned int iLimit /* Drop pages with this pgno or larger */
  33819. ){
  33820. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  33821. unsigned int h;
  33822. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  33823. for(h=0; h<pCache->nHash; h++){
  33824. PgHdr1 **pp = &pCache->apHash[h];
  33825. PgHdr1 *pPage;
  33826. while( (pPage = *pp)!=0 ){
  33827. if( pPage->iKey>=iLimit ){
  33828. pCache->nPage--;
  33829. *pp = pPage->pNext;
  33830. pcache1PinPage(pPage);
  33831. pcache1FreePage(pPage);
  33832. }else{
  33833. pp = &pPage->pNext;
  33834. TESTONLY( nPage++; )
  33835. }
  33836. }
  33837. }
  33838. assert( pCache->nPage==nPage );
  33839. }
  33840. /******************************************************************************/
  33841. /******** sqlite3_pcache Methods **********************************************/
  33842. /*
  33843. ** Implementation of the sqlite3_pcache.xInit method.
  33844. */
  33845. static int pcache1Init(void *NotUsed){
  33846. UNUSED_PARAMETER(NotUsed);
  33847. assert( pcache1.isInit==0 );
  33848. memset(&pcache1, 0, sizeof(pcache1));
  33849. if( sqlite3GlobalConfig.bCoreMutex ){
  33850. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  33851. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  33852. }
  33853. pcache1.grp.mxPinned = 10;
  33854. pcache1.isInit = 1;
  33855. return SQLITE_OK;
  33856. }
  33857. /*
  33858. ** Implementation of the sqlite3_pcache.xShutdown method.
  33859. ** Note that the static mutex allocated in xInit does
  33860. ** not need to be freed.
  33861. */
  33862. static void pcache1Shutdown(void *NotUsed){
  33863. UNUSED_PARAMETER(NotUsed);
  33864. assert( pcache1.isInit!=0 );
  33865. memset(&pcache1, 0, sizeof(pcache1));
  33866. }
  33867. /*
  33868. ** Implementation of the sqlite3_pcache.xCreate method.
  33869. **
  33870. ** Allocate a new cache.
  33871. */
  33872. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  33873. PCache1 *pCache; /* The newly created page cache */
  33874. PGroup *pGroup; /* The group the new page cache will belong to */
  33875. int sz; /* Bytes of memory required to allocate the new cache */
  33876. /*
  33877. ** The seperateCache variable is true if each PCache has its own private
  33878. ** PGroup. In other words, separateCache is true for mode (1) where no
  33879. ** mutexing is required.
  33880. **
  33881. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  33882. **
  33883. ** * Always use a unified cache in single-threaded applications
  33884. **
  33885. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  33886. ** use separate caches (mode-1)
  33887. */
  33888. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  33889. const int separateCache = 0;
  33890. #else
  33891. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  33892. #endif
  33893. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  33894. assert( szExtra < 300 );
  33895. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  33896. pCache = (PCache1 *)sqlite3MallocZero(sz);
  33897. if( pCache ){
  33898. if( separateCache ){
  33899. pGroup = (PGroup*)&pCache[1];
  33900. pGroup->mxPinned = 10;
  33901. }else{
  33902. pGroup = &pcache1.grp;
  33903. }
  33904. pCache->pGroup = pGroup;
  33905. pCache->szPage = szPage;
  33906. pCache->szExtra = szExtra;
  33907. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  33908. if( bPurgeable ){
  33909. pCache->nMin = 10;
  33910. pcache1EnterMutex(pGroup);
  33911. pGroup->nMinPage += pCache->nMin;
  33912. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  33913. pcache1LeaveMutex(pGroup);
  33914. }
  33915. }
  33916. return (sqlite3_pcache *)pCache;
  33917. }
  33918. /*
  33919. ** Implementation of the sqlite3_pcache.xCachesize method.
  33920. **
  33921. ** Configure the cache_size limit for a cache.
  33922. */
  33923. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  33924. PCache1 *pCache = (PCache1 *)p;
  33925. if( pCache->bPurgeable ){
  33926. PGroup *pGroup = pCache->pGroup;
  33927. pcache1EnterMutex(pGroup);
  33928. pGroup->nMaxPage += (nMax - pCache->nMax);
  33929. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  33930. pCache->nMax = nMax;
  33931. pCache->n90pct = pCache->nMax*9/10;
  33932. pcache1EnforceMaxPage(pGroup);
  33933. pcache1LeaveMutex(pGroup);
  33934. }
  33935. }
  33936. /*
  33937. ** Implementation of the sqlite3_pcache.xShrink method.
  33938. **
  33939. ** Free up as much memory as possible.
  33940. */
  33941. static void pcache1Shrink(sqlite3_pcache *p){
  33942. PCache1 *pCache = (PCache1*)p;
  33943. if( pCache->bPurgeable ){
  33944. PGroup *pGroup = pCache->pGroup;
  33945. int savedMaxPage;
  33946. pcache1EnterMutex(pGroup);
  33947. savedMaxPage = pGroup->nMaxPage;
  33948. pGroup->nMaxPage = 0;
  33949. pcache1EnforceMaxPage(pGroup);
  33950. pGroup->nMaxPage = savedMaxPage;
  33951. pcache1LeaveMutex(pGroup);
  33952. }
  33953. }
  33954. /*
  33955. ** Implementation of the sqlite3_pcache.xPagecount method.
  33956. */
  33957. static int pcache1Pagecount(sqlite3_pcache *p){
  33958. int n;
  33959. PCache1 *pCache = (PCache1*)p;
  33960. pcache1EnterMutex(pCache->pGroup);
  33961. n = pCache->nPage;
  33962. pcache1LeaveMutex(pCache->pGroup);
  33963. return n;
  33964. }
  33965. /*
  33966. ** Implementation of the sqlite3_pcache.xFetch method.
  33967. **
  33968. ** Fetch a page by key value.
  33969. **
  33970. ** Whether or not a new page may be allocated by this function depends on
  33971. ** the value of the createFlag argument. 0 means do not allocate a new
  33972. ** page. 1 means allocate a new page if space is easily available. 2
  33973. ** means to try really hard to allocate a new page.
  33974. **
  33975. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  33976. ** database) there is really no difference between createFlag 1 and 2. So
  33977. ** the calling function (pcache.c) will never have a createFlag of 1 on
  33978. ** a non-purgeable cache.
  33979. **
  33980. ** There are three different approaches to obtaining space for a page,
  33981. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  33982. **
  33983. ** 1. Regardless of the value of createFlag, the cache is searched for a
  33984. ** copy of the requested page. If one is found, it is returned.
  33985. **
  33986. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  33987. ** returned.
  33988. **
  33989. ** 3. If createFlag is 1, and the page is not already in the cache, then
  33990. ** return NULL (do not allocate a new page) if any of the following
  33991. ** conditions are true:
  33992. **
  33993. ** (a) the number of pages pinned by the cache is greater than
  33994. ** PCache1.nMax, or
  33995. **
  33996. ** (b) the number of pages pinned by the cache is greater than
  33997. ** the sum of nMax for all purgeable caches, less the sum of
  33998. ** nMin for all other purgeable caches, or
  33999. **
  34000. ** 4. If none of the first three conditions apply and the cache is marked
  34001. ** as purgeable, and if one of the following is true:
  34002. **
  34003. ** (a) The number of pages allocated for the cache is already
  34004. ** PCache1.nMax, or
  34005. **
  34006. ** (b) The number of pages allocated for all purgeable caches is
  34007. ** already equal to or greater than the sum of nMax for all
  34008. ** purgeable caches,
  34009. **
  34010. ** (c) The system is under memory pressure and wants to avoid
  34011. ** unnecessary pages cache entry allocations
  34012. **
  34013. ** then attempt to recycle a page from the LRU list. If it is the right
  34014. ** size, return the recycled buffer. Otherwise, free the buffer and
  34015. ** proceed to step 5.
  34016. **
  34017. ** 5. Otherwise, allocate and return a new page buffer.
  34018. */
  34019. static sqlite3_pcache_page *pcache1Fetch(
  34020. sqlite3_pcache *p,
  34021. unsigned int iKey,
  34022. int createFlag
  34023. ){
  34024. unsigned int nPinned;
  34025. PCache1 *pCache = (PCache1 *)p;
  34026. PGroup *pGroup;
  34027. PgHdr1 *pPage = 0;
  34028. assert( pCache->bPurgeable || createFlag!=1 );
  34029. assert( pCache->bPurgeable || pCache->nMin==0 );
  34030. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  34031. assert( pCache->nMin==0 || pCache->bPurgeable );
  34032. pcache1EnterMutex(pGroup = pCache->pGroup);
  34033. /* Step 1: Search the hash table for an existing entry. */
  34034. if( pCache->nHash>0 ){
  34035. unsigned int h = iKey % pCache->nHash;
  34036. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  34037. }
  34038. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  34039. if( pPage || createFlag==0 ){
  34040. pcache1PinPage(pPage);
  34041. goto fetch_out;
  34042. }
  34043. /* The pGroup local variable will normally be initialized by the
  34044. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  34045. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  34046. ** local variable here. Delaying the initialization of pGroup is an
  34047. ** optimization: The common case is to exit the module before reaching
  34048. ** this point.
  34049. */
  34050. #ifdef SQLITE_MUTEX_OMIT
  34051. pGroup = pCache->pGroup;
  34052. #endif
  34053. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  34054. assert( pCache->nPage >= pCache->nRecyclable );
  34055. nPinned = pCache->nPage - pCache->nRecyclable;
  34056. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  34057. assert( pCache->n90pct == pCache->nMax*9/10 );
  34058. if( createFlag==1 && (
  34059. nPinned>=pGroup->mxPinned
  34060. || nPinned>=pCache->n90pct
  34061. || pcache1UnderMemoryPressure(pCache)
  34062. )){
  34063. goto fetch_out;
  34064. }
  34065. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  34066. goto fetch_out;
  34067. }
  34068. /* Step 4. Try to recycle a page. */
  34069. if( pCache->bPurgeable && pGroup->pLruTail && (
  34070. (pCache->nPage+1>=pCache->nMax)
  34071. || pGroup->nCurrentPage>=pGroup->nMaxPage
  34072. || pcache1UnderMemoryPressure(pCache)
  34073. )){
  34074. PCache1 *pOther;
  34075. pPage = pGroup->pLruTail;
  34076. pcache1RemoveFromHash(pPage);
  34077. pcache1PinPage(pPage);
  34078. pOther = pPage->pCache;
  34079. /* We want to verify that szPage and szExtra are the same for pOther
  34080. ** and pCache. Assert that we can verify this by comparing sums. */
  34081. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  34082. assert( pCache->szExtra<512 );
  34083. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  34084. assert( pOther->szExtra<512 );
  34085. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  34086. pcache1FreePage(pPage);
  34087. pPage = 0;
  34088. }else{
  34089. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  34090. }
  34091. }
  34092. /* Step 5. If a usable page buffer has still not been found,
  34093. ** attempt to allocate a new one.
  34094. */
  34095. if( !pPage ){
  34096. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  34097. pPage = pcache1AllocPage(pCache);
  34098. if( createFlag==1 ) sqlite3EndBenignMalloc();
  34099. }
  34100. if( pPage ){
  34101. unsigned int h = iKey % pCache->nHash;
  34102. pCache->nPage++;
  34103. pPage->iKey = iKey;
  34104. pPage->pNext = pCache->apHash[h];
  34105. pPage->pCache = pCache;
  34106. pPage->pLruPrev = 0;
  34107. pPage->pLruNext = 0;
  34108. *(void **)pPage->page.pExtra = 0;
  34109. pCache->apHash[h] = pPage;
  34110. }
  34111. fetch_out:
  34112. if( pPage && iKey>pCache->iMaxKey ){
  34113. pCache->iMaxKey = iKey;
  34114. }
  34115. pcache1LeaveMutex(pGroup);
  34116. return &pPage->page;
  34117. }
  34118. /*
  34119. ** Implementation of the sqlite3_pcache.xUnpin method.
  34120. **
  34121. ** Mark a page as unpinned (eligible for asynchronous recycling).
  34122. */
  34123. static void pcache1Unpin(
  34124. sqlite3_pcache *p,
  34125. sqlite3_pcache_page *pPg,
  34126. int reuseUnlikely
  34127. ){
  34128. PCache1 *pCache = (PCache1 *)p;
  34129. PgHdr1 *pPage = (PgHdr1 *)pPg;
  34130. PGroup *pGroup = pCache->pGroup;
  34131. assert( pPage->pCache==pCache );
  34132. pcache1EnterMutex(pGroup);
  34133. /* It is an error to call this function if the page is already
  34134. ** part of the PGroup LRU list.
  34135. */
  34136. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  34137. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  34138. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  34139. pcache1RemoveFromHash(pPage);
  34140. pcache1FreePage(pPage);
  34141. }else{
  34142. /* Add the page to the PGroup LRU list. */
  34143. if( pGroup->pLruHead ){
  34144. pGroup->pLruHead->pLruPrev = pPage;
  34145. pPage->pLruNext = pGroup->pLruHead;
  34146. pGroup->pLruHead = pPage;
  34147. }else{
  34148. pGroup->pLruTail = pPage;
  34149. pGroup->pLruHead = pPage;
  34150. }
  34151. pCache->nRecyclable++;
  34152. }
  34153. pcache1LeaveMutex(pCache->pGroup);
  34154. }
  34155. /*
  34156. ** Implementation of the sqlite3_pcache.xRekey method.
  34157. */
  34158. static void pcache1Rekey(
  34159. sqlite3_pcache *p,
  34160. sqlite3_pcache_page *pPg,
  34161. unsigned int iOld,
  34162. unsigned int iNew
  34163. ){
  34164. PCache1 *pCache = (PCache1 *)p;
  34165. PgHdr1 *pPage = (PgHdr1 *)pPg;
  34166. PgHdr1 **pp;
  34167. unsigned int h;
  34168. assert( pPage->iKey==iOld );
  34169. assert( pPage->pCache==pCache );
  34170. pcache1EnterMutex(pCache->pGroup);
  34171. h = iOld%pCache->nHash;
  34172. pp = &pCache->apHash[h];
  34173. while( (*pp)!=pPage ){
  34174. pp = &(*pp)->pNext;
  34175. }
  34176. *pp = pPage->pNext;
  34177. h = iNew%pCache->nHash;
  34178. pPage->iKey = iNew;
  34179. pPage->pNext = pCache->apHash[h];
  34180. pCache->apHash[h] = pPage;
  34181. if( iNew>pCache->iMaxKey ){
  34182. pCache->iMaxKey = iNew;
  34183. }
  34184. pcache1LeaveMutex(pCache->pGroup);
  34185. }
  34186. /*
  34187. ** Implementation of the sqlite3_pcache.xTruncate method.
  34188. **
  34189. ** Discard all unpinned pages in the cache with a page number equal to
  34190. ** or greater than parameter iLimit. Any pinned pages with a page number
  34191. ** equal to or greater than iLimit are implicitly unpinned.
  34192. */
  34193. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  34194. PCache1 *pCache = (PCache1 *)p;
  34195. pcache1EnterMutex(pCache->pGroup);
  34196. if( iLimit<=pCache->iMaxKey ){
  34197. pcache1TruncateUnsafe(pCache, iLimit);
  34198. pCache->iMaxKey = iLimit-1;
  34199. }
  34200. pcache1LeaveMutex(pCache->pGroup);
  34201. }
  34202. /*
  34203. ** Implementation of the sqlite3_pcache.xDestroy method.
  34204. **
  34205. ** Destroy a cache allocated using pcache1Create().
  34206. */
  34207. static void pcache1Destroy(sqlite3_pcache *p){
  34208. PCache1 *pCache = (PCache1 *)p;
  34209. PGroup *pGroup = pCache->pGroup;
  34210. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  34211. pcache1EnterMutex(pGroup);
  34212. pcache1TruncateUnsafe(pCache, 0);
  34213. assert( pGroup->nMaxPage >= pCache->nMax );
  34214. pGroup->nMaxPage -= pCache->nMax;
  34215. assert( pGroup->nMinPage >= pCache->nMin );
  34216. pGroup->nMinPage -= pCache->nMin;
  34217. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  34218. pcache1EnforceMaxPage(pGroup);
  34219. pcache1LeaveMutex(pGroup);
  34220. sqlite3_free(pCache->apHash);
  34221. sqlite3_free(pCache);
  34222. }
  34223. /*
  34224. ** This function is called during initialization (sqlite3_initialize()) to
  34225. ** install the default pluggable cache module, assuming the user has not
  34226. ** already provided an alternative.
  34227. */
  34228. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  34229. static const sqlite3_pcache_methods2 defaultMethods = {
  34230. 1, /* iVersion */
  34231. 0, /* pArg */
  34232. pcache1Init, /* xInit */
  34233. pcache1Shutdown, /* xShutdown */
  34234. pcache1Create, /* xCreate */
  34235. pcache1Cachesize, /* xCachesize */
  34236. pcache1Pagecount, /* xPagecount */
  34237. pcache1Fetch, /* xFetch */
  34238. pcache1Unpin, /* xUnpin */
  34239. pcache1Rekey, /* xRekey */
  34240. pcache1Truncate, /* xTruncate */
  34241. pcache1Destroy, /* xDestroy */
  34242. pcache1Shrink /* xShrink */
  34243. };
  34244. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  34245. }
  34246. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  34247. /*
  34248. ** This function is called to free superfluous dynamically allocated memory
  34249. ** held by the pager system. Memory in use by any SQLite pager allocated
  34250. ** by the current thread may be sqlite3_free()ed.
  34251. **
  34252. ** nReq is the number of bytes of memory required. Once this much has
  34253. ** been released, the function returns. The return value is the total number
  34254. ** of bytes of memory released.
  34255. */
  34256. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  34257. int nFree = 0;
  34258. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  34259. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  34260. if( pcache1.pStart==0 ){
  34261. PgHdr1 *p;
  34262. pcache1EnterMutex(&pcache1.grp);
  34263. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  34264. nFree += pcache1MemSize(p->page.pBuf);
  34265. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  34266. nFree += sqlite3MemSize(p);
  34267. #endif
  34268. pcache1PinPage(p);
  34269. pcache1RemoveFromHash(p);
  34270. pcache1FreePage(p);
  34271. }
  34272. pcache1LeaveMutex(&pcache1.grp);
  34273. }
  34274. return nFree;
  34275. }
  34276. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  34277. #ifdef SQLITE_TEST
  34278. /*
  34279. ** This function is used by test procedures to inspect the internal state
  34280. ** of the global cache.
  34281. */
  34282. SQLITE_PRIVATE void sqlite3PcacheStats(
  34283. int *pnCurrent, /* OUT: Total number of pages cached */
  34284. int *pnMax, /* OUT: Global maximum cache size */
  34285. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  34286. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  34287. ){
  34288. PgHdr1 *p;
  34289. int nRecyclable = 0;
  34290. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  34291. nRecyclable++;
  34292. }
  34293. *pnCurrent = pcache1.grp.nCurrentPage;
  34294. *pnMax = (int)pcache1.grp.nMaxPage;
  34295. *pnMin = (int)pcache1.grp.nMinPage;
  34296. *pnRecyclable = nRecyclable;
  34297. }
  34298. #endif
  34299. /************** End of pcache1.c *********************************************/
  34300. /************** Begin file rowset.c ******************************************/
  34301. /*
  34302. ** 2008 December 3
  34303. **
  34304. ** The author disclaims copyright to this source code. In place of
  34305. ** a legal notice, here is a blessing:
  34306. **
  34307. ** May you do good and not evil.
  34308. ** May you find forgiveness for yourself and forgive others.
  34309. ** May you share freely, never taking more than you give.
  34310. **
  34311. *************************************************************************
  34312. **
  34313. ** This module implements an object we call a "RowSet".
  34314. **
  34315. ** The RowSet object is a collection of rowids. Rowids
  34316. ** are inserted into the RowSet in an arbitrary order. Inserts
  34317. ** can be intermixed with tests to see if a given rowid has been
  34318. ** previously inserted into the RowSet.
  34319. **
  34320. ** After all inserts are finished, it is possible to extract the
  34321. ** elements of the RowSet in sorted order. Once this extraction
  34322. ** process has started, no new elements may be inserted.
  34323. **
  34324. ** Hence, the primitive operations for a RowSet are:
  34325. **
  34326. ** CREATE
  34327. ** INSERT
  34328. ** TEST
  34329. ** SMALLEST
  34330. ** DESTROY
  34331. **
  34332. ** The CREATE and DESTROY primitives are the constructor and destructor,
  34333. ** obviously. The INSERT primitive adds a new element to the RowSet.
  34334. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  34335. ** extracts the least value from the RowSet.
  34336. **
  34337. ** The INSERT primitive might allocate additional memory. Memory is
  34338. ** allocated in chunks so most INSERTs do no allocation. There is an
  34339. ** upper bound on the size of allocated memory. No memory is freed
  34340. ** until DESTROY.
  34341. **
  34342. ** The TEST primitive includes a "batch" number. The TEST primitive
  34343. ** will only see elements that were inserted before the last change
  34344. ** in the batch number. In other words, if an INSERT occurs between
  34345. ** two TESTs where the TESTs have the same batch nubmer, then the
  34346. ** value added by the INSERT will not be visible to the second TEST.
  34347. ** The initial batch number is zero, so if the very first TEST contains
  34348. ** a non-zero batch number, it will see all prior INSERTs.
  34349. **
  34350. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  34351. ** that is attempted.
  34352. **
  34353. ** The cost of an INSERT is roughly constant. (Sometime new memory
  34354. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  34355. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  34356. ** The cost of a TEST using the same batch number is O(logN). The cost
  34357. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  34358. ** primitives are constant time. The cost of DESTROY is O(N).
  34359. **
  34360. ** There is an added cost of O(N) when switching between TEST and
  34361. ** SMALLEST primitives.
  34362. */
  34363. /*
  34364. ** Target size for allocation chunks.
  34365. */
  34366. #define ROWSET_ALLOCATION_SIZE 1024
  34367. /*
  34368. ** The number of rowset entries per allocation chunk.
  34369. */
  34370. #define ROWSET_ENTRY_PER_CHUNK \
  34371. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  34372. /*
  34373. ** Each entry in a RowSet is an instance of the following object.
  34374. **
  34375. ** This same object is reused to store a linked list of trees of RowSetEntry
  34376. ** objects. In that alternative use, pRight points to the next entry
  34377. ** in the list, pLeft points to the tree, and v is unused. The
  34378. ** RowSet.pForest value points to the head of this forest list.
  34379. */
  34380. struct RowSetEntry {
  34381. i64 v; /* ROWID value for this entry */
  34382. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  34383. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  34384. };
  34385. /*
  34386. ** RowSetEntry objects are allocated in large chunks (instances of the
  34387. ** following structure) to reduce memory allocation overhead. The
  34388. ** chunks are kept on a linked list so that they can be deallocated
  34389. ** when the RowSet is destroyed.
  34390. */
  34391. struct RowSetChunk {
  34392. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  34393. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  34394. };
  34395. /*
  34396. ** A RowSet in an instance of the following structure.
  34397. **
  34398. ** A typedef of this structure if found in sqliteInt.h.
  34399. */
  34400. struct RowSet {
  34401. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  34402. sqlite3 *db; /* The database connection */
  34403. struct RowSetEntry *pEntry; /* List of entries using pRight */
  34404. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  34405. struct RowSetEntry *pFresh; /* Source of new entry objects */
  34406. struct RowSetEntry *pForest; /* List of binary trees of entries */
  34407. u16 nFresh; /* Number of objects on pFresh */
  34408. u8 rsFlags; /* Various flags */
  34409. u8 iBatch; /* Current insert batch */
  34410. };
  34411. /*
  34412. ** Allowed values for RowSet.rsFlags
  34413. */
  34414. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  34415. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  34416. /*
  34417. ** Turn bulk memory into a RowSet object. N bytes of memory
  34418. ** are available at pSpace. The db pointer is used as a memory context
  34419. ** for any subsequent allocations that need to occur.
  34420. ** Return a pointer to the new RowSet object.
  34421. **
  34422. ** It must be the case that N is sufficient to make a Rowset. If not
  34423. ** an assertion fault occurs.
  34424. **
  34425. ** If N is larger than the minimum, use the surplus as an initial
  34426. ** allocation of entries available to be filled.
  34427. */
  34428. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  34429. RowSet *p;
  34430. assert( N >= ROUND8(sizeof(*p)) );
  34431. p = pSpace;
  34432. p->pChunk = 0;
  34433. p->db = db;
  34434. p->pEntry = 0;
  34435. p->pLast = 0;
  34436. p->pForest = 0;
  34437. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  34438. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  34439. p->rsFlags = ROWSET_SORTED;
  34440. p->iBatch = 0;
  34441. return p;
  34442. }
  34443. /*
  34444. ** Deallocate all chunks from a RowSet. This frees all memory that
  34445. ** the RowSet has allocated over its lifetime. This routine is
  34446. ** the destructor for the RowSet.
  34447. */
  34448. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  34449. struct RowSetChunk *pChunk, *pNextChunk;
  34450. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  34451. pNextChunk = pChunk->pNextChunk;
  34452. sqlite3DbFree(p->db, pChunk);
  34453. }
  34454. p->pChunk = 0;
  34455. p->nFresh = 0;
  34456. p->pEntry = 0;
  34457. p->pLast = 0;
  34458. p->pForest = 0;
  34459. p->rsFlags = ROWSET_SORTED;
  34460. }
  34461. /*
  34462. ** Allocate a new RowSetEntry object that is associated with the
  34463. ** given RowSet. Return a pointer to the new and completely uninitialized
  34464. ** objected.
  34465. **
  34466. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  34467. ** routine returns NULL.
  34468. */
  34469. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  34470. assert( p!=0 );
  34471. if( p->nFresh==0 ){
  34472. struct RowSetChunk *pNew;
  34473. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  34474. if( pNew==0 ){
  34475. return 0;
  34476. }
  34477. pNew->pNextChunk = p->pChunk;
  34478. p->pChunk = pNew;
  34479. p->pFresh = pNew->aEntry;
  34480. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  34481. }
  34482. p->nFresh--;
  34483. return p->pFresh++;
  34484. }
  34485. /*
  34486. ** Insert a new value into a RowSet.
  34487. **
  34488. ** The mallocFailed flag of the database connection is set if a
  34489. ** memory allocation fails.
  34490. */
  34491. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  34492. struct RowSetEntry *pEntry; /* The new entry */
  34493. struct RowSetEntry *pLast; /* The last prior entry */
  34494. /* This routine is never called after sqlite3RowSetNext() */
  34495. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  34496. pEntry = rowSetEntryAlloc(p);
  34497. if( pEntry==0 ) return;
  34498. pEntry->v = rowid;
  34499. pEntry->pRight = 0;
  34500. pLast = p->pLast;
  34501. if( pLast ){
  34502. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  34503. p->rsFlags &= ~ROWSET_SORTED;
  34504. }
  34505. pLast->pRight = pEntry;
  34506. }else{
  34507. p->pEntry = pEntry;
  34508. }
  34509. p->pLast = pEntry;
  34510. }
  34511. /*
  34512. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  34513. **
  34514. ** The input lists are connected via pRight pointers and are
  34515. ** assumed to each already be in sorted order.
  34516. */
  34517. static struct RowSetEntry *rowSetEntryMerge(
  34518. struct RowSetEntry *pA, /* First sorted list to be merged */
  34519. struct RowSetEntry *pB /* Second sorted list to be merged */
  34520. ){
  34521. struct RowSetEntry head;
  34522. struct RowSetEntry *pTail;
  34523. pTail = &head;
  34524. while( pA && pB ){
  34525. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  34526. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  34527. if( pA->v<pB->v ){
  34528. pTail->pRight = pA;
  34529. pA = pA->pRight;
  34530. pTail = pTail->pRight;
  34531. }else if( pB->v<pA->v ){
  34532. pTail->pRight = pB;
  34533. pB = pB->pRight;
  34534. pTail = pTail->pRight;
  34535. }else{
  34536. pA = pA->pRight;
  34537. }
  34538. }
  34539. if( pA ){
  34540. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  34541. pTail->pRight = pA;
  34542. }else{
  34543. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  34544. pTail->pRight = pB;
  34545. }
  34546. return head.pRight;
  34547. }
  34548. /*
  34549. ** Sort all elements on the list of RowSetEntry objects into order of
  34550. ** increasing v.
  34551. */
  34552. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  34553. unsigned int i;
  34554. struct RowSetEntry *pNext, *aBucket[40];
  34555. memset(aBucket, 0, sizeof(aBucket));
  34556. while( pIn ){
  34557. pNext = pIn->pRight;
  34558. pIn->pRight = 0;
  34559. for(i=0; aBucket[i]; i++){
  34560. pIn = rowSetEntryMerge(aBucket[i], pIn);
  34561. aBucket[i] = 0;
  34562. }
  34563. aBucket[i] = pIn;
  34564. pIn = pNext;
  34565. }
  34566. pIn = 0;
  34567. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  34568. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  34569. }
  34570. return pIn;
  34571. }
  34572. /*
  34573. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  34574. ** Convert this tree into a linked list connected by the pRight pointers
  34575. ** and return pointers to the first and last elements of the new list.
  34576. */
  34577. static void rowSetTreeToList(
  34578. struct RowSetEntry *pIn, /* Root of the input tree */
  34579. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  34580. struct RowSetEntry **ppLast /* Write tail of the output list here */
  34581. ){
  34582. assert( pIn!=0 );
  34583. if( pIn->pLeft ){
  34584. struct RowSetEntry *p;
  34585. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  34586. p->pRight = pIn;
  34587. }else{
  34588. *ppFirst = pIn;
  34589. }
  34590. if( pIn->pRight ){
  34591. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  34592. }else{
  34593. *ppLast = pIn;
  34594. }
  34595. assert( (*ppLast)->pRight==0 );
  34596. }
  34597. /*
  34598. ** Convert a sorted list of elements (connected by pRight) into a binary
  34599. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  34600. ** node taken from the head of *ppList. A depth of 2 means a tree with
  34601. ** three nodes. And so forth.
  34602. **
  34603. ** Use as many entries from the input list as required and update the
  34604. ** *ppList to point to the unused elements of the list. If the input
  34605. ** list contains too few elements, then construct an incomplete tree
  34606. ** and leave *ppList set to NULL.
  34607. **
  34608. ** Return a pointer to the root of the constructed binary tree.
  34609. */
  34610. static struct RowSetEntry *rowSetNDeepTree(
  34611. struct RowSetEntry **ppList,
  34612. int iDepth
  34613. ){
  34614. struct RowSetEntry *p; /* Root of the new tree */
  34615. struct RowSetEntry *pLeft; /* Left subtree */
  34616. if( *ppList==0 ){
  34617. return 0;
  34618. }
  34619. if( iDepth==1 ){
  34620. p = *ppList;
  34621. *ppList = p->pRight;
  34622. p->pLeft = p->pRight = 0;
  34623. return p;
  34624. }
  34625. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  34626. p = *ppList;
  34627. if( p==0 ){
  34628. return pLeft;
  34629. }
  34630. p->pLeft = pLeft;
  34631. *ppList = p->pRight;
  34632. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  34633. return p;
  34634. }
  34635. /*
  34636. ** Convert a sorted list of elements into a binary tree. Make the tree
  34637. ** as deep as it needs to be in order to contain the entire list.
  34638. */
  34639. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  34640. int iDepth; /* Depth of the tree so far */
  34641. struct RowSetEntry *p; /* Current tree root */
  34642. struct RowSetEntry *pLeft; /* Left subtree */
  34643. assert( pList!=0 );
  34644. p = pList;
  34645. pList = p->pRight;
  34646. p->pLeft = p->pRight = 0;
  34647. for(iDepth=1; pList; iDepth++){
  34648. pLeft = p;
  34649. p = pList;
  34650. pList = p->pRight;
  34651. p->pLeft = pLeft;
  34652. p->pRight = rowSetNDeepTree(&pList, iDepth);
  34653. }
  34654. return p;
  34655. }
  34656. /*
  34657. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  34658. ** sort them all together into one big ordered list on p->pEntry.
  34659. **
  34660. ** This routine should only be called once in the life of a RowSet.
  34661. */
  34662. static void rowSetToList(RowSet *p){
  34663. /* This routine is called only once */
  34664. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  34665. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  34666. p->pEntry = rowSetEntrySort(p->pEntry);
  34667. }
  34668. /* While this module could theoretically support it, sqlite3RowSetNext()
  34669. ** is never called after sqlite3RowSetText() for the same RowSet. So
  34670. ** there is never a forest to deal with. Should this change, simply
  34671. ** remove the assert() and the #if 0. */
  34672. assert( p->pForest==0 );
  34673. #if 0
  34674. while( p->pForest ){
  34675. struct RowSetEntry *pTree = p->pForest->pLeft;
  34676. if( pTree ){
  34677. struct RowSetEntry *pHead, *pTail;
  34678. rowSetTreeToList(pTree, &pHead, &pTail);
  34679. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  34680. }
  34681. p->pForest = p->pForest->pRight;
  34682. }
  34683. #endif
  34684. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  34685. }
  34686. /*
  34687. ** Extract the smallest element from the RowSet.
  34688. ** Write the element into *pRowid. Return 1 on success. Return
  34689. ** 0 if the RowSet is already empty.
  34690. **
  34691. ** After this routine has been called, the sqlite3RowSetInsert()
  34692. ** routine may not be called again.
  34693. */
  34694. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  34695. assert( p!=0 );
  34696. /* Merge the forest into a single sorted list on first call */
  34697. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  34698. /* Return the next entry on the list */
  34699. if( p->pEntry ){
  34700. *pRowid = p->pEntry->v;
  34701. p->pEntry = p->pEntry->pRight;
  34702. if( p->pEntry==0 ){
  34703. sqlite3RowSetClear(p);
  34704. }
  34705. return 1;
  34706. }else{
  34707. return 0;
  34708. }
  34709. }
  34710. /*
  34711. ** Check to see if element iRowid was inserted into the rowset as
  34712. ** part of any insert batch prior to iBatch. Return 1 or 0.
  34713. **
  34714. ** If this is the first test of a new batch and if there exist entires
  34715. ** on pRowSet->pEntry, then sort those entires into the forest at
  34716. ** pRowSet->pForest so that they can be tested.
  34717. */
  34718. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  34719. struct RowSetEntry *p, *pTree;
  34720. /* This routine is never called after sqlite3RowSetNext() */
  34721. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  34722. /* Sort entries into the forest on the first test of a new batch
  34723. */
  34724. if( iBatch!=pRowSet->iBatch ){
  34725. p = pRowSet->pEntry;
  34726. if( p ){
  34727. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  34728. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  34729. p = rowSetEntrySort(p);
  34730. }
  34731. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  34732. ppPrevTree = &pTree->pRight;
  34733. if( pTree->pLeft==0 ){
  34734. pTree->pLeft = rowSetListToTree(p);
  34735. break;
  34736. }else{
  34737. struct RowSetEntry *pAux, *pTail;
  34738. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  34739. pTree->pLeft = 0;
  34740. p = rowSetEntryMerge(pAux, p);
  34741. }
  34742. }
  34743. if( pTree==0 ){
  34744. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  34745. if( pTree ){
  34746. pTree->v = 0;
  34747. pTree->pRight = 0;
  34748. pTree->pLeft = rowSetListToTree(p);
  34749. }
  34750. }
  34751. pRowSet->pEntry = 0;
  34752. pRowSet->pLast = 0;
  34753. pRowSet->rsFlags |= ROWSET_SORTED;
  34754. }
  34755. pRowSet->iBatch = iBatch;
  34756. }
  34757. /* Test to see if the iRowid value appears anywhere in the forest.
  34758. ** Return 1 if it does and 0 if not.
  34759. */
  34760. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  34761. p = pTree->pLeft;
  34762. while( p ){
  34763. if( p->v<iRowid ){
  34764. p = p->pRight;
  34765. }else if( p->v>iRowid ){
  34766. p = p->pLeft;
  34767. }else{
  34768. return 1;
  34769. }
  34770. }
  34771. }
  34772. return 0;
  34773. }
  34774. /************** End of rowset.c **********************************************/
  34775. /************** Begin file pager.c *******************************************/
  34776. /*
  34777. ** 2001 September 15
  34778. **
  34779. ** The author disclaims copyright to this source code. In place of
  34780. ** a legal notice, here is a blessing:
  34781. **
  34782. ** May you do good and not evil.
  34783. ** May you find forgiveness for yourself and forgive others.
  34784. ** May you share freely, never taking more than you give.
  34785. **
  34786. *************************************************************************
  34787. ** This is the implementation of the page cache subsystem or "pager".
  34788. **
  34789. ** The pager is used to access a database disk file. It implements
  34790. ** atomic commit and rollback through the use of a journal file that
  34791. ** is separate from the database file. The pager also implements file
  34792. ** locking to prevent two processes from writing the same database
  34793. ** file simultaneously, or one process from reading the database while
  34794. ** another is writing.
  34795. */
  34796. #ifndef SQLITE_OMIT_DISKIO
  34797. /************** Include wal.h in the middle of pager.c ***********************/
  34798. /************** Begin file wal.h *********************************************/
  34799. /*
  34800. ** 2010 February 1
  34801. **
  34802. ** The author disclaims copyright to this source code. In place of
  34803. ** a legal notice, here is a blessing:
  34804. **
  34805. ** May you do good and not evil.
  34806. ** May you find forgiveness for yourself and forgive others.
  34807. ** May you share freely, never taking more than you give.
  34808. **
  34809. *************************************************************************
  34810. ** This header file defines the interface to the write-ahead logging
  34811. ** system. Refer to the comments below and the header comment attached to
  34812. ** the implementation of each function in log.c for further details.
  34813. */
  34814. #ifndef _WAL_H_
  34815. #define _WAL_H_
  34816. /* Additional values that can be added to the sync_flags argument of
  34817. ** sqlite3WalFrames():
  34818. */
  34819. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  34820. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  34821. #ifdef SQLITE_OMIT_WAL
  34822. # define sqlite3WalOpen(x,y,z) 0
  34823. # define sqlite3WalLimit(x,y)
  34824. # define sqlite3WalClose(w,x,y,z) 0
  34825. # define sqlite3WalBeginReadTransaction(y,z) 0
  34826. # define sqlite3WalEndReadTransaction(z)
  34827. # define sqlite3WalRead(v,w,x,y,z) 0
  34828. # define sqlite3WalDbsize(y) 0
  34829. # define sqlite3WalBeginWriteTransaction(y) 0
  34830. # define sqlite3WalEndWriteTransaction(x) 0
  34831. # define sqlite3WalUndo(x,y,z) 0
  34832. # define sqlite3WalSavepoint(y,z)
  34833. # define sqlite3WalSavepointUndo(y,z) 0
  34834. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  34835. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  34836. # define sqlite3WalCallback(z) 0
  34837. # define sqlite3WalExclusiveMode(y,z) 0
  34838. # define sqlite3WalHeapMemory(z) 0
  34839. # define sqlite3WalFramesize(z) 0
  34840. #else
  34841. #define WAL_SAVEPOINT_NDATA 4
  34842. /* Connection to a write-ahead log (WAL) file.
  34843. ** There is one object of this type for each pager.
  34844. */
  34845. typedef struct Wal Wal;
  34846. /* Open and close a connection to a write-ahead log. */
  34847. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  34848. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  34849. /* Set the limiting size of a WAL file. */
  34850. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  34851. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  34852. ** snapshot is like a read-transaction. It is the state of the database
  34853. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  34854. ** preserves the current state even if the other threads or processes
  34855. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  34856. ** transaction and releases the lock.
  34857. */
  34858. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  34859. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  34860. /* Read a page from the write-ahead log, if it is present. */
  34861. SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
  34862. /* If the WAL is not empty, return the size of the database. */
  34863. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  34864. /* Obtain or release the WRITER lock. */
  34865. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  34866. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  34867. /* Undo any frames written (but not committed) to the log */
  34868. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  34869. /* Return an integer that records the current (uncommitted) write
  34870. ** position in the WAL */
  34871. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  34872. /* Move the write position of the WAL back to iFrame. Called in
  34873. ** response to a ROLLBACK TO command. */
  34874. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  34875. /* Write a frame or frames to the log. */
  34876. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  34877. /* Copy pages from the log to the database file */
  34878. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  34879. Wal *pWal, /* Write-ahead log connection */
  34880. int eMode, /* One of PASSIVE, FULL and RESTART */
  34881. int (*xBusy)(void*), /* Function to call when busy */
  34882. void *pBusyArg, /* Context argument for xBusyHandler */
  34883. int sync_flags, /* Flags to sync db file with (or 0) */
  34884. int nBuf, /* Size of buffer nBuf */
  34885. u8 *zBuf, /* Temporary buffer to use */
  34886. int *pnLog, /* OUT: Number of frames in WAL */
  34887. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  34888. );
  34889. /* Return the value to pass to a sqlite3_wal_hook callback, the
  34890. ** number of frames in the WAL at the point of the last commit since
  34891. ** sqlite3WalCallback() was called. If no commits have occurred since
  34892. ** the last call, then return 0.
  34893. */
  34894. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  34895. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  34896. ** by the pager layer on the database file.
  34897. */
  34898. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  34899. /* Return true if the argument is non-NULL and the WAL module is using
  34900. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  34901. ** WAL module is using shared-memory, return false.
  34902. */
  34903. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  34904. #ifdef SQLITE_ENABLE_ZIPVFS
  34905. /* If the WAL file is not empty, return the number of bytes of content
  34906. ** stored in each frame (i.e. the db page-size when the WAL was created).
  34907. */
  34908. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  34909. #endif
  34910. #endif /* ifndef SQLITE_OMIT_WAL */
  34911. #endif /* _WAL_H_ */
  34912. /************** End of wal.h *************************************************/
  34913. /************** Continuing where we left off in pager.c **********************/
  34914. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  34915. **
  34916. ** This comment block describes invariants that hold when using a rollback
  34917. ** journal. These invariants do not apply for journal_mode=WAL,
  34918. ** journal_mode=MEMORY, or journal_mode=OFF.
  34919. **
  34920. ** Within this comment block, a page is deemed to have been synced
  34921. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  34922. ** Otherwise, the page is not synced until the xSync method of the VFS
  34923. ** is called successfully on the file containing the page.
  34924. **
  34925. ** Definition: A page of the database file is said to be "overwriteable" if
  34926. ** one or more of the following are true about the page:
  34927. **
  34928. ** (a) The original content of the page as it was at the beginning of
  34929. ** the transaction has been written into the rollback journal and
  34930. ** synced.
  34931. **
  34932. ** (b) The page was a freelist leaf page at the start of the transaction.
  34933. **
  34934. ** (c) The page number is greater than the largest page that existed in
  34935. ** the database file at the start of the transaction.
  34936. **
  34937. ** (1) A page of the database file is never overwritten unless one of the
  34938. ** following are true:
  34939. **
  34940. ** (a) The page and all other pages on the same sector are overwriteable.
  34941. **
  34942. ** (b) The atomic page write optimization is enabled, and the entire
  34943. ** transaction other than the update of the transaction sequence
  34944. ** number consists of a single page change.
  34945. **
  34946. ** (2) The content of a page written into the rollback journal exactly matches
  34947. ** both the content in the database when the rollback journal was written
  34948. ** and the content in the database at the beginning of the current
  34949. ** transaction.
  34950. **
  34951. ** (3) Writes to the database file are an integer multiple of the page size
  34952. ** in length and are aligned on a page boundary.
  34953. **
  34954. ** (4) Reads from the database file are either aligned on a page boundary and
  34955. ** an integer multiple of the page size in length or are taken from the
  34956. ** first 100 bytes of the database file.
  34957. **
  34958. ** (5) All writes to the database file are synced prior to the rollback journal
  34959. ** being deleted, truncated, or zeroed.
  34960. **
  34961. ** (6) If a master journal file is used, then all writes to the database file
  34962. ** are synced prior to the master journal being deleted.
  34963. **
  34964. ** Definition: Two databases (or the same database at two points it time)
  34965. ** are said to be "logically equivalent" if they give the same answer to
  34966. ** all queries. Note in particular the content of freelist leaf
  34967. ** pages can be changed arbitarily without effecting the logical equivalence
  34968. ** of the database.
  34969. **
  34970. ** (7) At any time, if any subset, including the empty set and the total set,
  34971. ** of the unsynced changes to a rollback journal are removed and the
  34972. ** journal is rolled back, the resulting database file will be logical
  34973. ** equivalent to the database file at the beginning of the transaction.
  34974. **
  34975. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  34976. ** is called to restore the database file to the same size it was at
  34977. ** the beginning of the transaction. (In some VFSes, the xTruncate
  34978. ** method is a no-op, but that does not change the fact the SQLite will
  34979. ** invoke it.)
  34980. **
  34981. ** (9) Whenever the database file is modified, at least one bit in the range
  34982. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  34983. ** the EXCLUSIVE lock, thus signaling other connections on the same
  34984. ** database to flush their caches.
  34985. **
  34986. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  34987. ** than one billion transactions.
  34988. **
  34989. ** (11) A database file is well-formed at the beginning and at the conclusion
  34990. ** of every transaction.
  34991. **
  34992. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  34993. ** the database file.
  34994. **
  34995. ** (13) A SHARED lock is held on the database file while reading any
  34996. ** content out of the database file.
  34997. **
  34998. ******************************************************************************/
  34999. /*
  35000. ** Macros for troubleshooting. Normally turned off
  35001. */
  35002. #if 0
  35003. int sqlite3PagerTrace=1; /* True to enable tracing */
  35004. #define sqlite3DebugPrintf printf
  35005. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  35006. #else
  35007. #define PAGERTRACE(X)
  35008. #endif
  35009. /*
  35010. ** The following two macros are used within the PAGERTRACE() macros above
  35011. ** to print out file-descriptors.
  35012. **
  35013. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  35014. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  35015. ** struct as its argument.
  35016. */
  35017. #define PAGERID(p) ((int)(p->fd))
  35018. #define FILEHANDLEID(fd) ((int)fd)
  35019. /*
  35020. ** The Pager.eState variable stores the current 'state' of a pager. A
  35021. ** pager may be in any one of the seven states shown in the following
  35022. ** state diagram.
  35023. **
  35024. ** OPEN <------+------+
  35025. ** | | |
  35026. ** V | |
  35027. ** +---------> READER-------+ |
  35028. ** | | |
  35029. ** | V |
  35030. ** |<-------WRITER_LOCKED------> ERROR
  35031. ** | | ^
  35032. ** | V |
  35033. ** |<------WRITER_CACHEMOD-------->|
  35034. ** | | |
  35035. ** | V |
  35036. ** |<-------WRITER_DBMOD---------->|
  35037. ** | | |
  35038. ** | V |
  35039. ** +<------WRITER_FINISHED-------->+
  35040. **
  35041. **
  35042. ** List of state transitions and the C [function] that performs each:
  35043. **
  35044. ** OPEN -> READER [sqlite3PagerSharedLock]
  35045. ** READER -> OPEN [pager_unlock]
  35046. **
  35047. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  35048. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  35049. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  35050. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  35051. ** WRITER_*** -> READER [pager_end_transaction]
  35052. **
  35053. ** WRITER_*** -> ERROR [pager_error]
  35054. ** ERROR -> OPEN [pager_unlock]
  35055. **
  35056. **
  35057. ** OPEN:
  35058. **
  35059. ** The pager starts up in this state. Nothing is guaranteed in this
  35060. ** state - the file may or may not be locked and the database size is
  35061. ** unknown. The database may not be read or written.
  35062. **
  35063. ** * No read or write transaction is active.
  35064. ** * Any lock, or no lock at all, may be held on the database file.
  35065. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  35066. **
  35067. ** READER:
  35068. **
  35069. ** In this state all the requirements for reading the database in
  35070. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  35071. ** was) in exclusive-locking mode, a user-level read transaction is
  35072. ** open. The database size is known in this state.
  35073. **
  35074. ** A connection running with locking_mode=normal enters this state when
  35075. ** it opens a read-transaction on the database and returns to state
  35076. ** OPEN after the read-transaction is completed. However a connection
  35077. ** running in locking_mode=exclusive (including temp databases) remains in
  35078. ** this state even after the read-transaction is closed. The only way
  35079. ** a locking_mode=exclusive connection can transition from READER to OPEN
  35080. ** is via the ERROR state (see below).
  35081. **
  35082. ** * A read transaction may be active (but a write-transaction cannot).
  35083. ** * A SHARED or greater lock is held on the database file.
  35084. ** * The dbSize variable may be trusted (even if a user-level read
  35085. ** transaction is not active). The dbOrigSize and dbFileSize variables
  35086. ** may not be trusted at this point.
  35087. ** * If the database is a WAL database, then the WAL connection is open.
  35088. ** * Even if a read-transaction is not open, it is guaranteed that
  35089. ** there is no hot-journal in the file-system.
  35090. **
  35091. ** WRITER_LOCKED:
  35092. **
  35093. ** The pager moves to this state from READER when a write-transaction
  35094. ** is first opened on the database. In WRITER_LOCKED state, all locks
  35095. ** required to start a write-transaction are held, but no actual
  35096. ** modifications to the cache or database have taken place.
  35097. **
  35098. ** In rollback mode, a RESERVED or (if the transaction was opened with
  35099. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  35100. ** moving to this state, but the journal file is not written to or opened
  35101. ** to in this state. If the transaction is committed or rolled back while
  35102. ** in WRITER_LOCKED state, all that is required is to unlock the database
  35103. ** file.
  35104. **
  35105. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  35106. ** If the connection is running with locking_mode=exclusive, an attempt
  35107. ** is made to obtain an EXCLUSIVE lock on the database file.
  35108. **
  35109. ** * A write transaction is active.
  35110. ** * If the connection is open in rollback-mode, a RESERVED or greater
  35111. ** lock is held on the database file.
  35112. ** * If the connection is open in WAL-mode, a WAL write transaction
  35113. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  35114. ** called).
  35115. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  35116. ** * The contents of the pager cache have not been modified.
  35117. ** * The journal file may or may not be open.
  35118. ** * Nothing (not even the first header) has been written to the journal.
  35119. **
  35120. ** WRITER_CACHEMOD:
  35121. **
  35122. ** A pager moves from WRITER_LOCKED state to this state when a page is
  35123. ** first modified by the upper layer. In rollback mode the journal file
  35124. ** is opened (if it is not already open) and a header written to the
  35125. ** start of it. The database file on disk has not been modified.
  35126. **
  35127. ** * A write transaction is active.
  35128. ** * A RESERVED or greater lock is held on the database file.
  35129. ** * The journal file is open and the first header has been written
  35130. ** to it, but the header has not been synced to disk.
  35131. ** * The contents of the page cache have been modified.
  35132. **
  35133. ** WRITER_DBMOD:
  35134. **
  35135. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  35136. ** when it modifies the contents of the database file. WAL connections
  35137. ** never enter this state (since they do not modify the database file,
  35138. ** just the log file).
  35139. **
  35140. ** * A write transaction is active.
  35141. ** * An EXCLUSIVE or greater lock is held on the database file.
  35142. ** * The journal file is open and the first header has been written
  35143. ** and synced to disk.
  35144. ** * The contents of the page cache have been modified (and possibly
  35145. ** written to disk).
  35146. **
  35147. ** WRITER_FINISHED:
  35148. **
  35149. ** It is not possible for a WAL connection to enter this state.
  35150. **
  35151. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  35152. ** state after the entire transaction has been successfully written into the
  35153. ** database file. In this state the transaction may be committed simply
  35154. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  35155. ** not possible to modify the database further. At this point, the upper
  35156. ** layer must either commit or rollback the transaction.
  35157. **
  35158. ** * A write transaction is active.
  35159. ** * An EXCLUSIVE or greater lock is held on the database file.
  35160. ** * All writing and syncing of journal and database data has finished.
  35161. ** If no error occured, all that remains is to finalize the journal to
  35162. ** commit the transaction. If an error did occur, the caller will need
  35163. ** to rollback the transaction.
  35164. **
  35165. ** ERROR:
  35166. **
  35167. ** The ERROR state is entered when an IO or disk-full error (including
  35168. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  35169. ** difficult to be sure that the in-memory pager state (cache contents,
  35170. ** db size etc.) are consistent with the contents of the file-system.
  35171. **
  35172. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  35173. ** cannot.
  35174. **
  35175. ** For example, if an IO error occurs while performing a rollback,
  35176. ** the contents of the page-cache may be left in an inconsistent state.
  35177. ** At this point it would be dangerous to change back to READER state
  35178. ** (as usually happens after a rollback). Any subsequent readers might
  35179. ** report database corruption (due to the inconsistent cache), and if
  35180. ** they upgrade to writers, they may inadvertently corrupt the database
  35181. ** file. To avoid this hazard, the pager switches into the ERROR state
  35182. ** instead of READER following such an error.
  35183. **
  35184. ** Once it has entered the ERROR state, any attempt to use the pager
  35185. ** to read or write data returns an error. Eventually, once all
  35186. ** outstanding transactions have been abandoned, the pager is able to
  35187. ** transition back to OPEN state, discarding the contents of the
  35188. ** page-cache and any other in-memory state at the same time. Everything
  35189. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  35190. ** when a read-transaction is next opened on the pager (transitioning
  35191. ** the pager into READER state). At that point the system has recovered
  35192. ** from the error.
  35193. **
  35194. ** Specifically, the pager jumps into the ERROR state if:
  35195. **
  35196. ** 1. An error occurs while attempting a rollback. This happens in
  35197. ** function sqlite3PagerRollback().
  35198. **
  35199. ** 2. An error occurs while attempting to finalize a journal file
  35200. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  35201. **
  35202. ** 3. An error occurs while attempting to write to the journal or
  35203. ** database file in function pagerStress() in order to free up
  35204. ** memory.
  35205. **
  35206. ** In other cases, the error is returned to the b-tree layer. The b-tree
  35207. ** layer then attempts a rollback operation. If the error condition
  35208. ** persists, the pager enters the ERROR state via condition (1) above.
  35209. **
  35210. ** Condition (3) is necessary because it can be triggered by a read-only
  35211. ** statement executed within a transaction. In this case, if the error
  35212. ** code were simply returned to the user, the b-tree layer would not
  35213. ** automatically attempt a rollback, as it assumes that an error in a
  35214. ** read-only statement cannot leave the pager in an internally inconsistent
  35215. ** state.
  35216. **
  35217. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  35218. ** * There are one or more outstanding references to pages (after the
  35219. ** last reference is dropped the pager should move back to OPEN state).
  35220. ** * The pager is not an in-memory pager.
  35221. **
  35222. **
  35223. ** Notes:
  35224. **
  35225. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  35226. ** connection is open in WAL mode. A WAL connection is always in one
  35227. ** of the first four states.
  35228. **
  35229. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  35230. ** state. There are two exceptions: immediately after exclusive-mode has
  35231. ** been turned on (and before any read or write transactions are
  35232. ** executed), and when the pager is leaving the "error state".
  35233. **
  35234. ** * See also: assert_pager_state().
  35235. */
  35236. #define PAGER_OPEN 0
  35237. #define PAGER_READER 1
  35238. #define PAGER_WRITER_LOCKED 2
  35239. #define PAGER_WRITER_CACHEMOD 3
  35240. #define PAGER_WRITER_DBMOD 4
  35241. #define PAGER_WRITER_FINISHED 5
  35242. #define PAGER_ERROR 6
  35243. /*
  35244. ** The Pager.eLock variable is almost always set to one of the
  35245. ** following locking-states, according to the lock currently held on
  35246. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  35247. ** This variable is kept up to date as locks are taken and released by
  35248. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  35249. **
  35250. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  35251. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  35252. ** the operation was successful. In these circumstances pagerLockDb() and
  35253. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  35254. ** when unlocking the file, and only updated when locking the file if the
  35255. ** VFS call is successful. This way, the Pager.eLock variable may be set
  35256. ** to a less exclusive (lower) value than the lock that is actually held
  35257. ** at the system level, but it is never set to a more exclusive value.
  35258. **
  35259. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  35260. ** be a few redundant xLock() calls or a lock may be held for longer than
  35261. ** required, but nothing really goes wrong.
  35262. **
  35263. ** The exception is when the database file is unlocked as the pager moves
  35264. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  35265. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  35266. ** transition, by the same pager or any other). If the call to xUnlock()
  35267. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  35268. ** can confuse the call to xCheckReservedLock() call made later as part
  35269. ** of hot-journal detection.
  35270. **
  35271. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  35272. ** lock held by this process or any others". So xCheckReservedLock may
  35273. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  35274. ** doesn't know it because of a previous error in xUnlock). If this happens
  35275. ** a hot-journal may be mistaken for a journal being created by an active
  35276. ** transaction in another process, causing SQLite to read from the database
  35277. ** without rolling it back.
  35278. **
  35279. ** To work around this, if a call to xUnlock() fails when unlocking the
  35280. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  35281. ** is only changed back to a real locking state after a successful call
  35282. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  35283. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  35284. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  35285. ** lock on the database file before attempting to roll it back. See function
  35286. ** PagerSharedLock() for more detail.
  35287. **
  35288. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  35289. ** PAGER_OPEN state.
  35290. */
  35291. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  35292. /*
  35293. ** A macro used for invoking the codec if there is one
  35294. */
  35295. #ifdef SQLITE_HAS_CODEC
  35296. # define CODEC1(P,D,N,X,E) \
  35297. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  35298. # define CODEC2(P,D,N,X,E,O) \
  35299. if( P->xCodec==0 ){ O=(char*)D; }else \
  35300. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  35301. #else
  35302. # define CODEC1(P,D,N,X,E) /* NO-OP */
  35303. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  35304. #endif
  35305. /*
  35306. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  35307. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  35308. ** This could conceivably cause corruption following a power failure on
  35309. ** such a system. This is currently an undocumented limit.
  35310. */
  35311. #define MAX_SECTOR_SIZE 0x10000
  35312. /*
  35313. ** An instance of the following structure is allocated for each active
  35314. ** savepoint and statement transaction in the system. All such structures
  35315. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  35316. ** resized using sqlite3Realloc().
  35317. **
  35318. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  35319. ** set to 0. If a journal-header is written into the main journal while
  35320. ** the savepoint is active, then iHdrOffset is set to the byte offset
  35321. ** immediately following the last journal record written into the main
  35322. ** journal before the journal-header. This is required during savepoint
  35323. ** rollback (see pagerPlaybackSavepoint()).
  35324. */
  35325. typedef struct PagerSavepoint PagerSavepoint;
  35326. struct PagerSavepoint {
  35327. i64 iOffset; /* Starting offset in main journal */
  35328. i64 iHdrOffset; /* See above */
  35329. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  35330. Pgno nOrig; /* Original number of pages in file */
  35331. Pgno iSubRec; /* Index of first record in sub-journal */
  35332. #ifndef SQLITE_OMIT_WAL
  35333. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  35334. #endif
  35335. };
  35336. /*
  35337. ** A open page cache is an instance of struct Pager. A description of
  35338. ** some of the more important member variables follows:
  35339. **
  35340. ** eState
  35341. **
  35342. ** The current 'state' of the pager object. See the comment and state
  35343. ** diagram above for a description of the pager state.
  35344. **
  35345. ** eLock
  35346. **
  35347. ** For a real on-disk database, the current lock held on the database file -
  35348. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  35349. **
  35350. ** For a temporary or in-memory database (neither of which require any
  35351. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  35352. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  35353. ** logic into thinking that it already has all the locks it will ever
  35354. ** need (and no reason to release them).
  35355. **
  35356. ** In some (obscure) circumstances, this variable may also be set to
  35357. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  35358. ** details.
  35359. **
  35360. ** changeCountDone
  35361. **
  35362. ** This boolean variable is used to make sure that the change-counter
  35363. ** (the 4-byte header field at byte offset 24 of the database file) is
  35364. ** not updated more often than necessary.
  35365. **
  35366. ** It is set to true when the change-counter field is updated, which
  35367. ** can only happen if an exclusive lock is held on the database file.
  35368. ** It is cleared (set to false) whenever an exclusive lock is
  35369. ** relinquished on the database file. Each time a transaction is committed,
  35370. ** The changeCountDone flag is inspected. If it is true, the work of
  35371. ** updating the change-counter is omitted for the current transaction.
  35372. **
  35373. ** This mechanism means that when running in exclusive mode, a connection
  35374. ** need only update the change-counter once, for the first transaction
  35375. ** committed.
  35376. **
  35377. ** setMaster
  35378. **
  35379. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  35380. ** (or may not) specify a master-journal name to be written into the
  35381. ** journal file before it is synced to disk.
  35382. **
  35383. ** Whether or not a journal file contains a master-journal pointer affects
  35384. ** the way in which the journal file is finalized after the transaction is
  35385. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  35386. ** If a journal file does not contain a master-journal pointer, it is
  35387. ** finalized by overwriting the first journal header with zeroes. If
  35388. ** it does contain a master-journal pointer the journal file is finalized
  35389. ** by truncating it to zero bytes, just as if the connection were
  35390. ** running in "journal_mode=truncate" mode.
  35391. **
  35392. ** Journal files that contain master journal pointers cannot be finalized
  35393. ** simply by overwriting the first journal-header with zeroes, as the
  35394. ** master journal pointer could interfere with hot-journal rollback of any
  35395. ** subsequently interrupted transaction that reuses the journal file.
  35396. **
  35397. ** The flag is cleared as soon as the journal file is finalized (either
  35398. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  35399. ** journal file from being successfully finalized, the setMaster flag
  35400. ** is cleared anyway (and the pager will move to ERROR state).
  35401. **
  35402. ** doNotSpill, doNotSyncSpill
  35403. **
  35404. ** These two boolean variables control the behaviour of cache-spills
  35405. ** (calls made by the pcache module to the pagerStress() routine to
  35406. ** write cached data to the file-system in order to free up memory).
  35407. **
  35408. ** When doNotSpill is non-zero, writing to the database from pagerStress()
  35409. ** is disabled altogether. This is done in a very obscure case that
  35410. ** comes up during savepoint rollback that requires the pcache module
  35411. ** to allocate a new page to prevent the journal file from being written
  35412. ** while it is being traversed by code in pager_playback().
  35413. **
  35414. ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
  35415. ** is permitted, but syncing the journal file is not. This flag is set
  35416. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  35417. ** the database page-size in order to prevent a journal sync from happening
  35418. ** in between the journalling of two pages on the same sector.
  35419. **
  35420. ** subjInMemory
  35421. **
  35422. ** This is a boolean variable. If true, then any required sub-journal
  35423. ** is opened as an in-memory journal file. If false, then in-memory
  35424. ** sub-journals are only used for in-memory pager files.
  35425. **
  35426. ** This variable is updated by the upper layer each time a new
  35427. ** write-transaction is opened.
  35428. **
  35429. ** dbSize, dbOrigSize, dbFileSize
  35430. **
  35431. ** Variable dbSize is set to the number of pages in the database file.
  35432. ** It is valid in PAGER_READER and higher states (all states except for
  35433. ** OPEN and ERROR).
  35434. **
  35435. ** dbSize is set based on the size of the database file, which may be
  35436. ** larger than the size of the database (the value stored at offset
  35437. ** 28 of the database header by the btree). If the size of the file
  35438. ** is not an integer multiple of the page-size, the value stored in
  35439. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  35440. ** Except, any file that is greater than 0 bytes in size is considered
  35441. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  35442. ** to dbSize==1).
  35443. **
  35444. ** During a write-transaction, if pages with page-numbers greater than
  35445. ** dbSize are modified in the cache, dbSize is updated accordingly.
  35446. ** Similarly, if the database is truncated using PagerTruncateImage(),
  35447. ** dbSize is updated.
  35448. **
  35449. ** Variables dbOrigSize and dbFileSize are valid in states
  35450. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  35451. ** variable at the start of the transaction. It is used during rollback,
  35452. ** and to determine whether or not pages need to be journalled before
  35453. ** being modified.
  35454. **
  35455. ** Throughout a write-transaction, dbFileSize contains the size of
  35456. ** the file on disk in pages. It is set to a copy of dbSize when the
  35457. ** write-transaction is first opened, and updated when VFS calls are made
  35458. ** to write or truncate the database file on disk.
  35459. **
  35460. ** The only reason the dbFileSize variable is required is to suppress
  35461. ** unnecessary calls to xTruncate() after committing a transaction. If,
  35462. ** when a transaction is committed, the dbFileSize variable indicates
  35463. ** that the database file is larger than the database image (Pager.dbSize),
  35464. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  35465. ** to measure the database file on disk, and then truncates it if required.
  35466. ** dbFileSize is not used when rolling back a transaction. In this case
  35467. ** pager_truncate() is called unconditionally (which means there may be
  35468. ** a call to xFilesize() that is not strictly required). In either case,
  35469. ** pager_truncate() may cause the file to become smaller or larger.
  35470. **
  35471. ** dbHintSize
  35472. **
  35473. ** The dbHintSize variable is used to limit the number of calls made to
  35474. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  35475. **
  35476. ** dbHintSize is set to a copy of the dbSize variable when a
  35477. ** write-transaction is opened (at the same time as dbFileSize and
  35478. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  35479. ** dbHintSize is increased to the number of pages that correspond to the
  35480. ** size-hint passed to the method call. See pager_write_pagelist() for
  35481. ** details.
  35482. **
  35483. ** errCode
  35484. **
  35485. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  35486. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  35487. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  35488. ** sub-codes.
  35489. */
  35490. struct Pager {
  35491. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  35492. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  35493. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  35494. u8 useJournal; /* Use a rollback journal on this file */
  35495. u8 noSync; /* Do not sync the journal if true */
  35496. u8 fullSync; /* Do extra syncs of the journal for robustness */
  35497. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  35498. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  35499. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  35500. u8 tempFile; /* zFilename is a temporary file */
  35501. u8 readOnly; /* True for a read-only database */
  35502. u8 memDb; /* True to inhibit all file I/O */
  35503. /**************************************************************************
  35504. ** The following block contains those class members that change during
  35505. ** routine opertion. Class members not in this block are either fixed
  35506. ** when the pager is first created or else only change when there is a
  35507. ** significant mode change (such as changing the page_size, locking_mode,
  35508. ** or the journal_mode). From another view, these class members describe
  35509. ** the "state" of the pager, while other class members describe the
  35510. ** "configuration" of the pager.
  35511. */
  35512. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  35513. u8 eLock; /* Current lock held on database file */
  35514. u8 changeCountDone; /* Set after incrementing the change-counter */
  35515. u8 setMaster; /* True if a m-j name has been written to jrnl */
  35516. u8 doNotSpill; /* Do not spill the cache when non-zero */
  35517. u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
  35518. u8 subjInMemory; /* True to use in-memory sub-journals */
  35519. Pgno dbSize; /* Number of pages in the database */
  35520. Pgno dbOrigSize; /* dbSize before the current transaction */
  35521. Pgno dbFileSize; /* Number of pages in the database file */
  35522. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  35523. int errCode; /* One of several kinds of errors */
  35524. int nRec; /* Pages journalled since last j-header written */
  35525. u32 cksumInit; /* Quasi-random value added to every checksum */
  35526. u32 nSubRec; /* Number of records written to sub-journal */
  35527. Bitvec *pInJournal; /* One bit for each page in the database file */
  35528. sqlite3_file *fd; /* File descriptor for database */
  35529. sqlite3_file *jfd; /* File descriptor for main journal */
  35530. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  35531. i64 journalOff; /* Current write offset in the journal file */
  35532. i64 journalHdr; /* Byte offset to previous journal header */
  35533. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  35534. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  35535. int nSavepoint; /* Number of elements in aSavepoint[] */
  35536. char dbFileVers[16]; /* Changes whenever database file changes */
  35537. /*
  35538. ** End of the routinely-changing class members
  35539. ***************************************************************************/
  35540. u16 nExtra; /* Add this many bytes to each in-memory page */
  35541. i16 nReserve; /* Number of unused bytes at end of each page */
  35542. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  35543. u32 sectorSize; /* Assumed sector size during rollback */
  35544. int pageSize; /* Number of bytes in a page */
  35545. Pgno mxPgno; /* Maximum allowed size of the database */
  35546. i64 journalSizeLimit; /* Size limit for persistent journal files */
  35547. char *zFilename; /* Name of the database file */
  35548. char *zJournal; /* Name of the journal file */
  35549. int (*xBusyHandler)(void*); /* Function to call when busy */
  35550. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  35551. int aStat[3]; /* Total cache hits, misses and writes */
  35552. #ifdef SQLITE_TEST
  35553. int nRead; /* Database pages read */
  35554. #endif
  35555. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  35556. #ifdef SQLITE_HAS_CODEC
  35557. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  35558. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  35559. void (*xCodecFree)(void*); /* Destructor for the codec */
  35560. void *pCodec; /* First argument to xCodec... methods */
  35561. #endif
  35562. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  35563. PCache *pPCache; /* Pointer to page cache object */
  35564. #ifndef SQLITE_OMIT_WAL
  35565. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  35566. char *zWal; /* File name for write-ahead log */
  35567. #endif
  35568. };
  35569. /*
  35570. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  35571. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  35572. ** or CACHE_WRITE to sqlite3_db_status().
  35573. */
  35574. #define PAGER_STAT_HIT 0
  35575. #define PAGER_STAT_MISS 1
  35576. #define PAGER_STAT_WRITE 2
  35577. /*
  35578. ** The following global variables hold counters used for
  35579. ** testing purposes only. These variables do not exist in
  35580. ** a non-testing build. These variables are not thread-safe.
  35581. */
  35582. #ifdef SQLITE_TEST
  35583. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  35584. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  35585. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  35586. # define PAGER_INCR(v) v++
  35587. #else
  35588. # define PAGER_INCR(v)
  35589. #endif
  35590. /*
  35591. ** Journal files begin with the following magic string. The data
  35592. ** was obtained from /dev/random. It is used only as a sanity check.
  35593. **
  35594. ** Since version 2.8.0, the journal format contains additional sanity
  35595. ** checking information. If the power fails while the journal is being
  35596. ** written, semi-random garbage data might appear in the journal
  35597. ** file after power is restored. If an attempt is then made
  35598. ** to roll the journal back, the database could be corrupted. The additional
  35599. ** sanity checking data is an attempt to discover the garbage in the
  35600. ** journal and ignore it.
  35601. **
  35602. ** The sanity checking information for the new journal format consists
  35603. ** of a 32-bit checksum on each page of data. The checksum covers both
  35604. ** the page number and the pPager->pageSize bytes of data for the page.
  35605. ** This cksum is initialized to a 32-bit random value that appears in the
  35606. ** journal file right after the header. The random initializer is important,
  35607. ** because garbage data that appears at the end of a journal is likely
  35608. ** data that was once in other files that have now been deleted. If the
  35609. ** garbage data came from an obsolete journal file, the checksums might
  35610. ** be correct. But by initializing the checksum to random value which
  35611. ** is different for every journal, we minimize that risk.
  35612. */
  35613. static const unsigned char aJournalMagic[] = {
  35614. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  35615. };
  35616. /*
  35617. ** The size of the of each page record in the journal is given by
  35618. ** the following macro.
  35619. */
  35620. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  35621. /*
  35622. ** The journal header size for this pager. This is usually the same
  35623. ** size as a single disk sector. See also setSectorSize().
  35624. */
  35625. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  35626. /*
  35627. ** The macro MEMDB is true if we are dealing with an in-memory database.
  35628. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  35629. ** the value of MEMDB will be a constant and the compiler will optimize
  35630. ** out code that would never execute.
  35631. */
  35632. #ifdef SQLITE_OMIT_MEMORYDB
  35633. # define MEMDB 0
  35634. #else
  35635. # define MEMDB pPager->memDb
  35636. #endif
  35637. /*
  35638. ** The maximum legal page number is (2^31 - 1).
  35639. */
  35640. #define PAGER_MAX_PGNO 2147483647
  35641. /*
  35642. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  35643. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  35644. **
  35645. ** This is so that expressions can be written as:
  35646. **
  35647. ** if( isOpen(pPager->jfd) ){ ...
  35648. **
  35649. ** instead of
  35650. **
  35651. ** if( pPager->jfd->pMethods ){ ...
  35652. */
  35653. #define isOpen(pFd) ((pFd)->pMethods)
  35654. /*
  35655. ** Return true if this pager uses a write-ahead log instead of the usual
  35656. ** rollback journal. Otherwise false.
  35657. */
  35658. #ifndef SQLITE_OMIT_WAL
  35659. static int pagerUseWal(Pager *pPager){
  35660. return (pPager->pWal!=0);
  35661. }
  35662. #else
  35663. # define pagerUseWal(x) 0
  35664. # define pagerRollbackWal(x) 0
  35665. # define pagerWalFrames(v,w,x,y) 0
  35666. # define pagerOpenWalIfPresent(z) SQLITE_OK
  35667. # define pagerBeginReadTransaction(z) SQLITE_OK
  35668. #endif
  35669. #ifndef NDEBUG
  35670. /*
  35671. ** Usage:
  35672. **
  35673. ** assert( assert_pager_state(pPager) );
  35674. **
  35675. ** This function runs many asserts to try to find inconsistencies in
  35676. ** the internal state of the Pager object.
  35677. */
  35678. static int assert_pager_state(Pager *p){
  35679. Pager *pPager = p;
  35680. /* State must be valid. */
  35681. assert( p->eState==PAGER_OPEN
  35682. || p->eState==PAGER_READER
  35683. || p->eState==PAGER_WRITER_LOCKED
  35684. || p->eState==PAGER_WRITER_CACHEMOD
  35685. || p->eState==PAGER_WRITER_DBMOD
  35686. || p->eState==PAGER_WRITER_FINISHED
  35687. || p->eState==PAGER_ERROR
  35688. );
  35689. /* Regardless of the current state, a temp-file connection always behaves
  35690. ** as if it has an exclusive lock on the database file. It never updates
  35691. ** the change-counter field, so the changeCountDone flag is always set.
  35692. */
  35693. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  35694. assert( p->tempFile==0 || pPager->changeCountDone );
  35695. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  35696. ** And if the journal-mode is "OFF", the journal file must not be open.
  35697. */
  35698. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  35699. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  35700. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  35701. ** this means an in-memory pager performs no IO at all, it cannot encounter
  35702. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  35703. ** a journal file. (although the in-memory journal implementation may
  35704. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  35705. ** is therefore not possible for an in-memory pager to enter the ERROR
  35706. ** state.
  35707. */
  35708. if( MEMDB ){
  35709. assert( p->noSync );
  35710. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  35711. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  35712. );
  35713. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  35714. assert( pagerUseWal(p)==0 );
  35715. }
  35716. /* If changeCountDone is set, a RESERVED lock or greater must be held
  35717. ** on the file.
  35718. */
  35719. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  35720. assert( p->eLock!=PENDING_LOCK );
  35721. switch( p->eState ){
  35722. case PAGER_OPEN:
  35723. assert( !MEMDB );
  35724. assert( pPager->errCode==SQLITE_OK );
  35725. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  35726. break;
  35727. case PAGER_READER:
  35728. assert( pPager->errCode==SQLITE_OK );
  35729. assert( p->eLock!=UNKNOWN_LOCK );
  35730. assert( p->eLock>=SHARED_LOCK );
  35731. break;
  35732. case PAGER_WRITER_LOCKED:
  35733. assert( p->eLock!=UNKNOWN_LOCK );
  35734. assert( pPager->errCode==SQLITE_OK );
  35735. if( !pagerUseWal(pPager) ){
  35736. assert( p->eLock>=RESERVED_LOCK );
  35737. }
  35738. assert( pPager->dbSize==pPager->dbOrigSize );
  35739. assert( pPager->dbOrigSize==pPager->dbFileSize );
  35740. assert( pPager->dbOrigSize==pPager->dbHintSize );
  35741. assert( pPager->setMaster==0 );
  35742. break;
  35743. case PAGER_WRITER_CACHEMOD:
  35744. assert( p->eLock!=UNKNOWN_LOCK );
  35745. assert( pPager->errCode==SQLITE_OK );
  35746. if( !pagerUseWal(pPager) ){
  35747. /* It is possible that if journal_mode=wal here that neither the
  35748. ** journal file nor the WAL file are open. This happens during
  35749. ** a rollback transaction that switches from journal_mode=off
  35750. ** to journal_mode=wal.
  35751. */
  35752. assert( p->eLock>=RESERVED_LOCK );
  35753. assert( isOpen(p->jfd)
  35754. || p->journalMode==PAGER_JOURNALMODE_OFF
  35755. || p->journalMode==PAGER_JOURNALMODE_WAL
  35756. );
  35757. }
  35758. assert( pPager->dbOrigSize==pPager->dbFileSize );
  35759. assert( pPager->dbOrigSize==pPager->dbHintSize );
  35760. break;
  35761. case PAGER_WRITER_DBMOD:
  35762. assert( p->eLock==EXCLUSIVE_LOCK );
  35763. assert( pPager->errCode==SQLITE_OK );
  35764. assert( !pagerUseWal(pPager) );
  35765. assert( p->eLock>=EXCLUSIVE_LOCK );
  35766. assert( isOpen(p->jfd)
  35767. || p->journalMode==PAGER_JOURNALMODE_OFF
  35768. || p->journalMode==PAGER_JOURNALMODE_WAL
  35769. );
  35770. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  35771. break;
  35772. case PAGER_WRITER_FINISHED:
  35773. assert( p->eLock==EXCLUSIVE_LOCK );
  35774. assert( pPager->errCode==SQLITE_OK );
  35775. assert( !pagerUseWal(pPager) );
  35776. assert( isOpen(p->jfd)
  35777. || p->journalMode==PAGER_JOURNALMODE_OFF
  35778. || p->journalMode==PAGER_JOURNALMODE_WAL
  35779. );
  35780. break;
  35781. case PAGER_ERROR:
  35782. /* There must be at least one outstanding reference to the pager if
  35783. ** in ERROR state. Otherwise the pager should have already dropped
  35784. ** back to OPEN state.
  35785. */
  35786. assert( pPager->errCode!=SQLITE_OK );
  35787. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  35788. break;
  35789. }
  35790. return 1;
  35791. }
  35792. #endif /* ifndef NDEBUG */
  35793. #ifdef SQLITE_DEBUG
  35794. /*
  35795. ** Return a pointer to a human readable string in a static buffer
  35796. ** containing the state of the Pager object passed as an argument. This
  35797. ** is intended to be used within debuggers. For example, as an alternative
  35798. ** to "print *pPager" in gdb:
  35799. **
  35800. ** (gdb) printf "%s", print_pager_state(pPager)
  35801. */
  35802. static char *print_pager_state(Pager *p){
  35803. static char zRet[1024];
  35804. sqlite3_snprintf(1024, zRet,
  35805. "Filename: %s\n"
  35806. "State: %s errCode=%d\n"
  35807. "Lock: %s\n"
  35808. "Locking mode: locking_mode=%s\n"
  35809. "Journal mode: journal_mode=%s\n"
  35810. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  35811. "Journal: journalOff=%lld journalHdr=%lld\n"
  35812. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  35813. , p->zFilename
  35814. , p->eState==PAGER_OPEN ? "OPEN" :
  35815. p->eState==PAGER_READER ? "READER" :
  35816. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  35817. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  35818. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  35819. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  35820. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  35821. , (int)p->errCode
  35822. , p->eLock==NO_LOCK ? "NO_LOCK" :
  35823. p->eLock==RESERVED_LOCK ? "RESERVED" :
  35824. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  35825. p->eLock==SHARED_LOCK ? "SHARED" :
  35826. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  35827. , p->exclusiveMode ? "exclusive" : "normal"
  35828. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  35829. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  35830. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  35831. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  35832. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  35833. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  35834. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  35835. , p->journalOff, p->journalHdr
  35836. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  35837. );
  35838. return zRet;
  35839. }
  35840. #endif
  35841. /*
  35842. ** Return true if it is necessary to write page *pPg into the sub-journal.
  35843. ** A page needs to be written into the sub-journal if there exists one
  35844. ** or more open savepoints for which:
  35845. **
  35846. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  35847. ** * The bit corresponding to the page-number is not set in
  35848. ** PagerSavepoint.pInSavepoint.
  35849. */
  35850. static int subjRequiresPage(PgHdr *pPg){
  35851. Pgno pgno = pPg->pgno;
  35852. Pager *pPager = pPg->pPager;
  35853. int i;
  35854. for(i=0; i<pPager->nSavepoint; i++){
  35855. PagerSavepoint *p = &pPager->aSavepoint[i];
  35856. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  35857. return 1;
  35858. }
  35859. }
  35860. return 0;
  35861. }
  35862. /*
  35863. ** Return true if the page is already in the journal file.
  35864. */
  35865. static int pageInJournal(PgHdr *pPg){
  35866. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  35867. }
  35868. /*
  35869. ** Read a 32-bit integer from the given file descriptor. Store the integer
  35870. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  35871. ** error code is something goes wrong.
  35872. **
  35873. ** All values are stored on disk as big-endian.
  35874. */
  35875. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  35876. unsigned char ac[4];
  35877. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  35878. if( rc==SQLITE_OK ){
  35879. *pRes = sqlite3Get4byte(ac);
  35880. }
  35881. return rc;
  35882. }
  35883. /*
  35884. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  35885. */
  35886. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  35887. /*
  35888. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  35889. ** on success or an error code is something goes wrong.
  35890. */
  35891. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  35892. char ac[4];
  35893. put32bits(ac, val);
  35894. return sqlite3OsWrite(fd, ac, 4, offset);
  35895. }
  35896. /*
  35897. ** Unlock the database file to level eLock, which must be either NO_LOCK
  35898. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  35899. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  35900. **
  35901. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  35902. ** called, do not modify it. See the comment above the #define of
  35903. ** UNKNOWN_LOCK for an explanation of this.
  35904. */
  35905. static int pagerUnlockDb(Pager *pPager, int eLock){
  35906. int rc = SQLITE_OK;
  35907. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  35908. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  35909. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  35910. if( isOpen(pPager->fd) ){
  35911. assert( pPager->eLock>=eLock );
  35912. rc = sqlite3OsUnlock(pPager->fd, eLock);
  35913. if( pPager->eLock!=UNKNOWN_LOCK ){
  35914. pPager->eLock = (u8)eLock;
  35915. }
  35916. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  35917. }
  35918. return rc;
  35919. }
  35920. /*
  35921. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  35922. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  35923. ** Pager.eLock variable to the new locking state.
  35924. **
  35925. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  35926. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  35927. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  35928. ** of this.
  35929. */
  35930. static int pagerLockDb(Pager *pPager, int eLock){
  35931. int rc = SQLITE_OK;
  35932. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  35933. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  35934. rc = sqlite3OsLock(pPager->fd, eLock);
  35935. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  35936. pPager->eLock = (u8)eLock;
  35937. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  35938. }
  35939. }
  35940. return rc;
  35941. }
  35942. /*
  35943. ** This function determines whether or not the atomic-write optimization
  35944. ** can be used with this pager. The optimization can be used if:
  35945. **
  35946. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  35947. ** a database page may be written atomically, and
  35948. ** (b) the value returned by OsSectorSize() is less than or equal
  35949. ** to the page size.
  35950. **
  35951. ** The optimization is also always enabled for temporary files. It is
  35952. ** an error to call this function if pPager is opened on an in-memory
  35953. ** database.
  35954. **
  35955. ** If the optimization cannot be used, 0 is returned. If it can be used,
  35956. ** then the value returned is the size of the journal file when it
  35957. ** contains rollback data for exactly one page.
  35958. */
  35959. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  35960. static int jrnlBufferSize(Pager *pPager){
  35961. assert( !MEMDB );
  35962. if( !pPager->tempFile ){
  35963. int dc; /* Device characteristics */
  35964. int nSector; /* Sector size */
  35965. int szPage; /* Page size */
  35966. assert( isOpen(pPager->fd) );
  35967. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  35968. nSector = pPager->sectorSize;
  35969. szPage = pPager->pageSize;
  35970. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  35971. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  35972. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  35973. return 0;
  35974. }
  35975. }
  35976. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  35977. }
  35978. #endif
  35979. /*
  35980. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  35981. ** on the cache using a hash function. This is used for testing
  35982. ** and debugging only.
  35983. */
  35984. #ifdef SQLITE_CHECK_PAGES
  35985. /*
  35986. ** Return a 32-bit hash of the page data for pPage.
  35987. */
  35988. static u32 pager_datahash(int nByte, unsigned char *pData){
  35989. u32 hash = 0;
  35990. int i;
  35991. for(i=0; i<nByte; i++){
  35992. hash = (hash*1039) + pData[i];
  35993. }
  35994. return hash;
  35995. }
  35996. static u32 pager_pagehash(PgHdr *pPage){
  35997. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  35998. }
  35999. static void pager_set_pagehash(PgHdr *pPage){
  36000. pPage->pageHash = pager_pagehash(pPage);
  36001. }
  36002. /*
  36003. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  36004. ** is defined, and NDEBUG is not defined, an assert() statement checks
  36005. ** that the page is either dirty or still matches the calculated page-hash.
  36006. */
  36007. #define CHECK_PAGE(x) checkPage(x)
  36008. static void checkPage(PgHdr *pPg){
  36009. Pager *pPager = pPg->pPager;
  36010. assert( pPager->eState!=PAGER_ERROR );
  36011. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  36012. }
  36013. #else
  36014. #define pager_datahash(X,Y) 0
  36015. #define pager_pagehash(X) 0
  36016. #define pager_set_pagehash(X)
  36017. #define CHECK_PAGE(x)
  36018. #endif /* SQLITE_CHECK_PAGES */
  36019. /*
  36020. ** When this is called the journal file for pager pPager must be open.
  36021. ** This function attempts to read a master journal file name from the
  36022. ** end of the file and, if successful, copies it into memory supplied
  36023. ** by the caller. See comments above writeMasterJournal() for the format
  36024. ** used to store a master journal file name at the end of a journal file.
  36025. **
  36026. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  36027. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  36028. ** enough space to write the master journal name). If the master journal
  36029. ** name in the journal is longer than nMaster bytes (including a
  36030. ** nul-terminator), then this is handled as if no master journal name
  36031. ** were present in the journal.
  36032. **
  36033. ** If a master journal file name is present at the end of the journal
  36034. ** file, then it is copied into the buffer pointed to by zMaster. A
  36035. ** nul-terminator byte is appended to the buffer following the master
  36036. ** journal file name.
  36037. **
  36038. ** If it is determined that no master journal file name is present
  36039. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  36040. **
  36041. ** If an error occurs while reading from the journal file, an SQLite
  36042. ** error code is returned.
  36043. */
  36044. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  36045. int rc; /* Return code */
  36046. u32 len; /* Length in bytes of master journal name */
  36047. i64 szJ; /* Total size in bytes of journal file pJrnl */
  36048. u32 cksum; /* MJ checksum value read from journal */
  36049. u32 u; /* Unsigned loop counter */
  36050. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  36051. zMaster[0] = '\0';
  36052. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  36053. || szJ<16
  36054. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  36055. || len>=nMaster
  36056. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  36057. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  36058. || memcmp(aMagic, aJournalMagic, 8)
  36059. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  36060. ){
  36061. return rc;
  36062. }
  36063. /* See if the checksum matches the master journal name */
  36064. for(u=0; u<len; u++){
  36065. cksum -= zMaster[u];
  36066. }
  36067. if( cksum ){
  36068. /* If the checksum doesn't add up, then one or more of the disk sectors
  36069. ** containing the master journal filename is corrupted. This means
  36070. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  36071. ** master-journal filename.
  36072. */
  36073. len = 0;
  36074. }
  36075. zMaster[len] = '\0';
  36076. return SQLITE_OK;
  36077. }
  36078. /*
  36079. ** Return the offset of the sector boundary at or immediately
  36080. ** following the value in pPager->journalOff, assuming a sector
  36081. ** size of pPager->sectorSize bytes.
  36082. **
  36083. ** i.e for a sector size of 512:
  36084. **
  36085. ** Pager.journalOff Return value
  36086. ** ---------------------------------------
  36087. ** 0 0
  36088. ** 512 512
  36089. ** 100 512
  36090. ** 2000 2048
  36091. **
  36092. */
  36093. static i64 journalHdrOffset(Pager *pPager){
  36094. i64 offset = 0;
  36095. i64 c = pPager->journalOff;
  36096. if( c ){
  36097. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  36098. }
  36099. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  36100. assert( offset>=c );
  36101. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  36102. return offset;
  36103. }
  36104. /*
  36105. ** The journal file must be open when this function is called.
  36106. **
  36107. ** This function is a no-op if the journal file has not been written to
  36108. ** within the current transaction (i.e. if Pager.journalOff==0).
  36109. **
  36110. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  36111. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  36112. ** zero the 28-byte header at the start of the journal file. In either case,
  36113. ** if the pager is not in no-sync mode, sync the journal file immediately
  36114. ** after writing or truncating it.
  36115. **
  36116. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  36117. ** following the truncation or zeroing described above the size of the
  36118. ** journal file in bytes is larger than this value, then truncate the
  36119. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  36120. ** not need to be synced following this operation.
  36121. **
  36122. ** If an IO error occurs, abandon processing and return the IO error code.
  36123. ** Otherwise, return SQLITE_OK.
  36124. */
  36125. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  36126. int rc = SQLITE_OK; /* Return code */
  36127. assert( isOpen(pPager->jfd) );
  36128. if( pPager->journalOff ){
  36129. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  36130. IOTRACE(("JZEROHDR %p\n", pPager))
  36131. if( doTruncate || iLimit==0 ){
  36132. rc = sqlite3OsTruncate(pPager->jfd, 0);
  36133. }else{
  36134. static const char zeroHdr[28] = {0};
  36135. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  36136. }
  36137. if( rc==SQLITE_OK && !pPager->noSync ){
  36138. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  36139. }
  36140. /* At this point the transaction is committed but the write lock
  36141. ** is still held on the file. If there is a size limit configured for
  36142. ** the persistent journal and the journal file currently consumes more
  36143. ** space than that limit allows for, truncate it now. There is no need
  36144. ** to sync the file following this operation.
  36145. */
  36146. if( rc==SQLITE_OK && iLimit>0 ){
  36147. i64 sz;
  36148. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  36149. if( rc==SQLITE_OK && sz>iLimit ){
  36150. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  36151. }
  36152. }
  36153. }
  36154. return rc;
  36155. }
  36156. /*
  36157. ** The journal file must be open when this routine is called. A journal
  36158. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  36159. ** current location.
  36160. **
  36161. ** The format for the journal header is as follows:
  36162. ** - 8 bytes: Magic identifying journal format.
  36163. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  36164. ** - 4 bytes: Random number used for page hash.
  36165. ** - 4 bytes: Initial database page count.
  36166. ** - 4 bytes: Sector size used by the process that wrote this journal.
  36167. ** - 4 bytes: Database page size.
  36168. **
  36169. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  36170. */
  36171. static int writeJournalHdr(Pager *pPager){
  36172. int rc = SQLITE_OK; /* Return code */
  36173. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  36174. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  36175. u32 nWrite; /* Bytes of header sector written */
  36176. int ii; /* Loop counter */
  36177. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  36178. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  36179. nHeader = JOURNAL_HDR_SZ(pPager);
  36180. }
  36181. /* If there are active savepoints and any of them were created
  36182. ** since the most recent journal header was written, update the
  36183. ** PagerSavepoint.iHdrOffset fields now.
  36184. */
  36185. for(ii=0; ii<pPager->nSavepoint; ii++){
  36186. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  36187. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  36188. }
  36189. }
  36190. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  36191. /*
  36192. ** Write the nRec Field - the number of page records that follow this
  36193. ** journal header. Normally, zero is written to this value at this time.
  36194. ** After the records are added to the journal (and the journal synced,
  36195. ** if in full-sync mode), the zero is overwritten with the true number
  36196. ** of records (see syncJournal()).
  36197. **
  36198. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  36199. ** reading the journal this value tells SQLite to assume that the
  36200. ** rest of the journal file contains valid page records. This assumption
  36201. ** is dangerous, as if a failure occurred whilst writing to the journal
  36202. ** file it may contain some garbage data. There are two scenarios
  36203. ** where this risk can be ignored:
  36204. **
  36205. ** * When the pager is in no-sync mode. Corruption can follow a
  36206. ** power failure in this case anyway.
  36207. **
  36208. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  36209. ** that garbage data is never appended to the journal file.
  36210. */
  36211. assert( isOpen(pPager->fd) || pPager->noSync );
  36212. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  36213. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  36214. ){
  36215. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  36216. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  36217. }else{
  36218. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  36219. }
  36220. /* The random check-hash initialiser */
  36221. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  36222. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  36223. /* The initial database size */
  36224. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  36225. /* The assumed sector size for this process */
  36226. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  36227. /* The page size */
  36228. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  36229. /* Initializing the tail of the buffer is not necessary. Everything
  36230. ** works find if the following memset() is omitted. But initializing
  36231. ** the memory prevents valgrind from complaining, so we are willing to
  36232. ** take the performance hit.
  36233. */
  36234. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  36235. nHeader-(sizeof(aJournalMagic)+20));
  36236. /* In theory, it is only necessary to write the 28 bytes that the
  36237. ** journal header consumes to the journal file here. Then increment the
  36238. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  36239. ** record is written to the following sector (leaving a gap in the file
  36240. ** that will be implicitly filled in by the OS).
  36241. **
  36242. ** However it has been discovered that on some systems this pattern can
  36243. ** be significantly slower than contiguously writing data to the file,
  36244. ** even if that means explicitly writing data to the block of
  36245. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  36246. ** is done.
  36247. **
  36248. ** The loop is required here in case the sector-size is larger than the
  36249. ** database page size. Since the zHeader buffer is only Pager.pageSize
  36250. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  36251. ** to populate the entire journal header sector.
  36252. */
  36253. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  36254. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  36255. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  36256. assert( pPager->journalHdr <= pPager->journalOff );
  36257. pPager->journalOff += nHeader;
  36258. }
  36259. return rc;
  36260. }
  36261. /*
  36262. ** The journal file must be open when this is called. A journal header file
  36263. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  36264. ** file. The current location in the journal file is given by
  36265. ** pPager->journalOff. See comments above function writeJournalHdr() for
  36266. ** a description of the journal header format.
  36267. **
  36268. ** If the header is read successfully, *pNRec is set to the number of
  36269. ** page records following this header and *pDbSize is set to the size of the
  36270. ** database before the transaction began, in pages. Also, pPager->cksumInit
  36271. ** is set to the value read from the journal header. SQLITE_OK is returned
  36272. ** in this case.
  36273. **
  36274. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  36275. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  36276. ** cannot be read from the journal file an error code is returned.
  36277. */
  36278. static int readJournalHdr(
  36279. Pager *pPager, /* Pager object */
  36280. int isHot,
  36281. i64 journalSize, /* Size of the open journal file in bytes */
  36282. u32 *pNRec, /* OUT: Value read from the nRec field */
  36283. u32 *pDbSize /* OUT: Value of original database size field */
  36284. ){
  36285. int rc; /* Return code */
  36286. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  36287. i64 iHdrOff; /* Offset of journal header being read */
  36288. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  36289. /* Advance Pager.journalOff to the start of the next sector. If the
  36290. ** journal file is too small for there to be a header stored at this
  36291. ** point, return SQLITE_DONE.
  36292. */
  36293. pPager->journalOff = journalHdrOffset(pPager);
  36294. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  36295. return SQLITE_DONE;
  36296. }
  36297. iHdrOff = pPager->journalOff;
  36298. /* Read in the first 8 bytes of the journal header. If they do not match
  36299. ** the magic string found at the start of each journal header, return
  36300. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  36301. ** proceed.
  36302. */
  36303. if( isHot || iHdrOff!=pPager->journalHdr ){
  36304. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  36305. if( rc ){
  36306. return rc;
  36307. }
  36308. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  36309. return SQLITE_DONE;
  36310. }
  36311. }
  36312. /* Read the first three 32-bit fields of the journal header: The nRec
  36313. ** field, the checksum-initializer and the database size at the start
  36314. ** of the transaction. Return an error code if anything goes wrong.
  36315. */
  36316. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  36317. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  36318. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  36319. ){
  36320. return rc;
  36321. }
  36322. if( pPager->journalOff==0 ){
  36323. u32 iPageSize; /* Page-size field of journal header */
  36324. u32 iSectorSize; /* Sector-size field of journal header */
  36325. /* Read the page-size and sector-size journal header fields. */
  36326. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  36327. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  36328. ){
  36329. return rc;
  36330. }
  36331. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  36332. ** journal header to zero. In this case, assume that the Pager.pageSize
  36333. ** variable is already set to the correct page size.
  36334. */
  36335. if( iPageSize==0 ){
  36336. iPageSize = pPager->pageSize;
  36337. }
  36338. /* Check that the values read from the page-size and sector-size fields
  36339. ** are within range. To be 'in range', both values need to be a power
  36340. ** of two greater than or equal to 512 or 32, and not greater than their
  36341. ** respective compile time maximum limits.
  36342. */
  36343. if( iPageSize<512 || iSectorSize<32
  36344. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  36345. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  36346. ){
  36347. /* If the either the page-size or sector-size in the journal-header is
  36348. ** invalid, then the process that wrote the journal-header must have
  36349. ** crashed before the header was synced. In this case stop reading
  36350. ** the journal file here.
  36351. */
  36352. return SQLITE_DONE;
  36353. }
  36354. /* Update the page-size to match the value read from the journal.
  36355. ** Use a testcase() macro to make sure that malloc failure within
  36356. ** PagerSetPagesize() is tested.
  36357. */
  36358. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  36359. testcase( rc!=SQLITE_OK );
  36360. /* Update the assumed sector-size to match the value used by
  36361. ** the process that created this journal. If this journal was
  36362. ** created by a process other than this one, then this routine
  36363. ** is being called from within pager_playback(). The local value
  36364. ** of Pager.sectorSize is restored at the end of that routine.
  36365. */
  36366. pPager->sectorSize = iSectorSize;
  36367. }
  36368. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  36369. return rc;
  36370. }
  36371. /*
  36372. ** Write the supplied master journal name into the journal file for pager
  36373. ** pPager at the current location. The master journal name must be the last
  36374. ** thing written to a journal file. If the pager is in full-sync mode, the
  36375. ** journal file descriptor is advanced to the next sector boundary before
  36376. ** anything is written. The format is:
  36377. **
  36378. ** + 4 bytes: PAGER_MJ_PGNO.
  36379. ** + N bytes: Master journal filename in utf-8.
  36380. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  36381. ** + 4 bytes: Master journal name checksum.
  36382. ** + 8 bytes: aJournalMagic[].
  36383. **
  36384. ** The master journal page checksum is the sum of the bytes in the master
  36385. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  36386. **
  36387. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  36388. ** this call is a no-op.
  36389. */
  36390. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  36391. int rc; /* Return code */
  36392. int nMaster; /* Length of string zMaster */
  36393. i64 iHdrOff; /* Offset of header in journal file */
  36394. i64 jrnlSize; /* Size of journal file on disk */
  36395. u32 cksum = 0; /* Checksum of string zMaster */
  36396. assert( pPager->setMaster==0 );
  36397. assert( !pagerUseWal(pPager) );
  36398. if( !zMaster
  36399. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  36400. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  36401. ){
  36402. return SQLITE_OK;
  36403. }
  36404. pPager->setMaster = 1;
  36405. assert( isOpen(pPager->jfd) );
  36406. assert( pPager->journalHdr <= pPager->journalOff );
  36407. /* Calculate the length in bytes and the checksum of zMaster */
  36408. for(nMaster=0; zMaster[nMaster]; nMaster++){
  36409. cksum += zMaster[nMaster];
  36410. }
  36411. /* If in full-sync mode, advance to the next disk sector before writing
  36412. ** the master journal name. This is in case the previous page written to
  36413. ** the journal has already been synced.
  36414. */
  36415. if( pPager->fullSync ){
  36416. pPager->journalOff = journalHdrOffset(pPager);
  36417. }
  36418. iHdrOff = pPager->journalOff;
  36419. /* Write the master journal data to the end of the journal file. If
  36420. ** an error occurs, return the error code to the caller.
  36421. */
  36422. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  36423. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  36424. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  36425. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  36426. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  36427. ){
  36428. return rc;
  36429. }
  36430. pPager->journalOff += (nMaster+20);
  36431. /* If the pager is in peristent-journal mode, then the physical
  36432. ** journal-file may extend past the end of the master-journal name
  36433. ** and 8 bytes of magic data just written to the file. This is
  36434. ** dangerous because the code to rollback a hot-journal file
  36435. ** will not be able to find the master-journal name to determine
  36436. ** whether or not the journal is hot.
  36437. **
  36438. ** Easiest thing to do in this scenario is to truncate the journal
  36439. ** file to the required size.
  36440. */
  36441. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  36442. && jrnlSize>pPager->journalOff
  36443. ){
  36444. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  36445. }
  36446. return rc;
  36447. }
  36448. /*
  36449. ** Find a page in the hash table given its page number. Return
  36450. ** a pointer to the page or NULL if the requested page is not
  36451. ** already in memory.
  36452. */
  36453. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  36454. PgHdr *p; /* Return value */
  36455. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  36456. ** fail, since no attempt to allocate dynamic memory will be made.
  36457. */
  36458. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  36459. return p;
  36460. }
  36461. /*
  36462. ** Discard the entire contents of the in-memory page-cache.
  36463. */
  36464. static void pager_reset(Pager *pPager){
  36465. sqlite3BackupRestart(pPager->pBackup);
  36466. sqlite3PcacheClear(pPager->pPCache);
  36467. }
  36468. /*
  36469. ** Free all structures in the Pager.aSavepoint[] array and set both
  36470. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  36471. ** if it is open and the pager is not in exclusive mode.
  36472. */
  36473. static void releaseAllSavepoints(Pager *pPager){
  36474. int ii; /* Iterator for looping through Pager.aSavepoint */
  36475. for(ii=0; ii<pPager->nSavepoint; ii++){
  36476. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  36477. }
  36478. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  36479. sqlite3OsClose(pPager->sjfd);
  36480. }
  36481. sqlite3_free(pPager->aSavepoint);
  36482. pPager->aSavepoint = 0;
  36483. pPager->nSavepoint = 0;
  36484. pPager->nSubRec = 0;
  36485. }
  36486. /*
  36487. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  36488. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  36489. ** or SQLITE_NOMEM if a malloc failure occurs.
  36490. */
  36491. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  36492. int ii; /* Loop counter */
  36493. int rc = SQLITE_OK; /* Result code */
  36494. for(ii=0; ii<pPager->nSavepoint; ii++){
  36495. PagerSavepoint *p = &pPager->aSavepoint[ii];
  36496. if( pgno<=p->nOrig ){
  36497. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  36498. testcase( rc==SQLITE_NOMEM );
  36499. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  36500. }
  36501. }
  36502. return rc;
  36503. }
  36504. /*
  36505. ** This function is a no-op if the pager is in exclusive mode and not
  36506. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  36507. ** state.
  36508. **
  36509. ** If the pager is not in exclusive-access mode, the database file is
  36510. ** completely unlocked. If the file is unlocked and the file-system does
  36511. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  36512. ** closed (if it is open).
  36513. **
  36514. ** If the pager is in ERROR state when this function is called, the
  36515. ** contents of the pager cache are discarded before switching back to
  36516. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  36517. ** or not, any journal file left in the file-system will be treated
  36518. ** as a hot-journal and rolled back the next time a read-transaction
  36519. ** is opened (by this or by any other connection).
  36520. */
  36521. static void pager_unlock(Pager *pPager){
  36522. assert( pPager->eState==PAGER_READER
  36523. || pPager->eState==PAGER_OPEN
  36524. || pPager->eState==PAGER_ERROR
  36525. );
  36526. sqlite3BitvecDestroy(pPager->pInJournal);
  36527. pPager->pInJournal = 0;
  36528. releaseAllSavepoints(pPager);
  36529. if( pagerUseWal(pPager) ){
  36530. assert( !isOpen(pPager->jfd) );
  36531. sqlite3WalEndReadTransaction(pPager->pWal);
  36532. pPager->eState = PAGER_OPEN;
  36533. }else if( !pPager->exclusiveMode ){
  36534. int rc; /* Error code returned by pagerUnlockDb() */
  36535. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  36536. /* If the operating system support deletion of open files, then
  36537. ** close the journal file when dropping the database lock. Otherwise
  36538. ** another connection with journal_mode=delete might delete the file
  36539. ** out from under us.
  36540. */
  36541. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  36542. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  36543. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  36544. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  36545. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  36546. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  36547. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  36548. || 1!=(pPager->journalMode & 5)
  36549. ){
  36550. sqlite3OsClose(pPager->jfd);
  36551. }
  36552. /* If the pager is in the ERROR state and the call to unlock the database
  36553. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  36554. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  36555. ** is necessary.
  36556. */
  36557. rc = pagerUnlockDb(pPager, NO_LOCK);
  36558. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  36559. pPager->eLock = UNKNOWN_LOCK;
  36560. }
  36561. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  36562. ** without clearing the error code. This is intentional - the error
  36563. ** code is cleared and the cache reset in the block below.
  36564. */
  36565. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  36566. pPager->changeCountDone = 0;
  36567. pPager->eState = PAGER_OPEN;
  36568. }
  36569. /* If Pager.errCode is set, the contents of the pager cache cannot be
  36570. ** trusted. Now that there are no outstanding references to the pager,
  36571. ** it can safely move back to PAGER_OPEN state. This happens in both
  36572. ** normal and exclusive-locking mode.
  36573. */
  36574. if( pPager->errCode ){
  36575. assert( !MEMDB );
  36576. pager_reset(pPager);
  36577. pPager->changeCountDone = pPager->tempFile;
  36578. pPager->eState = PAGER_OPEN;
  36579. pPager->errCode = SQLITE_OK;
  36580. }
  36581. pPager->journalOff = 0;
  36582. pPager->journalHdr = 0;
  36583. pPager->setMaster = 0;
  36584. }
  36585. /*
  36586. ** This function is called whenever an IOERR or FULL error that requires
  36587. ** the pager to transition into the ERROR state may ahve occurred.
  36588. ** The first argument is a pointer to the pager structure, the second
  36589. ** the error-code about to be returned by a pager API function. The
  36590. ** value returned is a copy of the second argument to this function.
  36591. **
  36592. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  36593. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  36594. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  36595. ** all major API calls on the Pager will immediately return Pager.errCode.
  36596. **
  36597. ** The ERROR state indicates that the contents of the pager-cache
  36598. ** cannot be trusted. This state can be cleared by completely discarding
  36599. ** the contents of the pager-cache. If a transaction was active when
  36600. ** the persistent error occurred, then the rollback journal may need
  36601. ** to be replayed to restore the contents of the database file (as if
  36602. ** it were a hot-journal).
  36603. */
  36604. static int pager_error(Pager *pPager, int rc){
  36605. int rc2 = rc & 0xff;
  36606. assert( rc==SQLITE_OK || !MEMDB );
  36607. assert(
  36608. pPager->errCode==SQLITE_FULL ||
  36609. pPager->errCode==SQLITE_OK ||
  36610. (pPager->errCode & 0xff)==SQLITE_IOERR
  36611. );
  36612. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  36613. pPager->errCode = rc;
  36614. pPager->eState = PAGER_ERROR;
  36615. }
  36616. return rc;
  36617. }
  36618. /*
  36619. ** This routine ends a transaction. A transaction is usually ended by
  36620. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  36621. ** after rollback of a hot-journal, or if an error occurs while opening
  36622. ** the journal file or writing the very first journal-header of a
  36623. ** database transaction.
  36624. **
  36625. ** This routine is never called in PAGER_ERROR state. If it is called
  36626. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  36627. ** exclusive than a RESERVED lock, it is a no-op.
  36628. **
  36629. ** Otherwise, any active savepoints are released.
  36630. **
  36631. ** If the journal file is open, then it is "finalized". Once a journal
  36632. ** file has been finalized it is not possible to use it to roll back a
  36633. ** transaction. Nor will it be considered to be a hot-journal by this
  36634. ** or any other database connection. Exactly how a journal is finalized
  36635. ** depends on whether or not the pager is running in exclusive mode and
  36636. ** the current journal-mode (Pager.journalMode value), as follows:
  36637. **
  36638. ** journalMode==MEMORY
  36639. ** Journal file descriptor is simply closed. This destroys an
  36640. ** in-memory journal.
  36641. **
  36642. ** journalMode==TRUNCATE
  36643. ** Journal file is truncated to zero bytes in size.
  36644. **
  36645. ** journalMode==PERSIST
  36646. ** The first 28 bytes of the journal file are zeroed. This invalidates
  36647. ** the first journal header in the file, and hence the entire journal
  36648. ** file. An invalid journal file cannot be rolled back.
  36649. **
  36650. ** journalMode==DELETE
  36651. ** The journal file is closed and deleted using sqlite3OsDelete().
  36652. **
  36653. ** If the pager is running in exclusive mode, this method of finalizing
  36654. ** the journal file is never used. Instead, if the journalMode is
  36655. ** DELETE and the pager is in exclusive mode, the method described under
  36656. ** journalMode==PERSIST is used instead.
  36657. **
  36658. ** After the journal is finalized, the pager moves to PAGER_READER state.
  36659. ** If running in non-exclusive rollback mode, the lock on the file is
  36660. ** downgraded to a SHARED_LOCK.
  36661. **
  36662. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  36663. ** any of the IO operations to finalize the journal file or unlock the
  36664. ** database then the IO error code is returned to the user. If the
  36665. ** operation to finalize the journal file fails, then the code still
  36666. ** tries to unlock the database file if not in exclusive mode. If the
  36667. ** unlock operation fails as well, then the first error code related
  36668. ** to the first error encountered (the journal finalization one) is
  36669. ** returned.
  36670. */
  36671. static int pager_end_transaction(Pager *pPager, int hasMaster){
  36672. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  36673. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  36674. /* Do nothing if the pager does not have an open write transaction
  36675. ** or at least a RESERVED lock. This function may be called when there
  36676. ** is no write-transaction active but a RESERVED or greater lock is
  36677. ** held under two circumstances:
  36678. **
  36679. ** 1. After a successful hot-journal rollback, it is called with
  36680. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  36681. **
  36682. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  36683. ** lock switches back to locking_mode=normal and then executes a
  36684. ** read-transaction, this function is called with eState==PAGER_READER
  36685. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  36686. */
  36687. assert( assert_pager_state(pPager) );
  36688. assert( pPager->eState!=PAGER_ERROR );
  36689. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  36690. return SQLITE_OK;
  36691. }
  36692. releaseAllSavepoints(pPager);
  36693. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  36694. if( isOpen(pPager->jfd) ){
  36695. assert( !pagerUseWal(pPager) );
  36696. /* Finalize the journal file. */
  36697. if( sqlite3IsMemJournal(pPager->jfd) ){
  36698. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  36699. sqlite3OsClose(pPager->jfd);
  36700. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  36701. if( pPager->journalOff==0 ){
  36702. rc = SQLITE_OK;
  36703. }else{
  36704. rc = sqlite3OsTruncate(pPager->jfd, 0);
  36705. }
  36706. pPager->journalOff = 0;
  36707. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  36708. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  36709. ){
  36710. rc = zeroJournalHdr(pPager, hasMaster);
  36711. pPager->journalOff = 0;
  36712. }else{
  36713. /* This branch may be executed with Pager.journalMode==MEMORY if
  36714. ** a hot-journal was just rolled back. In this case the journal
  36715. ** file should be closed and deleted. If this connection writes to
  36716. ** the database file, it will do so using an in-memory journal.
  36717. */
  36718. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  36719. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  36720. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  36721. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  36722. );
  36723. sqlite3OsClose(pPager->jfd);
  36724. if( bDelete ){
  36725. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  36726. }
  36727. }
  36728. }
  36729. #ifdef SQLITE_CHECK_PAGES
  36730. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  36731. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  36732. PgHdr *p = pager_lookup(pPager, 1);
  36733. if( p ){
  36734. p->pageHash = 0;
  36735. sqlite3PagerUnref(p);
  36736. }
  36737. }
  36738. #endif
  36739. sqlite3BitvecDestroy(pPager->pInJournal);
  36740. pPager->pInJournal = 0;
  36741. pPager->nRec = 0;
  36742. sqlite3PcacheCleanAll(pPager->pPCache);
  36743. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  36744. if( pagerUseWal(pPager) ){
  36745. /* Drop the WAL write-lock, if any. Also, if the connection was in
  36746. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  36747. ** lock held on the database file.
  36748. */
  36749. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  36750. assert( rc2==SQLITE_OK );
  36751. }
  36752. if( !pPager->exclusiveMode
  36753. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  36754. ){
  36755. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  36756. pPager->changeCountDone = 0;
  36757. }
  36758. pPager->eState = PAGER_READER;
  36759. pPager->setMaster = 0;
  36760. return (rc==SQLITE_OK?rc2:rc);
  36761. }
  36762. /*
  36763. ** Execute a rollback if a transaction is active and unlock the
  36764. ** database file.
  36765. **
  36766. ** If the pager has already entered the ERROR state, do not attempt
  36767. ** the rollback at this time. Instead, pager_unlock() is called. The
  36768. ** call to pager_unlock() will discard all in-memory pages, unlock
  36769. ** the database file and move the pager back to OPEN state. If this
  36770. ** means that there is a hot-journal left in the file-system, the next
  36771. ** connection to obtain a shared lock on the pager (which may be this one)
  36772. ** will roll it back.
  36773. **
  36774. ** If the pager has not already entered the ERROR state, but an IO or
  36775. ** malloc error occurs during a rollback, then this will itself cause
  36776. ** the pager to enter the ERROR state. Which will be cleared by the
  36777. ** call to pager_unlock(), as described above.
  36778. */
  36779. static void pagerUnlockAndRollback(Pager *pPager){
  36780. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  36781. assert( assert_pager_state(pPager) );
  36782. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  36783. sqlite3BeginBenignMalloc();
  36784. sqlite3PagerRollback(pPager);
  36785. sqlite3EndBenignMalloc();
  36786. }else if( !pPager->exclusiveMode ){
  36787. assert( pPager->eState==PAGER_READER );
  36788. pager_end_transaction(pPager, 0);
  36789. }
  36790. }
  36791. pager_unlock(pPager);
  36792. }
  36793. /*
  36794. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  36795. ** of data. Compute and return a checksum based ont the contents of the
  36796. ** page of data and the current value of pPager->cksumInit.
  36797. **
  36798. ** This is not a real checksum. It is really just the sum of the
  36799. ** random initial value (pPager->cksumInit) and every 200th byte
  36800. ** of the page data, starting with byte offset (pPager->pageSize%200).
  36801. ** Each byte is interpreted as an 8-bit unsigned integer.
  36802. **
  36803. ** Changing the formula used to compute this checksum results in an
  36804. ** incompatible journal file format.
  36805. **
  36806. ** If journal corruption occurs due to a power failure, the most likely
  36807. ** scenario is that one end or the other of the record will be changed.
  36808. ** It is much less likely that the two ends of the journal record will be
  36809. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  36810. ** though fast and simple, catches the mostly likely kind of corruption.
  36811. */
  36812. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  36813. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  36814. int i = pPager->pageSize-200; /* Loop counter */
  36815. while( i>0 ){
  36816. cksum += aData[i];
  36817. i -= 200;
  36818. }
  36819. return cksum;
  36820. }
  36821. /*
  36822. ** Report the current page size and number of reserved bytes back
  36823. ** to the codec.
  36824. */
  36825. #ifdef SQLITE_HAS_CODEC
  36826. static void pagerReportSize(Pager *pPager){
  36827. if( pPager->xCodecSizeChng ){
  36828. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  36829. (int)pPager->nReserve);
  36830. }
  36831. }
  36832. #else
  36833. # define pagerReportSize(X) /* No-op if we do not support a codec */
  36834. #endif
  36835. /*
  36836. ** Read a single page from either the journal file (if isMainJrnl==1) or
  36837. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  36838. ** The page begins at offset *pOffset into the file. The *pOffset
  36839. ** value is increased to the start of the next page in the journal.
  36840. **
  36841. ** The main rollback journal uses checksums - the statement journal does
  36842. ** not.
  36843. **
  36844. ** If the page number of the page record read from the (sub-)journal file
  36845. ** is greater than the current value of Pager.dbSize, then playback is
  36846. ** skipped and SQLITE_OK is returned.
  36847. **
  36848. ** If pDone is not NULL, then it is a record of pages that have already
  36849. ** been played back. If the page at *pOffset has already been played back
  36850. ** (if the corresponding pDone bit is set) then skip the playback.
  36851. ** Make sure the pDone bit corresponding to the *pOffset page is set
  36852. ** prior to returning.
  36853. **
  36854. ** If the page record is successfully read from the (sub-)journal file
  36855. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  36856. ** while reading the record from the (sub-)journal file or while writing
  36857. ** to the database file, then the IO error code is returned. If data
  36858. ** is successfully read from the (sub-)journal file but appears to be
  36859. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  36860. ** two circumstances:
  36861. **
  36862. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  36863. ** * If the record is being rolled back from the main journal file
  36864. ** and the checksum field does not match the record content.
  36865. **
  36866. ** Neither of these two scenarios are possible during a savepoint rollback.
  36867. **
  36868. ** If this is a savepoint rollback, then memory may have to be dynamically
  36869. ** allocated by this function. If this is the case and an allocation fails,
  36870. ** SQLITE_NOMEM is returned.
  36871. */
  36872. static int pager_playback_one_page(
  36873. Pager *pPager, /* The pager being played back */
  36874. i64 *pOffset, /* Offset of record to playback */
  36875. Bitvec *pDone, /* Bitvec of pages already played back */
  36876. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  36877. int isSavepnt /* True for a savepoint rollback */
  36878. ){
  36879. int rc;
  36880. PgHdr *pPg; /* An existing page in the cache */
  36881. Pgno pgno; /* The page number of a page in journal */
  36882. u32 cksum; /* Checksum used for sanity checking */
  36883. char *aData; /* Temporary storage for the page */
  36884. sqlite3_file *jfd; /* The file descriptor for the journal file */
  36885. int isSynced; /* True if journal page is synced */
  36886. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  36887. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  36888. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  36889. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  36890. aData = pPager->pTmpSpace;
  36891. assert( aData ); /* Temp storage must have already been allocated */
  36892. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  36893. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  36894. ** or savepoint rollback done at the request of the caller) or this is
  36895. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  36896. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  36897. ** only reads from the main journal, not the sub-journal.
  36898. */
  36899. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  36900. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  36901. );
  36902. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  36903. /* Read the page number and page data from the journal or sub-journal
  36904. ** file. Return an error code to the caller if an IO error occurs.
  36905. */
  36906. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  36907. rc = read32bits(jfd, *pOffset, &pgno);
  36908. if( rc!=SQLITE_OK ) return rc;
  36909. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  36910. if( rc!=SQLITE_OK ) return rc;
  36911. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  36912. /* Sanity checking on the page. This is more important that I originally
  36913. ** thought. If a power failure occurs while the journal is being written,
  36914. ** it could cause invalid data to be written into the journal. We need to
  36915. ** detect this invalid data (with high probability) and ignore it.
  36916. */
  36917. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  36918. assert( !isSavepnt );
  36919. return SQLITE_DONE;
  36920. }
  36921. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  36922. return SQLITE_OK;
  36923. }
  36924. if( isMainJrnl ){
  36925. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  36926. if( rc ) return rc;
  36927. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  36928. return SQLITE_DONE;
  36929. }
  36930. }
  36931. /* If this page has already been played by before during the current
  36932. ** rollback, then don't bother to play it back again.
  36933. */
  36934. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  36935. return rc;
  36936. }
  36937. /* When playing back page 1, restore the nReserve setting
  36938. */
  36939. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  36940. pPager->nReserve = ((u8*)aData)[20];
  36941. pagerReportSize(pPager);
  36942. }
  36943. /* If the pager is in CACHEMOD state, then there must be a copy of this
  36944. ** page in the pager cache. In this case just update the pager cache,
  36945. ** not the database file. The page is left marked dirty in this case.
  36946. **
  36947. ** An exception to the above rule: If the database is in no-sync mode
  36948. ** and a page is moved during an incremental vacuum then the page may
  36949. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  36950. ** during a Movepage() call, then the page may not be in the cache
  36951. ** either. So the condition described in the above paragraph is not
  36952. ** assert()able.
  36953. **
  36954. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  36955. ** pager cache if it exists and the main file. The page is then marked
  36956. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  36957. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  36958. ** if the pager is in OPEN state.
  36959. **
  36960. ** Ticket #1171: The statement journal might contain page content that is
  36961. ** different from the page content at the start of the transaction.
  36962. ** This occurs when a page is changed prior to the start of a statement
  36963. ** then changed again within the statement. When rolling back such a
  36964. ** statement we must not write to the original database unless we know
  36965. ** for certain that original page contents are synced into the main rollback
  36966. ** journal. Otherwise, a power loss might leave modified data in the
  36967. ** database file without an entry in the rollback journal that can
  36968. ** restore the database to its original form. Two conditions must be
  36969. ** met before writing to the database files. (1) the database must be
  36970. ** locked. (2) we know that the original page content is fully synced
  36971. ** in the main journal either because the page is not in cache or else
  36972. ** the page is marked as needSync==0.
  36973. **
  36974. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  36975. ** is possible to fail a statement on a database that does not yet exist.
  36976. ** Do not attempt to write if database file has never been opened.
  36977. */
  36978. if( pagerUseWal(pPager) ){
  36979. pPg = 0;
  36980. }else{
  36981. pPg = pager_lookup(pPager, pgno);
  36982. }
  36983. assert( pPg || !MEMDB );
  36984. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  36985. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  36986. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  36987. (isMainJrnl?"main-journal":"sub-journal")
  36988. ));
  36989. if( isMainJrnl ){
  36990. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  36991. }else{
  36992. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  36993. }
  36994. if( isOpen(pPager->fd)
  36995. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  36996. && isSynced
  36997. ){
  36998. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  36999. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  37000. assert( !pagerUseWal(pPager) );
  37001. rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
  37002. if( pgno>pPager->dbFileSize ){
  37003. pPager->dbFileSize = pgno;
  37004. }
  37005. if( pPager->pBackup ){
  37006. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  37007. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  37008. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  37009. }
  37010. }else if( !isMainJrnl && pPg==0 ){
  37011. /* If this is a rollback of a savepoint and data was not written to
  37012. ** the database and the page is not in-memory, there is a potential
  37013. ** problem. When the page is next fetched by the b-tree layer, it
  37014. ** will be read from the database file, which may or may not be
  37015. ** current.
  37016. **
  37017. ** There are a couple of different ways this can happen. All are quite
  37018. ** obscure. When running in synchronous mode, this can only happen
  37019. ** if the page is on the free-list at the start of the transaction, then
  37020. ** populated, then moved using sqlite3PagerMovepage().
  37021. **
  37022. ** The solution is to add an in-memory page to the cache containing
  37023. ** the data just read from the sub-journal. Mark the page as dirty
  37024. ** and if the pager requires a journal-sync, then mark the page as
  37025. ** requiring a journal-sync before it is written.
  37026. */
  37027. assert( isSavepnt );
  37028. assert( pPager->doNotSpill==0 );
  37029. pPager->doNotSpill++;
  37030. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  37031. assert( pPager->doNotSpill==1 );
  37032. pPager->doNotSpill--;
  37033. if( rc!=SQLITE_OK ) return rc;
  37034. pPg->flags &= ~PGHDR_NEED_READ;
  37035. sqlite3PcacheMakeDirty(pPg);
  37036. }
  37037. if( pPg ){
  37038. /* No page should ever be explicitly rolled back that is in use, except
  37039. ** for page 1 which is held in use in order to keep the lock on the
  37040. ** database active. However such a page may be rolled back as a result
  37041. ** of an internal error resulting in an automatic call to
  37042. ** sqlite3PagerRollback().
  37043. */
  37044. void *pData;
  37045. pData = pPg->pData;
  37046. memcpy(pData, (u8*)aData, pPager->pageSize);
  37047. pPager->xReiniter(pPg);
  37048. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  37049. /* If the contents of this page were just restored from the main
  37050. ** journal file, then its content must be as they were when the
  37051. ** transaction was first opened. In this case we can mark the page
  37052. ** as clean, since there will be no need to write it out to the
  37053. ** database.
  37054. **
  37055. ** There is one exception to this rule. If the page is being rolled
  37056. ** back as part of a savepoint (or statement) rollback from an
  37057. ** unsynced portion of the main journal file, then it is not safe
  37058. ** to mark the page as clean. This is because marking the page as
  37059. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  37060. ** already in the journal file (recorded in Pager.pInJournal) and
  37061. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  37062. ** again within this transaction, it will be marked as dirty but
  37063. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  37064. ** be written out into the database file before its journal file
  37065. ** segment is synced. If a crash occurs during or following this,
  37066. ** database corruption may ensue.
  37067. */
  37068. assert( !pagerUseWal(pPager) );
  37069. sqlite3PcacheMakeClean(pPg);
  37070. }
  37071. pager_set_pagehash(pPg);
  37072. /* If this was page 1, then restore the value of Pager.dbFileVers.
  37073. ** Do this before any decoding. */
  37074. if( pgno==1 ){
  37075. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  37076. }
  37077. /* Decode the page just read from disk */
  37078. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  37079. sqlite3PcacheRelease(pPg);
  37080. }
  37081. return rc;
  37082. }
  37083. /*
  37084. ** Parameter zMaster is the name of a master journal file. A single journal
  37085. ** file that referred to the master journal file has just been rolled back.
  37086. ** This routine checks if it is possible to delete the master journal file,
  37087. ** and does so if it is.
  37088. **
  37089. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  37090. ** available for use within this function.
  37091. **
  37092. ** When a master journal file is created, it is populated with the names
  37093. ** of all of its child journals, one after another, formatted as utf-8
  37094. ** encoded text. The end of each child journal file is marked with a
  37095. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  37096. ** file for a transaction involving two databases might be:
  37097. **
  37098. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  37099. **
  37100. ** A master journal file may only be deleted once all of its child
  37101. ** journals have been rolled back.
  37102. **
  37103. ** This function reads the contents of the master-journal file into
  37104. ** memory and loops through each of the child journal names. For
  37105. ** each child journal, it checks if:
  37106. **
  37107. ** * if the child journal exists, and if so
  37108. ** * if the child journal contains a reference to master journal
  37109. ** file zMaster
  37110. **
  37111. ** If a child journal can be found that matches both of the criteria
  37112. ** above, this function returns without doing anything. Otherwise, if
  37113. ** no such child journal can be found, file zMaster is deleted from
  37114. ** the file-system using sqlite3OsDelete().
  37115. **
  37116. ** If an IO error within this function, an error code is returned. This
  37117. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  37118. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  37119. ** occur, SQLITE_OK is returned.
  37120. **
  37121. ** TODO: This function allocates a single block of memory to load
  37122. ** the entire contents of the master journal file. This could be
  37123. ** a couple of kilobytes or so - potentially larger than the page
  37124. ** size.
  37125. */
  37126. static int pager_delmaster(Pager *pPager, const char *zMaster){
  37127. sqlite3_vfs *pVfs = pPager->pVfs;
  37128. int rc; /* Return code */
  37129. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  37130. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  37131. char *zMasterJournal = 0; /* Contents of master journal file */
  37132. i64 nMasterJournal; /* Size of master journal file */
  37133. char *zJournal; /* Pointer to one journal within MJ file */
  37134. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  37135. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  37136. /* Allocate space for both the pJournal and pMaster file descriptors.
  37137. ** If successful, open the master journal file for reading.
  37138. */
  37139. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  37140. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  37141. if( !pMaster ){
  37142. rc = SQLITE_NOMEM;
  37143. }else{
  37144. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  37145. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  37146. }
  37147. if( rc!=SQLITE_OK ) goto delmaster_out;
  37148. /* Load the entire master journal file into space obtained from
  37149. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  37150. ** sufficient space (in zMasterPtr) to hold the names of master
  37151. ** journal files extracted from regular rollback-journals.
  37152. */
  37153. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  37154. if( rc!=SQLITE_OK ) goto delmaster_out;
  37155. nMasterPtr = pVfs->mxPathname+1;
  37156. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  37157. if( !zMasterJournal ){
  37158. rc = SQLITE_NOMEM;
  37159. goto delmaster_out;
  37160. }
  37161. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  37162. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  37163. if( rc!=SQLITE_OK ) goto delmaster_out;
  37164. zMasterJournal[nMasterJournal] = 0;
  37165. zJournal = zMasterJournal;
  37166. while( (zJournal-zMasterJournal)<nMasterJournal ){
  37167. int exists;
  37168. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  37169. if( rc!=SQLITE_OK ){
  37170. goto delmaster_out;
  37171. }
  37172. if( exists ){
  37173. /* One of the journals pointed to by the master journal exists.
  37174. ** Open it and check if it points at the master journal. If
  37175. ** so, return without deleting the master journal file.
  37176. */
  37177. int c;
  37178. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  37179. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  37180. if( rc!=SQLITE_OK ){
  37181. goto delmaster_out;
  37182. }
  37183. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  37184. sqlite3OsClose(pJournal);
  37185. if( rc!=SQLITE_OK ){
  37186. goto delmaster_out;
  37187. }
  37188. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  37189. if( c ){
  37190. /* We have a match. Do not delete the master journal file. */
  37191. goto delmaster_out;
  37192. }
  37193. }
  37194. zJournal += (sqlite3Strlen30(zJournal)+1);
  37195. }
  37196. sqlite3OsClose(pMaster);
  37197. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  37198. delmaster_out:
  37199. sqlite3_free(zMasterJournal);
  37200. if( pMaster ){
  37201. sqlite3OsClose(pMaster);
  37202. assert( !isOpen(pJournal) );
  37203. sqlite3_free(pMaster);
  37204. }
  37205. return rc;
  37206. }
  37207. /*
  37208. ** This function is used to change the actual size of the database
  37209. ** file in the file-system. This only happens when committing a transaction,
  37210. ** or rolling back a transaction (including rolling back a hot-journal).
  37211. **
  37212. ** If the main database file is not open, or the pager is not in either
  37213. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  37214. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  37215. ** If the file on disk is currently larger than nPage pages, then use the VFS
  37216. ** xTruncate() method to truncate it.
  37217. **
  37218. ** Or, it might might be the case that the file on disk is smaller than
  37219. ** nPage pages. Some operating system implementations can get confused if
  37220. ** you try to truncate a file to some size that is larger than it
  37221. ** currently is, so detect this case and write a single zero byte to
  37222. ** the end of the new file instead.
  37223. **
  37224. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  37225. ** the database file, return the error code to the caller.
  37226. */
  37227. static int pager_truncate(Pager *pPager, Pgno nPage){
  37228. int rc = SQLITE_OK;
  37229. assert( pPager->eState!=PAGER_ERROR );
  37230. assert( pPager->eState!=PAGER_READER );
  37231. if( isOpen(pPager->fd)
  37232. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  37233. ){
  37234. i64 currentSize, newSize;
  37235. int szPage = pPager->pageSize;
  37236. assert( pPager->eLock==EXCLUSIVE_LOCK );
  37237. /* TODO: Is it safe to use Pager.dbFileSize here? */
  37238. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  37239. newSize = szPage*(i64)nPage;
  37240. if( rc==SQLITE_OK && currentSize!=newSize ){
  37241. if( currentSize>newSize ){
  37242. rc = sqlite3OsTruncate(pPager->fd, newSize);
  37243. }else if( (currentSize+szPage)<=newSize ){
  37244. char *pTmp = pPager->pTmpSpace;
  37245. memset(pTmp, 0, szPage);
  37246. testcase( (newSize-szPage) == currentSize );
  37247. testcase( (newSize-szPage) > currentSize );
  37248. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  37249. }
  37250. if( rc==SQLITE_OK ){
  37251. pPager->dbFileSize = nPage;
  37252. }
  37253. }
  37254. }
  37255. return rc;
  37256. }
  37257. /*
  37258. ** Return a sanitized version of the sector-size of OS file pFile. The
  37259. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  37260. */
  37261. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  37262. int iRet = sqlite3OsSectorSize(pFile);
  37263. if( iRet<32 ){
  37264. iRet = 512;
  37265. }else if( iRet>MAX_SECTOR_SIZE ){
  37266. assert( MAX_SECTOR_SIZE>=512 );
  37267. iRet = MAX_SECTOR_SIZE;
  37268. }
  37269. return iRet;
  37270. }
  37271. /*
  37272. ** Set the value of the Pager.sectorSize variable for the given
  37273. ** pager based on the value returned by the xSectorSize method
  37274. ** of the open database file. The sector size will be used used
  37275. ** to determine the size and alignment of journal header and
  37276. ** master journal pointers within created journal files.
  37277. **
  37278. ** For temporary files the effective sector size is always 512 bytes.
  37279. **
  37280. ** Otherwise, for non-temporary files, the effective sector size is
  37281. ** the value returned by the xSectorSize() method rounded up to 32 if
  37282. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  37283. ** is greater than MAX_SECTOR_SIZE.
  37284. **
  37285. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  37286. ** the effective sector size to its minimum value (512). The purpose of
  37287. ** pPager->sectorSize is to define the "blast radius" of bytes that
  37288. ** might change if a crash occurs while writing to a single byte in
  37289. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  37290. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  37291. ** size. For backwards compatibility of the rollback journal file format,
  37292. ** we cannot reduce the effective sector size below 512.
  37293. */
  37294. static void setSectorSize(Pager *pPager){
  37295. assert( isOpen(pPager->fd) || pPager->tempFile );
  37296. if( pPager->tempFile
  37297. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  37298. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  37299. ){
  37300. /* Sector size doesn't matter for temporary files. Also, the file
  37301. ** may not have been opened yet, in which case the OsSectorSize()
  37302. ** call will segfault. */
  37303. pPager->sectorSize = 512;
  37304. }else{
  37305. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  37306. }
  37307. }
  37308. /*
  37309. ** Playback the journal and thus restore the database file to
  37310. ** the state it was in before we started making changes.
  37311. **
  37312. ** The journal file format is as follows:
  37313. **
  37314. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  37315. ** (2) 4 byte big-endian integer which is the number of valid page records
  37316. ** in the journal. If this value is 0xffffffff, then compute the
  37317. ** number of page records from the journal size.
  37318. ** (3) 4 byte big-endian integer which is the initial value for the
  37319. ** sanity checksum.
  37320. ** (4) 4 byte integer which is the number of pages to truncate the
  37321. ** database to during a rollback.
  37322. ** (5) 4 byte big-endian integer which is the sector size. The header
  37323. ** is this many bytes in size.
  37324. ** (6) 4 byte big-endian integer which is the page size.
  37325. ** (7) zero padding out to the next sector size.
  37326. ** (8) Zero or more pages instances, each as follows:
  37327. ** + 4 byte page number.
  37328. ** + pPager->pageSize bytes of data.
  37329. ** + 4 byte checksum
  37330. **
  37331. ** When we speak of the journal header, we mean the first 7 items above.
  37332. ** Each entry in the journal is an instance of the 8th item.
  37333. **
  37334. ** Call the value from the second bullet "nRec". nRec is the number of
  37335. ** valid page entries in the journal. In most cases, you can compute the
  37336. ** value of nRec from the size of the journal file. But if a power
  37337. ** failure occurred while the journal was being written, it could be the
  37338. ** case that the size of the journal file had already been increased but
  37339. ** the extra entries had not yet made it safely to disk. In such a case,
  37340. ** the value of nRec computed from the file size would be too large. For
  37341. ** that reason, we always use the nRec value in the header.
  37342. **
  37343. ** If the nRec value is 0xffffffff it means that nRec should be computed
  37344. ** from the file size. This value is used when the user selects the
  37345. ** no-sync option for the journal. A power failure could lead to corruption
  37346. ** in this case. But for things like temporary table (which will be
  37347. ** deleted when the power is restored) we don't care.
  37348. **
  37349. ** If the file opened as the journal file is not a well-formed
  37350. ** journal file then all pages up to the first corrupted page are rolled
  37351. ** back (or no pages if the journal header is corrupted). The journal file
  37352. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  37353. ** been encountered.
  37354. **
  37355. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  37356. ** and an error code is returned.
  37357. **
  37358. ** The isHot parameter indicates that we are trying to rollback a journal
  37359. ** that might be a hot journal. Or, it could be that the journal is
  37360. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  37361. ** If the journal really is hot, reset the pager cache prior rolling
  37362. ** back any content. If the journal is merely persistent, no reset is
  37363. ** needed.
  37364. */
  37365. static int pager_playback(Pager *pPager, int isHot){
  37366. sqlite3_vfs *pVfs = pPager->pVfs;
  37367. i64 szJ; /* Size of the journal file in bytes */
  37368. u32 nRec; /* Number of Records in the journal */
  37369. u32 u; /* Unsigned loop counter */
  37370. Pgno mxPg = 0; /* Size of the original file in pages */
  37371. int rc; /* Result code of a subroutine */
  37372. int res = 1; /* Value returned by sqlite3OsAccess() */
  37373. char *zMaster = 0; /* Name of master journal file if any */
  37374. int needPagerReset; /* True to reset page prior to first page rollback */
  37375. /* Figure out how many records are in the journal. Abort early if
  37376. ** the journal is empty.
  37377. */
  37378. assert( isOpen(pPager->jfd) );
  37379. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  37380. if( rc!=SQLITE_OK ){
  37381. goto end_playback;
  37382. }
  37383. /* Read the master journal name from the journal, if it is present.
  37384. ** If a master journal file name is specified, but the file is not
  37385. ** present on disk, then the journal is not hot and does not need to be
  37386. ** played back.
  37387. **
  37388. ** TODO: Technically the following is an error because it assumes that
  37389. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  37390. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  37391. ** mxPathname is 512, which is the same as the minimum allowable value
  37392. ** for pageSize.
  37393. */
  37394. zMaster = pPager->pTmpSpace;
  37395. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  37396. if( rc==SQLITE_OK && zMaster[0] ){
  37397. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  37398. }
  37399. zMaster = 0;
  37400. if( rc!=SQLITE_OK || !res ){
  37401. goto end_playback;
  37402. }
  37403. pPager->journalOff = 0;
  37404. needPagerReset = isHot;
  37405. /* This loop terminates either when a readJournalHdr() or
  37406. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  37407. ** occurs.
  37408. */
  37409. while( 1 ){
  37410. /* Read the next journal header from the journal file. If there are
  37411. ** not enough bytes left in the journal file for a complete header, or
  37412. ** it is corrupted, then a process must have failed while writing it.
  37413. ** This indicates nothing more needs to be rolled back.
  37414. */
  37415. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  37416. if( rc!=SQLITE_OK ){
  37417. if( rc==SQLITE_DONE ){
  37418. rc = SQLITE_OK;
  37419. }
  37420. goto end_playback;
  37421. }
  37422. /* If nRec is 0xffffffff, then this journal was created by a process
  37423. ** working in no-sync mode. This means that the rest of the journal
  37424. ** file consists of pages, there are no more journal headers. Compute
  37425. ** the value of nRec based on this assumption.
  37426. */
  37427. if( nRec==0xffffffff ){
  37428. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  37429. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  37430. }
  37431. /* If nRec is 0 and this rollback is of a transaction created by this
  37432. ** process and if this is the final header in the journal, then it means
  37433. ** that this part of the journal was being filled but has not yet been
  37434. ** synced to disk. Compute the number of pages based on the remaining
  37435. ** size of the file.
  37436. **
  37437. ** The third term of the test was added to fix ticket #2565.
  37438. ** When rolling back a hot journal, nRec==0 always means that the next
  37439. ** chunk of the journal contains zero pages to be rolled back. But
  37440. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  37441. ** the journal, it means that the journal might contain additional
  37442. ** pages that need to be rolled back and that the number of pages
  37443. ** should be computed based on the journal file size.
  37444. */
  37445. if( nRec==0 && !isHot &&
  37446. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  37447. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  37448. }
  37449. /* If this is the first header read from the journal, truncate the
  37450. ** database file back to its original size.
  37451. */
  37452. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  37453. rc = pager_truncate(pPager, mxPg);
  37454. if( rc!=SQLITE_OK ){
  37455. goto end_playback;
  37456. }
  37457. pPager->dbSize = mxPg;
  37458. }
  37459. /* Copy original pages out of the journal and back into the
  37460. ** database file and/or page cache.
  37461. */
  37462. for(u=0; u<nRec; u++){
  37463. if( needPagerReset ){
  37464. pager_reset(pPager);
  37465. needPagerReset = 0;
  37466. }
  37467. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  37468. if( rc!=SQLITE_OK ){
  37469. if( rc==SQLITE_DONE ){
  37470. pPager->journalOff = szJ;
  37471. break;
  37472. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  37473. /* If the journal has been truncated, simply stop reading and
  37474. ** processing the journal. This might happen if the journal was
  37475. ** not completely written and synced prior to a crash. In that
  37476. ** case, the database should have never been written in the
  37477. ** first place so it is OK to simply abandon the rollback. */
  37478. rc = SQLITE_OK;
  37479. goto end_playback;
  37480. }else{
  37481. /* If we are unable to rollback, quit and return the error
  37482. ** code. This will cause the pager to enter the error state
  37483. ** so that no further harm will be done. Perhaps the next
  37484. ** process to come along will be able to rollback the database.
  37485. */
  37486. goto end_playback;
  37487. }
  37488. }
  37489. }
  37490. }
  37491. /*NOTREACHED*/
  37492. assert( 0 );
  37493. end_playback:
  37494. /* Following a rollback, the database file should be back in its original
  37495. ** state prior to the start of the transaction, so invoke the
  37496. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  37497. ** assertion that the transaction counter was modified.
  37498. */
  37499. #ifdef SQLITE_DEBUG
  37500. if( pPager->fd->pMethods ){
  37501. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  37502. }
  37503. #endif
  37504. /* If this playback is happening automatically as a result of an IO or
  37505. ** malloc error that occurred after the change-counter was updated but
  37506. ** before the transaction was committed, then the change-counter
  37507. ** modification may just have been reverted. If this happens in exclusive
  37508. ** mode, then subsequent transactions performed by the connection will not
  37509. ** update the change-counter at all. This may lead to cache inconsistency
  37510. ** problems for other processes at some point in the future. So, just
  37511. ** in case this has happened, clear the changeCountDone flag now.
  37512. */
  37513. pPager->changeCountDone = pPager->tempFile;
  37514. if( rc==SQLITE_OK ){
  37515. zMaster = pPager->pTmpSpace;
  37516. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  37517. testcase( rc!=SQLITE_OK );
  37518. }
  37519. if( rc==SQLITE_OK
  37520. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  37521. ){
  37522. rc = sqlite3PagerSync(pPager);
  37523. }
  37524. if( rc==SQLITE_OK ){
  37525. rc = pager_end_transaction(pPager, zMaster[0]!='\0');
  37526. testcase( rc!=SQLITE_OK );
  37527. }
  37528. if( rc==SQLITE_OK && zMaster[0] && res ){
  37529. /* If there was a master journal and this routine will return success,
  37530. ** see if it is possible to delete the master journal.
  37531. */
  37532. rc = pager_delmaster(pPager, zMaster);
  37533. testcase( rc!=SQLITE_OK );
  37534. }
  37535. /* The Pager.sectorSize variable may have been updated while rolling
  37536. ** back a journal created by a process with a different sector size
  37537. ** value. Reset it to the correct value for this process.
  37538. */
  37539. setSectorSize(pPager);
  37540. return rc;
  37541. }
  37542. /*
  37543. ** Read the content for page pPg out of the database file and into
  37544. ** pPg->pData. A shared lock or greater must be held on the database
  37545. ** file before this function is called.
  37546. **
  37547. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  37548. ** the value read from the database file.
  37549. **
  37550. ** If an IO error occurs, then the IO error is returned to the caller.
  37551. ** Otherwise, SQLITE_OK is returned.
  37552. */
  37553. static int readDbPage(PgHdr *pPg){
  37554. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  37555. Pgno pgno = pPg->pgno; /* Page number to read */
  37556. int rc = SQLITE_OK; /* Return code */
  37557. int isInWal = 0; /* True if page is in log file */
  37558. int pgsz = pPager->pageSize; /* Number of bytes to read */
  37559. assert( pPager->eState>=PAGER_READER && !MEMDB );
  37560. assert( isOpen(pPager->fd) );
  37561. if( NEVER(!isOpen(pPager->fd)) ){
  37562. assert( pPager->tempFile );
  37563. memset(pPg->pData, 0, pPager->pageSize);
  37564. return SQLITE_OK;
  37565. }
  37566. if( pagerUseWal(pPager) ){
  37567. /* Try to pull the page from the write-ahead log. */
  37568. rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
  37569. }
  37570. if( rc==SQLITE_OK && !isInWal ){
  37571. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  37572. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  37573. if( rc==SQLITE_IOERR_SHORT_READ ){
  37574. rc = SQLITE_OK;
  37575. }
  37576. }
  37577. if( pgno==1 ){
  37578. if( rc ){
  37579. /* If the read is unsuccessful, set the dbFileVers[] to something
  37580. ** that will never be a valid file version. dbFileVers[] is a copy
  37581. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  37582. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  37583. ** should be page numbers which are never 0xffffffff. So filling
  37584. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  37585. **
  37586. ** For an encrypted database, the situation is more complex: bytes
  37587. ** 24..39 of the database are white noise. But the probability of
  37588. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  37589. ** we should still be ok.
  37590. */
  37591. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  37592. }else{
  37593. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  37594. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  37595. }
  37596. }
  37597. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  37598. PAGER_INCR(sqlite3_pager_readdb_count);
  37599. PAGER_INCR(pPager->nRead);
  37600. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  37601. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  37602. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  37603. return rc;
  37604. }
  37605. /*
  37606. ** Update the value of the change-counter at offsets 24 and 92 in
  37607. ** the header and the sqlite version number at offset 96.
  37608. **
  37609. ** This is an unconditional update. See also the pager_incr_changecounter()
  37610. ** routine which only updates the change-counter if the update is actually
  37611. ** needed, as determined by the pPager->changeCountDone state variable.
  37612. */
  37613. static void pager_write_changecounter(PgHdr *pPg){
  37614. u32 change_counter;
  37615. /* Increment the value just read and write it back to byte 24. */
  37616. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  37617. put32bits(((char*)pPg->pData)+24, change_counter);
  37618. /* Also store the SQLite version number in bytes 96..99 and in
  37619. ** bytes 92..95 store the change counter for which the version number
  37620. ** is valid. */
  37621. put32bits(((char*)pPg->pData)+92, change_counter);
  37622. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  37623. }
  37624. #ifndef SQLITE_OMIT_WAL
  37625. /*
  37626. ** This function is invoked once for each page that has already been
  37627. ** written into the log file when a WAL transaction is rolled back.
  37628. ** Parameter iPg is the page number of said page. The pCtx argument
  37629. ** is actually a pointer to the Pager structure.
  37630. **
  37631. ** If page iPg is present in the cache, and has no outstanding references,
  37632. ** it is discarded. Otherwise, if there are one or more outstanding
  37633. ** references, the page content is reloaded from the database. If the
  37634. ** attempt to reload content from the database is required and fails,
  37635. ** return an SQLite error code. Otherwise, SQLITE_OK.
  37636. */
  37637. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  37638. int rc = SQLITE_OK;
  37639. Pager *pPager = (Pager *)pCtx;
  37640. PgHdr *pPg;
  37641. pPg = sqlite3PagerLookup(pPager, iPg);
  37642. if( pPg ){
  37643. if( sqlite3PcachePageRefcount(pPg)==1 ){
  37644. sqlite3PcacheDrop(pPg);
  37645. }else{
  37646. rc = readDbPage(pPg);
  37647. if( rc==SQLITE_OK ){
  37648. pPager->xReiniter(pPg);
  37649. }
  37650. sqlite3PagerUnref(pPg);
  37651. }
  37652. }
  37653. /* Normally, if a transaction is rolled back, any backup processes are
  37654. ** updated as data is copied out of the rollback journal and into the
  37655. ** database. This is not generally possible with a WAL database, as
  37656. ** rollback involves simply truncating the log file. Therefore, if one
  37657. ** or more frames have already been written to the log (and therefore
  37658. ** also copied into the backup databases) as part of this transaction,
  37659. ** the backups must be restarted.
  37660. */
  37661. sqlite3BackupRestart(pPager->pBackup);
  37662. return rc;
  37663. }
  37664. /*
  37665. ** This function is called to rollback a transaction on a WAL database.
  37666. */
  37667. static int pagerRollbackWal(Pager *pPager){
  37668. int rc; /* Return Code */
  37669. PgHdr *pList; /* List of dirty pages to revert */
  37670. /* For all pages in the cache that are currently dirty or have already
  37671. ** been written (but not committed) to the log file, do one of the
  37672. ** following:
  37673. **
  37674. ** + Discard the cached page (if refcount==0), or
  37675. ** + Reload page content from the database (if refcount>0).
  37676. */
  37677. pPager->dbSize = pPager->dbOrigSize;
  37678. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  37679. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  37680. while( pList && rc==SQLITE_OK ){
  37681. PgHdr *pNext = pList->pDirty;
  37682. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  37683. pList = pNext;
  37684. }
  37685. return rc;
  37686. }
  37687. /*
  37688. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  37689. ** the contents of the list of pages headed by pList (connected by pDirty),
  37690. ** this function notifies any active backup processes that the pages have
  37691. ** changed.
  37692. **
  37693. ** The list of pages passed into this routine is always sorted by page number.
  37694. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  37695. */
  37696. static int pagerWalFrames(
  37697. Pager *pPager, /* Pager object */
  37698. PgHdr *pList, /* List of frames to log */
  37699. Pgno nTruncate, /* Database size after this commit */
  37700. int isCommit /* True if this is a commit */
  37701. ){
  37702. int rc; /* Return code */
  37703. int nList; /* Number of pages in pList */
  37704. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  37705. PgHdr *p; /* For looping over pages */
  37706. #endif
  37707. assert( pPager->pWal );
  37708. assert( pList );
  37709. #ifdef SQLITE_DEBUG
  37710. /* Verify that the page list is in accending order */
  37711. for(p=pList; p && p->pDirty; p=p->pDirty){
  37712. assert( p->pgno < p->pDirty->pgno );
  37713. }
  37714. #endif
  37715. assert( pList->pDirty==0 || isCommit );
  37716. if( isCommit ){
  37717. /* If a WAL transaction is being committed, there is no point in writing
  37718. ** any pages with page numbers greater than nTruncate into the WAL file.
  37719. ** They will never be read by any client. So remove them from the pDirty
  37720. ** list here. */
  37721. PgHdr *p;
  37722. PgHdr **ppNext = &pList;
  37723. nList = 0;
  37724. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  37725. if( p->pgno<=nTruncate ){
  37726. ppNext = &p->pDirty;
  37727. nList++;
  37728. }
  37729. }
  37730. assert( pList );
  37731. }else{
  37732. nList = 1;
  37733. }
  37734. pPager->aStat[PAGER_STAT_WRITE] += nList;
  37735. if( pList->pgno==1 ) pager_write_changecounter(pList);
  37736. rc = sqlite3WalFrames(pPager->pWal,
  37737. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  37738. );
  37739. if( rc==SQLITE_OK && pPager->pBackup ){
  37740. PgHdr *p;
  37741. for(p=pList; p; p=p->pDirty){
  37742. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  37743. }
  37744. }
  37745. #ifdef SQLITE_CHECK_PAGES
  37746. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  37747. for(p=pList; p; p=p->pDirty){
  37748. pager_set_pagehash(p);
  37749. }
  37750. #endif
  37751. return rc;
  37752. }
  37753. /*
  37754. ** Begin a read transaction on the WAL.
  37755. **
  37756. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  37757. ** makes a snapshot of the database at the current point in time and preserves
  37758. ** that snapshot for use by the reader in spite of concurrently changes by
  37759. ** other writers or checkpointers.
  37760. */
  37761. static int pagerBeginReadTransaction(Pager *pPager){
  37762. int rc; /* Return code */
  37763. int changed = 0; /* True if cache must be reset */
  37764. assert( pagerUseWal(pPager) );
  37765. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  37766. /* sqlite3WalEndReadTransaction() was not called for the previous
  37767. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  37768. ** are in locking_mode=NORMAL and EndRead() was previously called,
  37769. ** the duplicate call is harmless.
  37770. */
  37771. sqlite3WalEndReadTransaction(pPager->pWal);
  37772. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  37773. if( rc!=SQLITE_OK || changed ){
  37774. pager_reset(pPager);
  37775. }
  37776. return rc;
  37777. }
  37778. #endif
  37779. /*
  37780. ** This function is called as part of the transition from PAGER_OPEN
  37781. ** to PAGER_READER state to determine the size of the database file
  37782. ** in pages (assuming the page size currently stored in Pager.pageSize).
  37783. **
  37784. ** If no error occurs, SQLITE_OK is returned and the size of the database
  37785. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  37786. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  37787. */
  37788. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  37789. Pgno nPage; /* Value to return via *pnPage */
  37790. /* Query the WAL sub-system for the database size. The WalDbsize()
  37791. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  37792. ** if the database size is not available. The database size is not
  37793. ** available from the WAL sub-system if the log file is empty or
  37794. ** contains no valid committed transactions.
  37795. */
  37796. assert( pPager->eState==PAGER_OPEN );
  37797. assert( pPager->eLock>=SHARED_LOCK );
  37798. nPage = sqlite3WalDbsize(pPager->pWal);
  37799. /* If the database size was not available from the WAL sub-system,
  37800. ** determine it based on the size of the database file. If the size
  37801. ** of the database file is not an integer multiple of the page-size,
  37802. ** round down to the nearest page. Except, any file larger than 0
  37803. ** bytes in size is considered to contain at least one page.
  37804. */
  37805. if( nPage==0 ){
  37806. i64 n = 0; /* Size of db file in bytes */
  37807. assert( isOpen(pPager->fd) || pPager->tempFile );
  37808. if( isOpen(pPager->fd) ){
  37809. int rc = sqlite3OsFileSize(pPager->fd, &n);
  37810. if( rc!=SQLITE_OK ){
  37811. return rc;
  37812. }
  37813. }
  37814. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  37815. }
  37816. /* If the current number of pages in the file is greater than the
  37817. ** configured maximum pager number, increase the allowed limit so
  37818. ** that the file can be read.
  37819. */
  37820. if( nPage>pPager->mxPgno ){
  37821. pPager->mxPgno = (Pgno)nPage;
  37822. }
  37823. *pnPage = nPage;
  37824. return SQLITE_OK;
  37825. }
  37826. #ifndef SQLITE_OMIT_WAL
  37827. /*
  37828. ** Check if the *-wal file that corresponds to the database opened by pPager
  37829. ** exists if the database is not empy, or verify that the *-wal file does
  37830. ** not exist (by deleting it) if the database file is empty.
  37831. **
  37832. ** If the database is not empty and the *-wal file exists, open the pager
  37833. ** in WAL mode. If the database is empty or if no *-wal file exists and
  37834. ** if no error occurs, make sure Pager.journalMode is not set to
  37835. ** PAGER_JOURNALMODE_WAL.
  37836. **
  37837. ** Return SQLITE_OK or an error code.
  37838. **
  37839. ** The caller must hold a SHARED lock on the database file to call this
  37840. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  37841. ** a WAL on a none-empty database, this ensures there is no race condition
  37842. ** between the xAccess() below and an xDelete() being executed by some
  37843. ** other connection.
  37844. */
  37845. static int pagerOpenWalIfPresent(Pager *pPager){
  37846. int rc = SQLITE_OK;
  37847. assert( pPager->eState==PAGER_OPEN );
  37848. assert( pPager->eLock>=SHARED_LOCK );
  37849. if( !pPager->tempFile ){
  37850. int isWal; /* True if WAL file exists */
  37851. Pgno nPage; /* Size of the database file */
  37852. rc = pagerPagecount(pPager, &nPage);
  37853. if( rc ) return rc;
  37854. if( nPage==0 ){
  37855. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  37856. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  37857. isWal = 0;
  37858. }else{
  37859. rc = sqlite3OsAccess(
  37860. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  37861. );
  37862. }
  37863. if( rc==SQLITE_OK ){
  37864. if( isWal ){
  37865. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  37866. rc = sqlite3PagerOpenWal(pPager, 0);
  37867. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  37868. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  37869. }
  37870. }
  37871. }
  37872. return rc;
  37873. }
  37874. #endif
  37875. /*
  37876. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  37877. ** the entire master journal file. The case pSavepoint==NULL occurs when
  37878. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  37879. ** savepoint.
  37880. **
  37881. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  37882. ** being rolled back), then the rollback consists of up to three stages,
  37883. ** performed in the order specified:
  37884. **
  37885. ** * Pages are played back from the main journal starting at byte
  37886. ** offset PagerSavepoint.iOffset and continuing to
  37887. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  37888. ** file if PagerSavepoint.iHdrOffset is zero.
  37889. **
  37890. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  37891. ** back starting from the journal header immediately following
  37892. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  37893. **
  37894. ** * Pages are then played back from the sub-journal file, starting
  37895. ** with the PagerSavepoint.iSubRec and continuing to the end of
  37896. ** the journal file.
  37897. **
  37898. ** Throughout the rollback process, each time a page is rolled back, the
  37899. ** corresponding bit is set in a bitvec structure (variable pDone in the
  37900. ** implementation below). This is used to ensure that a page is only
  37901. ** rolled back the first time it is encountered in either journal.
  37902. **
  37903. ** If pSavepoint is NULL, then pages are only played back from the main
  37904. ** journal file. There is no need for a bitvec in this case.
  37905. **
  37906. ** In either case, before playback commences the Pager.dbSize variable
  37907. ** is reset to the value that it held at the start of the savepoint
  37908. ** (or transaction). No page with a page-number greater than this value
  37909. ** is played back. If one is encountered it is simply skipped.
  37910. */
  37911. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  37912. i64 szJ; /* Effective size of the main journal */
  37913. i64 iHdrOff; /* End of first segment of main-journal records */
  37914. int rc = SQLITE_OK; /* Return code */
  37915. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  37916. assert( pPager->eState!=PAGER_ERROR );
  37917. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  37918. /* Allocate a bitvec to use to store the set of pages rolled back */
  37919. if( pSavepoint ){
  37920. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  37921. if( !pDone ){
  37922. return SQLITE_NOMEM;
  37923. }
  37924. }
  37925. /* Set the database size back to the value it was before the savepoint
  37926. ** being reverted was opened.
  37927. */
  37928. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  37929. pPager->changeCountDone = pPager->tempFile;
  37930. if( !pSavepoint && pagerUseWal(pPager) ){
  37931. return pagerRollbackWal(pPager);
  37932. }
  37933. /* Use pPager->journalOff as the effective size of the main rollback
  37934. ** journal. The actual file might be larger than this in
  37935. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  37936. ** past pPager->journalOff is off-limits to us.
  37937. */
  37938. szJ = pPager->journalOff;
  37939. assert( pagerUseWal(pPager)==0 || szJ==0 );
  37940. /* Begin by rolling back records from the main journal starting at
  37941. ** PagerSavepoint.iOffset and continuing to the next journal header.
  37942. ** There might be records in the main journal that have a page number
  37943. ** greater than the current database size (pPager->dbSize) but those
  37944. ** will be skipped automatically. Pages are added to pDone as they
  37945. ** are played back.
  37946. */
  37947. if( pSavepoint && !pagerUseWal(pPager) ){
  37948. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  37949. pPager->journalOff = pSavepoint->iOffset;
  37950. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  37951. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  37952. }
  37953. assert( rc!=SQLITE_DONE );
  37954. }else{
  37955. pPager->journalOff = 0;
  37956. }
  37957. /* Continue rolling back records out of the main journal starting at
  37958. ** the first journal header seen and continuing until the effective end
  37959. ** of the main journal file. Continue to skip out-of-range pages and
  37960. ** continue adding pages rolled back to pDone.
  37961. */
  37962. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  37963. u32 ii; /* Loop counter */
  37964. u32 nJRec = 0; /* Number of Journal Records */
  37965. u32 dummy;
  37966. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  37967. assert( rc!=SQLITE_DONE );
  37968. /*
  37969. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  37970. ** test is related to ticket #2565. See the discussion in the
  37971. ** pager_playback() function for additional information.
  37972. */
  37973. if( nJRec==0
  37974. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  37975. ){
  37976. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  37977. }
  37978. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  37979. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  37980. }
  37981. assert( rc!=SQLITE_DONE );
  37982. }
  37983. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  37984. /* Finally, rollback pages from the sub-journal. Page that were
  37985. ** previously rolled back out of the main journal (and are hence in pDone)
  37986. ** will be skipped. Out-of-range pages are also skipped.
  37987. */
  37988. if( pSavepoint ){
  37989. u32 ii; /* Loop counter */
  37990. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  37991. if( pagerUseWal(pPager) ){
  37992. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  37993. }
  37994. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  37995. assert( offset==(i64)ii*(4+pPager->pageSize) );
  37996. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  37997. }
  37998. assert( rc!=SQLITE_DONE );
  37999. }
  38000. sqlite3BitvecDestroy(pDone);
  38001. if( rc==SQLITE_OK ){
  38002. pPager->journalOff = szJ;
  38003. }
  38004. return rc;
  38005. }
  38006. /*
  38007. ** Change the maximum number of in-memory pages that are allowed.
  38008. */
  38009. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  38010. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  38011. }
  38012. /*
  38013. ** Free as much memory as possible from the pager.
  38014. */
  38015. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  38016. sqlite3PcacheShrink(pPager->pPCache);
  38017. }
  38018. /*
  38019. ** Adjust the robustness of the database to damage due to OS crashes
  38020. ** or power failures by changing the number of syncs()s when writing
  38021. ** the rollback journal. There are three levels:
  38022. **
  38023. ** OFF sqlite3OsSync() is never called. This is the default
  38024. ** for temporary and transient files.
  38025. **
  38026. ** NORMAL The journal is synced once before writes begin on the
  38027. ** database. This is normally adequate protection, but
  38028. ** it is theoretically possible, though very unlikely,
  38029. ** that an inopertune power failure could leave the journal
  38030. ** in a state which would cause damage to the database
  38031. ** when it is rolled back.
  38032. **
  38033. ** FULL The journal is synced twice before writes begin on the
  38034. ** database (with some additional information - the nRec field
  38035. ** of the journal header - being written in between the two
  38036. ** syncs). If we assume that writing a
  38037. ** single disk sector is atomic, then this mode provides
  38038. ** assurance that the journal will not be corrupted to the
  38039. ** point of causing damage to the database during rollback.
  38040. **
  38041. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  38042. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  38043. ** prior to the start of checkpoint and that the database file is synced
  38044. ** at the conclusion of the checkpoint if the entire content of the WAL
  38045. ** was written back into the database. But no sync operations occur for
  38046. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  38047. ** file is synced following each commit operation, in addition to the
  38048. ** syncs associated with NORMAL.
  38049. **
  38050. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  38051. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  38052. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  38053. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  38054. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  38055. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  38056. ** the xSync primitive is called and is relevant to all platforms.
  38057. **
  38058. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  38059. ** and FULL=3.
  38060. */
  38061. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  38062. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
  38063. Pager *pPager, /* The pager to set safety level for */
  38064. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  38065. int bFullFsync, /* PRAGMA fullfsync */
  38066. int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
  38067. ){
  38068. assert( level>=1 && level<=3 );
  38069. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  38070. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  38071. if( pPager->noSync ){
  38072. pPager->syncFlags = 0;
  38073. pPager->ckptSyncFlags = 0;
  38074. }else if( bFullFsync ){
  38075. pPager->syncFlags = SQLITE_SYNC_FULL;
  38076. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  38077. }else if( bCkptFullFsync ){
  38078. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  38079. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  38080. }else{
  38081. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  38082. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  38083. }
  38084. pPager->walSyncFlags = pPager->syncFlags;
  38085. if( pPager->fullSync ){
  38086. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  38087. }
  38088. }
  38089. #endif
  38090. /*
  38091. ** The following global variable is incremented whenever the library
  38092. ** attempts to open a temporary file. This information is used for
  38093. ** testing and analysis only.
  38094. */
  38095. #ifdef SQLITE_TEST
  38096. SQLITE_API int sqlite3_opentemp_count = 0;
  38097. #endif
  38098. /*
  38099. ** Open a temporary file.
  38100. **
  38101. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  38102. ** or some other error code if we fail. The OS will automatically
  38103. ** delete the temporary file when it is closed.
  38104. **
  38105. ** The flags passed to the VFS layer xOpen() call are those specified
  38106. ** by parameter vfsFlags ORed with the following:
  38107. **
  38108. ** SQLITE_OPEN_READWRITE
  38109. ** SQLITE_OPEN_CREATE
  38110. ** SQLITE_OPEN_EXCLUSIVE
  38111. ** SQLITE_OPEN_DELETEONCLOSE
  38112. */
  38113. static int pagerOpentemp(
  38114. Pager *pPager, /* The pager object */
  38115. sqlite3_file *pFile, /* Write the file descriptor here */
  38116. int vfsFlags /* Flags passed through to the VFS */
  38117. ){
  38118. int rc; /* Return code */
  38119. #ifdef SQLITE_TEST
  38120. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  38121. #endif
  38122. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  38123. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  38124. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  38125. assert( rc!=SQLITE_OK || isOpen(pFile) );
  38126. return rc;
  38127. }
  38128. /*
  38129. ** Set the busy handler function.
  38130. **
  38131. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  38132. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  38133. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  38134. ** lock. It does *not* invoke the busy handler when upgrading from
  38135. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  38136. ** (which occurs during hot-journal rollback). Summary:
  38137. **
  38138. ** Transition | Invokes xBusyHandler
  38139. ** --------------------------------------------------------
  38140. ** NO_LOCK -> SHARED_LOCK | Yes
  38141. ** SHARED_LOCK -> RESERVED_LOCK | No
  38142. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  38143. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  38144. **
  38145. ** If the busy-handler callback returns non-zero, the lock is
  38146. ** retried. If it returns zero, then the SQLITE_BUSY error is
  38147. ** returned to the caller of the pager API function.
  38148. */
  38149. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  38150. Pager *pPager, /* Pager object */
  38151. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  38152. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  38153. ){
  38154. pPager->xBusyHandler = xBusyHandler;
  38155. pPager->pBusyHandlerArg = pBusyHandlerArg;
  38156. if( isOpen(pPager->fd) ){
  38157. void **ap = (void **)&pPager->xBusyHandler;
  38158. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  38159. assert( ap[1]==pBusyHandlerArg );
  38160. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  38161. }
  38162. }
  38163. /*
  38164. ** Change the page size used by the Pager object. The new page size
  38165. ** is passed in *pPageSize.
  38166. **
  38167. ** If the pager is in the error state when this function is called, it
  38168. ** is a no-op. The value returned is the error state error code (i.e.
  38169. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  38170. **
  38171. ** Otherwise, if all of the following are true:
  38172. **
  38173. ** * the new page size (value of *pPageSize) is valid (a power
  38174. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  38175. **
  38176. ** * there are no outstanding page references, and
  38177. **
  38178. ** * the database is either not an in-memory database or it is
  38179. ** an in-memory database that currently consists of zero pages.
  38180. **
  38181. ** then the pager object page size is set to *pPageSize.
  38182. **
  38183. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  38184. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  38185. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  38186. ** In all other cases, SQLITE_OK is returned.
  38187. **
  38188. ** If the page size is not changed, either because one of the enumerated
  38189. ** conditions above is not true, the pager was in error state when this
  38190. ** function was called, or because the memory allocation attempt failed,
  38191. ** then *pPageSize is set to the old, retained page size before returning.
  38192. */
  38193. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  38194. int rc = SQLITE_OK;
  38195. /* It is not possible to do a full assert_pager_state() here, as this
  38196. ** function may be called from within PagerOpen(), before the state
  38197. ** of the Pager object is internally consistent.
  38198. **
  38199. ** At one point this function returned an error if the pager was in
  38200. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  38201. ** there is at least one outstanding page reference, this function
  38202. ** is a no-op for that case anyhow.
  38203. */
  38204. u32 pageSize = *pPageSize;
  38205. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  38206. if( (pPager->memDb==0 || pPager->dbSize==0)
  38207. && sqlite3PcacheRefCount(pPager->pPCache)==0
  38208. && pageSize && pageSize!=(u32)pPager->pageSize
  38209. ){
  38210. char *pNew = NULL; /* New temp space */
  38211. i64 nByte = 0;
  38212. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  38213. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  38214. }
  38215. if( rc==SQLITE_OK ){
  38216. pNew = (char *)sqlite3PageMalloc(pageSize);
  38217. if( !pNew ) rc = SQLITE_NOMEM;
  38218. }
  38219. if( rc==SQLITE_OK ){
  38220. pager_reset(pPager);
  38221. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  38222. pPager->pageSize = pageSize;
  38223. sqlite3PageFree(pPager->pTmpSpace);
  38224. pPager->pTmpSpace = pNew;
  38225. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  38226. }
  38227. }
  38228. *pPageSize = pPager->pageSize;
  38229. if( rc==SQLITE_OK ){
  38230. if( nReserve<0 ) nReserve = pPager->nReserve;
  38231. assert( nReserve>=0 && nReserve<1000 );
  38232. pPager->nReserve = (i16)nReserve;
  38233. pagerReportSize(pPager);
  38234. }
  38235. return rc;
  38236. }
  38237. /*
  38238. ** Return a pointer to the "temporary page" buffer held internally
  38239. ** by the pager. This is a buffer that is big enough to hold the
  38240. ** entire content of a database page. This buffer is used internally
  38241. ** during rollback and will be overwritten whenever a rollback
  38242. ** occurs. But other modules are free to use it too, as long as
  38243. ** no rollbacks are happening.
  38244. */
  38245. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  38246. return pPager->pTmpSpace;
  38247. }
  38248. /*
  38249. ** Attempt to set the maximum database page count if mxPage is positive.
  38250. ** Make no changes if mxPage is zero or negative. And never reduce the
  38251. ** maximum page count below the current size of the database.
  38252. **
  38253. ** Regardless of mxPage, return the current maximum page count.
  38254. */
  38255. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  38256. if( mxPage>0 ){
  38257. pPager->mxPgno = mxPage;
  38258. }
  38259. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  38260. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  38261. return pPager->mxPgno;
  38262. }
  38263. /*
  38264. ** The following set of routines are used to disable the simulated
  38265. ** I/O error mechanism. These routines are used to avoid simulated
  38266. ** errors in places where we do not care about errors.
  38267. **
  38268. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  38269. ** and generate no code.
  38270. */
  38271. #ifdef SQLITE_TEST
  38272. SQLITE_API extern int sqlite3_io_error_pending;
  38273. SQLITE_API extern int sqlite3_io_error_hit;
  38274. static int saved_cnt;
  38275. void disable_simulated_io_errors(void){
  38276. saved_cnt = sqlite3_io_error_pending;
  38277. sqlite3_io_error_pending = -1;
  38278. }
  38279. void enable_simulated_io_errors(void){
  38280. sqlite3_io_error_pending = saved_cnt;
  38281. }
  38282. #else
  38283. # define disable_simulated_io_errors()
  38284. # define enable_simulated_io_errors()
  38285. #endif
  38286. /*
  38287. ** Read the first N bytes from the beginning of the file into memory
  38288. ** that pDest points to.
  38289. **
  38290. ** If the pager was opened on a transient file (zFilename==""), or
  38291. ** opened on a file less than N bytes in size, the output buffer is
  38292. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  38293. ** function is used to read database headers, and a new transient or
  38294. ** zero sized database has a header than consists entirely of zeroes.
  38295. **
  38296. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  38297. ** the error code is returned to the caller and the contents of the
  38298. ** output buffer undefined.
  38299. */
  38300. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  38301. int rc = SQLITE_OK;
  38302. memset(pDest, 0, N);
  38303. assert( isOpen(pPager->fd) || pPager->tempFile );
  38304. /* This routine is only called by btree immediately after creating
  38305. ** the Pager object. There has not been an opportunity to transition
  38306. ** to WAL mode yet.
  38307. */
  38308. assert( !pagerUseWal(pPager) );
  38309. if( isOpen(pPager->fd) ){
  38310. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  38311. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  38312. if( rc==SQLITE_IOERR_SHORT_READ ){
  38313. rc = SQLITE_OK;
  38314. }
  38315. }
  38316. return rc;
  38317. }
  38318. /*
  38319. ** This function may only be called when a read-transaction is open on
  38320. ** the pager. It returns the total number of pages in the database.
  38321. **
  38322. ** However, if the file is between 1 and <page-size> bytes in size, then
  38323. ** this is considered a 1 page file.
  38324. */
  38325. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  38326. assert( pPager->eState>=PAGER_READER );
  38327. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  38328. *pnPage = (int)pPager->dbSize;
  38329. }
  38330. /*
  38331. ** Try to obtain a lock of type locktype on the database file. If
  38332. ** a similar or greater lock is already held, this function is a no-op
  38333. ** (returning SQLITE_OK immediately).
  38334. **
  38335. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  38336. ** the busy callback if the lock is currently not available. Repeat
  38337. ** until the busy callback returns false or until the attempt to
  38338. ** obtain the lock succeeds.
  38339. **
  38340. ** Return SQLITE_OK on success and an error code if we cannot obtain
  38341. ** the lock. If the lock is obtained successfully, set the Pager.state
  38342. ** variable to locktype before returning.
  38343. */
  38344. static int pager_wait_on_lock(Pager *pPager, int locktype){
  38345. int rc; /* Return code */
  38346. /* Check that this is either a no-op (because the requested lock is
  38347. ** already held, or one of the transistions that the busy-handler
  38348. ** may be invoked during, according to the comment above
  38349. ** sqlite3PagerSetBusyhandler().
  38350. */
  38351. assert( (pPager->eLock>=locktype)
  38352. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  38353. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  38354. );
  38355. do {
  38356. rc = pagerLockDb(pPager, locktype);
  38357. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  38358. return rc;
  38359. }
  38360. /*
  38361. ** Function assertTruncateConstraint(pPager) checks that one of the
  38362. ** following is true for all dirty pages currently in the page-cache:
  38363. **
  38364. ** a) The page number is less than or equal to the size of the
  38365. ** current database image, in pages, OR
  38366. **
  38367. ** b) if the page content were written at this time, it would not
  38368. ** be necessary to write the current content out to the sub-journal
  38369. ** (as determined by function subjRequiresPage()).
  38370. **
  38371. ** If the condition asserted by this function were not true, and the
  38372. ** dirty page were to be discarded from the cache via the pagerStress()
  38373. ** routine, pagerStress() would not write the current page content to
  38374. ** the database file. If a savepoint transaction were rolled back after
  38375. ** this happened, the correct behaviour would be to restore the current
  38376. ** content of the page. However, since this content is not present in either
  38377. ** the database file or the portion of the rollback journal and
  38378. ** sub-journal rolled back the content could not be restored and the
  38379. ** database image would become corrupt. It is therefore fortunate that
  38380. ** this circumstance cannot arise.
  38381. */
  38382. #if defined(SQLITE_DEBUG)
  38383. static void assertTruncateConstraintCb(PgHdr *pPg){
  38384. assert( pPg->flags&PGHDR_DIRTY );
  38385. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  38386. }
  38387. static void assertTruncateConstraint(Pager *pPager){
  38388. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  38389. }
  38390. #else
  38391. # define assertTruncateConstraint(pPager)
  38392. #endif
  38393. /*
  38394. ** Truncate the in-memory database file image to nPage pages. This
  38395. ** function does not actually modify the database file on disk. It
  38396. ** just sets the internal state of the pager object so that the
  38397. ** truncation will be done when the current transaction is committed.
  38398. */
  38399. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  38400. assert( pPager->dbSize>=nPage );
  38401. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  38402. pPager->dbSize = nPage;
  38403. assertTruncateConstraint(pPager);
  38404. }
  38405. /*
  38406. ** This function is called before attempting a hot-journal rollback. It
  38407. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  38408. ** size of the journal file so that the pager_playback() routine knows
  38409. ** that the entire journal file has been synced.
  38410. **
  38411. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  38412. ** that if a power-failure occurs during the rollback, the process that
  38413. ** attempts rollback following system recovery sees the same journal
  38414. ** content as this process.
  38415. **
  38416. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  38417. ** an SQLite error code.
  38418. */
  38419. static int pagerSyncHotJournal(Pager *pPager){
  38420. int rc = SQLITE_OK;
  38421. if( !pPager->noSync ){
  38422. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  38423. }
  38424. if( rc==SQLITE_OK ){
  38425. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  38426. }
  38427. return rc;
  38428. }
  38429. /*
  38430. ** Shutdown the page cache. Free all memory and close all files.
  38431. **
  38432. ** If a transaction was in progress when this routine is called, that
  38433. ** transaction is rolled back. All outstanding pages are invalidated
  38434. ** and their memory is freed. Any attempt to use a page associated
  38435. ** with this page cache after this function returns will likely
  38436. ** result in a coredump.
  38437. **
  38438. ** This function always succeeds. If a transaction is active an attempt
  38439. ** is made to roll it back. If an error occurs during the rollback
  38440. ** a hot journal may be left in the filesystem but no error is returned
  38441. ** to the caller.
  38442. */
  38443. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  38444. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  38445. assert( assert_pager_state(pPager) );
  38446. disable_simulated_io_errors();
  38447. sqlite3BeginBenignMalloc();
  38448. /* pPager->errCode = 0; */
  38449. pPager->exclusiveMode = 0;
  38450. #ifndef SQLITE_OMIT_WAL
  38451. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  38452. pPager->pWal = 0;
  38453. #endif
  38454. pager_reset(pPager);
  38455. if( MEMDB ){
  38456. pager_unlock(pPager);
  38457. }else{
  38458. /* If it is open, sync the journal file before calling UnlockAndRollback.
  38459. ** If this is not done, then an unsynced portion of the open journal
  38460. ** file may be played back into the database. If a power failure occurs
  38461. ** while this is happening, the database could become corrupt.
  38462. **
  38463. ** If an error occurs while trying to sync the journal, shift the pager
  38464. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  38465. ** database and close the journal file without attempting to roll it
  38466. ** back or finalize it. The next database user will have to do hot-journal
  38467. ** rollback before accessing the database file.
  38468. */
  38469. if( isOpen(pPager->jfd) ){
  38470. pager_error(pPager, pagerSyncHotJournal(pPager));
  38471. }
  38472. pagerUnlockAndRollback(pPager);
  38473. }
  38474. sqlite3EndBenignMalloc();
  38475. enable_simulated_io_errors();
  38476. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  38477. IOTRACE(("CLOSE %p\n", pPager))
  38478. sqlite3OsClose(pPager->jfd);
  38479. sqlite3OsClose(pPager->fd);
  38480. sqlite3PageFree(pTmp);
  38481. sqlite3PcacheClose(pPager->pPCache);
  38482. #ifdef SQLITE_HAS_CODEC
  38483. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  38484. #endif
  38485. assert( !pPager->aSavepoint && !pPager->pInJournal );
  38486. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  38487. sqlite3_free(pPager);
  38488. return SQLITE_OK;
  38489. }
  38490. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  38491. /*
  38492. ** Return the page number for page pPg.
  38493. */
  38494. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  38495. return pPg->pgno;
  38496. }
  38497. #endif
  38498. /*
  38499. ** Increment the reference count for page pPg.
  38500. */
  38501. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  38502. sqlite3PcacheRef(pPg);
  38503. }
  38504. /*
  38505. ** Sync the journal. In other words, make sure all the pages that have
  38506. ** been written to the journal have actually reached the surface of the
  38507. ** disk and can be restored in the event of a hot-journal rollback.
  38508. **
  38509. ** If the Pager.noSync flag is set, then this function is a no-op.
  38510. ** Otherwise, the actions required depend on the journal-mode and the
  38511. ** device characteristics of the file-system, as follows:
  38512. **
  38513. ** * If the journal file is an in-memory journal file, no action need
  38514. ** be taken.
  38515. **
  38516. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  38517. ** then the nRec field of the most recently written journal header
  38518. ** is updated to contain the number of journal records that have
  38519. ** been written following it. If the pager is operating in full-sync
  38520. ** mode, then the journal file is synced before this field is updated.
  38521. **
  38522. ** * If the device does not support the SEQUENTIAL property, then
  38523. ** journal file is synced.
  38524. **
  38525. ** Or, in pseudo-code:
  38526. **
  38527. ** if( NOT <in-memory journal> ){
  38528. ** if( NOT SAFE_APPEND ){
  38529. ** if( <full-sync mode> ) xSync(<journal file>);
  38530. ** <update nRec field>
  38531. ** }
  38532. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  38533. ** }
  38534. **
  38535. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  38536. ** page currently held in memory before returning SQLITE_OK. If an IO
  38537. ** error is encountered, then the IO error code is returned to the caller.
  38538. */
  38539. static int syncJournal(Pager *pPager, int newHdr){
  38540. int rc; /* Return code */
  38541. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  38542. || pPager->eState==PAGER_WRITER_DBMOD
  38543. );
  38544. assert( assert_pager_state(pPager) );
  38545. assert( !pagerUseWal(pPager) );
  38546. rc = sqlite3PagerExclusiveLock(pPager);
  38547. if( rc!=SQLITE_OK ) return rc;
  38548. if( !pPager->noSync ){
  38549. assert( !pPager->tempFile );
  38550. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  38551. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  38552. assert( isOpen(pPager->jfd) );
  38553. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  38554. /* This block deals with an obscure problem. If the last connection
  38555. ** that wrote to this database was operating in persistent-journal
  38556. ** mode, then the journal file may at this point actually be larger
  38557. ** than Pager.journalOff bytes. If the next thing in the journal
  38558. ** file happens to be a journal-header (written as part of the
  38559. ** previous connection's transaction), and a crash or power-failure
  38560. ** occurs after nRec is updated but before this connection writes
  38561. ** anything else to the journal file (or commits/rolls back its
  38562. ** transaction), then SQLite may become confused when doing the
  38563. ** hot-journal rollback following recovery. It may roll back all
  38564. ** of this connections data, then proceed to rolling back the old,
  38565. ** out-of-date data that follows it. Database corruption.
  38566. **
  38567. ** To work around this, if the journal file does appear to contain
  38568. ** a valid header following Pager.journalOff, then write a 0x00
  38569. ** byte to the start of it to prevent it from being recognized.
  38570. **
  38571. ** Variable iNextHdrOffset is set to the offset at which this
  38572. ** problematic header will occur, if it exists. aMagic is used
  38573. ** as a temporary buffer to inspect the first couple of bytes of
  38574. ** the potential journal header.
  38575. */
  38576. i64 iNextHdrOffset;
  38577. u8 aMagic[8];
  38578. u8 zHeader[sizeof(aJournalMagic)+4];
  38579. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  38580. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  38581. iNextHdrOffset = journalHdrOffset(pPager);
  38582. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  38583. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  38584. static const u8 zerobyte = 0;
  38585. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  38586. }
  38587. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  38588. return rc;
  38589. }
  38590. /* Write the nRec value into the journal file header. If in
  38591. ** full-synchronous mode, sync the journal first. This ensures that
  38592. ** all data has really hit the disk before nRec is updated to mark
  38593. ** it as a candidate for rollback.
  38594. **
  38595. ** This is not required if the persistent media supports the
  38596. ** SAFE_APPEND property. Because in this case it is not possible
  38597. ** for garbage data to be appended to the file, the nRec field
  38598. ** is populated with 0xFFFFFFFF when the journal header is written
  38599. ** and never needs to be updated.
  38600. */
  38601. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  38602. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  38603. IOTRACE(("JSYNC %p\n", pPager))
  38604. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  38605. if( rc!=SQLITE_OK ) return rc;
  38606. }
  38607. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  38608. rc = sqlite3OsWrite(
  38609. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  38610. );
  38611. if( rc!=SQLITE_OK ) return rc;
  38612. }
  38613. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  38614. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  38615. IOTRACE(("JSYNC %p\n", pPager))
  38616. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  38617. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  38618. );
  38619. if( rc!=SQLITE_OK ) return rc;
  38620. }
  38621. pPager->journalHdr = pPager->journalOff;
  38622. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  38623. pPager->nRec = 0;
  38624. rc = writeJournalHdr(pPager);
  38625. if( rc!=SQLITE_OK ) return rc;
  38626. }
  38627. }else{
  38628. pPager->journalHdr = pPager->journalOff;
  38629. }
  38630. }
  38631. /* Unless the pager is in noSync mode, the journal file was just
  38632. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  38633. ** all pages.
  38634. */
  38635. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  38636. pPager->eState = PAGER_WRITER_DBMOD;
  38637. assert( assert_pager_state(pPager) );
  38638. return SQLITE_OK;
  38639. }
  38640. /*
  38641. ** The argument is the first in a linked list of dirty pages connected
  38642. ** by the PgHdr.pDirty pointer. This function writes each one of the
  38643. ** in-memory pages in the list to the database file. The argument may
  38644. ** be NULL, representing an empty list. In this case this function is
  38645. ** a no-op.
  38646. **
  38647. ** The pager must hold at least a RESERVED lock when this function
  38648. ** is called. Before writing anything to the database file, this lock
  38649. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  38650. ** SQLITE_BUSY is returned and no data is written to the database file.
  38651. **
  38652. ** If the pager is a temp-file pager and the actual file-system file
  38653. ** is not yet open, it is created and opened before any data is
  38654. ** written out.
  38655. **
  38656. ** Once the lock has been upgraded and, if necessary, the file opened,
  38657. ** the pages are written out to the database file in list order. Writing
  38658. ** a page is skipped if it meets either of the following criteria:
  38659. **
  38660. ** * The page number is greater than Pager.dbSize, or
  38661. ** * The PGHDR_DONT_WRITE flag is set on the page.
  38662. **
  38663. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  38664. ** is updated accordingly. If page 1 is written out, then the value cached
  38665. ** in Pager.dbFileVers[] is updated to match the new value stored in
  38666. ** the database file.
  38667. **
  38668. ** If everything is successful, SQLITE_OK is returned. If an IO error
  38669. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  38670. ** be obtained, SQLITE_BUSY is returned.
  38671. */
  38672. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  38673. int rc = SQLITE_OK; /* Return code */
  38674. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  38675. assert( !pagerUseWal(pPager) );
  38676. assert( pPager->eState==PAGER_WRITER_DBMOD );
  38677. assert( pPager->eLock==EXCLUSIVE_LOCK );
  38678. /* If the file is a temp-file has not yet been opened, open it now. It
  38679. ** is not possible for rc to be other than SQLITE_OK if this branch
  38680. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  38681. */
  38682. if( !isOpen(pPager->fd) ){
  38683. assert( pPager->tempFile && rc==SQLITE_OK );
  38684. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  38685. }
  38686. /* Before the first write, give the VFS a hint of what the final
  38687. ** file size will be.
  38688. */
  38689. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  38690. if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
  38691. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  38692. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  38693. pPager->dbHintSize = pPager->dbSize;
  38694. }
  38695. while( rc==SQLITE_OK && pList ){
  38696. Pgno pgno = pList->pgno;
  38697. /* If there are dirty pages in the page cache with page numbers greater
  38698. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  38699. ** make the file smaller (presumably by auto-vacuum code). Do not write
  38700. ** any such pages to the file.
  38701. **
  38702. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  38703. ** set (set by sqlite3PagerDontWrite()).
  38704. */
  38705. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  38706. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  38707. char *pData; /* Data to write */
  38708. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  38709. if( pList->pgno==1 ) pager_write_changecounter(pList);
  38710. /* Encode the database */
  38711. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  38712. /* Write out the page data. */
  38713. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  38714. /* If page 1 was just written, update Pager.dbFileVers to match
  38715. ** the value now stored in the database file. If writing this
  38716. ** page caused the database file to grow, update dbFileSize.
  38717. */
  38718. if( pgno==1 ){
  38719. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  38720. }
  38721. if( pgno>pPager->dbFileSize ){
  38722. pPager->dbFileSize = pgno;
  38723. }
  38724. pPager->aStat[PAGER_STAT_WRITE]++;
  38725. /* Update any backup objects copying the contents of this pager. */
  38726. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  38727. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  38728. PAGERID(pPager), pgno, pager_pagehash(pList)));
  38729. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  38730. PAGER_INCR(sqlite3_pager_writedb_count);
  38731. }else{
  38732. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  38733. }
  38734. pager_set_pagehash(pList);
  38735. pList = pList->pDirty;
  38736. }
  38737. return rc;
  38738. }
  38739. /*
  38740. ** Ensure that the sub-journal file is open. If it is already open, this
  38741. ** function is a no-op.
  38742. **
  38743. ** SQLITE_OK is returned if everything goes according to plan. An
  38744. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  38745. ** fails.
  38746. */
  38747. static int openSubJournal(Pager *pPager){
  38748. int rc = SQLITE_OK;
  38749. if( !isOpen(pPager->sjfd) ){
  38750. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  38751. sqlite3MemJournalOpen(pPager->sjfd);
  38752. }else{
  38753. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  38754. }
  38755. }
  38756. return rc;
  38757. }
  38758. /*
  38759. ** Append a record of the current state of page pPg to the sub-journal.
  38760. ** It is the callers responsibility to use subjRequiresPage() to check
  38761. ** that it is really required before calling this function.
  38762. **
  38763. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  38764. ** for all open savepoints before returning.
  38765. **
  38766. ** This function returns SQLITE_OK if everything is successful, an IO
  38767. ** error code if the attempt to write to the sub-journal fails, or
  38768. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  38769. ** bitvec.
  38770. */
  38771. static int subjournalPage(PgHdr *pPg){
  38772. int rc = SQLITE_OK;
  38773. Pager *pPager = pPg->pPager;
  38774. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  38775. /* Open the sub-journal, if it has not already been opened */
  38776. assert( pPager->useJournal );
  38777. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  38778. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  38779. assert( pagerUseWal(pPager)
  38780. || pageInJournal(pPg)
  38781. || pPg->pgno>pPager->dbOrigSize
  38782. );
  38783. rc = openSubJournal(pPager);
  38784. /* If the sub-journal was opened successfully (or was already open),
  38785. ** write the journal record into the file. */
  38786. if( rc==SQLITE_OK ){
  38787. void *pData = pPg->pData;
  38788. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  38789. char *pData2;
  38790. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  38791. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  38792. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  38793. if( rc==SQLITE_OK ){
  38794. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  38795. }
  38796. }
  38797. }
  38798. if( rc==SQLITE_OK ){
  38799. pPager->nSubRec++;
  38800. assert( pPager->nSavepoint>0 );
  38801. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  38802. }
  38803. return rc;
  38804. }
  38805. /*
  38806. ** This function is called by the pcache layer when it has reached some
  38807. ** soft memory limit. The first argument is a pointer to a Pager object
  38808. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  38809. ** database). The second argument is a reference to a page that is
  38810. ** currently dirty but has no outstanding references. The page
  38811. ** is always associated with the Pager object passed as the first
  38812. ** argument.
  38813. **
  38814. ** The job of this function is to make pPg clean by writing its contents
  38815. ** out to the database file, if possible. This may involve syncing the
  38816. ** journal file.
  38817. **
  38818. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  38819. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  38820. ** page clean, the IO error code is returned. If the page cannot be
  38821. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  38822. ** is returned by sqlite3PcacheMakeClean() is not called.
  38823. */
  38824. static int pagerStress(void *p, PgHdr *pPg){
  38825. Pager *pPager = (Pager *)p;
  38826. int rc = SQLITE_OK;
  38827. assert( pPg->pPager==pPager );
  38828. assert( pPg->flags&PGHDR_DIRTY );
  38829. /* The doNotSyncSpill flag is set during times when doing a sync of
  38830. ** journal (and adding a new header) is not allowed. This occurs
  38831. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  38832. ** pages belonging to the same sector.
  38833. **
  38834. ** The doNotSpill flag inhibits all cache spilling regardless of whether
  38835. ** or not a sync is required. This is set during a rollback.
  38836. **
  38837. ** Spilling is also prohibited when in an error state since that could
  38838. ** lead to database corruption. In the current implementaton it
  38839. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  38840. ** while in the error state, hence it is impossible for this routine to
  38841. ** be called in the error state. Nevertheless, we include a NEVER()
  38842. ** test for the error state as a safeguard against future changes.
  38843. */
  38844. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  38845. if( pPager->doNotSpill ) return SQLITE_OK;
  38846. if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
  38847. return SQLITE_OK;
  38848. }
  38849. pPg->pDirty = 0;
  38850. if( pagerUseWal(pPager) ){
  38851. /* Write a single frame for this page to the log. */
  38852. if( subjRequiresPage(pPg) ){
  38853. rc = subjournalPage(pPg);
  38854. }
  38855. if( rc==SQLITE_OK ){
  38856. rc = pagerWalFrames(pPager, pPg, 0, 0);
  38857. }
  38858. }else{
  38859. /* Sync the journal file if required. */
  38860. if( pPg->flags&PGHDR_NEED_SYNC
  38861. || pPager->eState==PAGER_WRITER_CACHEMOD
  38862. ){
  38863. rc = syncJournal(pPager, 1);
  38864. }
  38865. /* If the page number of this page is larger than the current size of
  38866. ** the database image, it may need to be written to the sub-journal.
  38867. ** This is because the call to pager_write_pagelist() below will not
  38868. ** actually write data to the file in this case.
  38869. **
  38870. ** Consider the following sequence of events:
  38871. **
  38872. ** BEGIN;
  38873. ** <journal page X>
  38874. ** <modify page X>
  38875. ** SAVEPOINT sp;
  38876. ** <shrink database file to Y pages>
  38877. ** pagerStress(page X)
  38878. ** ROLLBACK TO sp;
  38879. **
  38880. ** If (X>Y), then when pagerStress is called page X will not be written
  38881. ** out to the database file, but will be dropped from the cache. Then,
  38882. ** following the "ROLLBACK TO sp" statement, reading page X will read
  38883. ** data from the database file. This will be the copy of page X as it
  38884. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  38885. ** was executed.
  38886. **
  38887. ** The solution is to write the current data for page X into the
  38888. ** sub-journal file now (if it is not already there), so that it will
  38889. ** be restored to its current value when the "ROLLBACK TO sp" is
  38890. ** executed.
  38891. */
  38892. if( NEVER(
  38893. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  38894. ) ){
  38895. rc = subjournalPage(pPg);
  38896. }
  38897. /* Write the contents of the page out to the database file. */
  38898. if( rc==SQLITE_OK ){
  38899. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  38900. rc = pager_write_pagelist(pPager, pPg);
  38901. }
  38902. }
  38903. /* Mark the page as clean. */
  38904. if( rc==SQLITE_OK ){
  38905. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  38906. sqlite3PcacheMakeClean(pPg);
  38907. }
  38908. return pager_error(pPager, rc);
  38909. }
  38910. /*
  38911. ** Allocate and initialize a new Pager object and put a pointer to it
  38912. ** in *ppPager. The pager should eventually be freed by passing it
  38913. ** to sqlite3PagerClose().
  38914. **
  38915. ** The zFilename argument is the path to the database file to open.
  38916. ** If zFilename is NULL then a randomly-named temporary file is created
  38917. ** and used as the file to be cached. Temporary files are be deleted
  38918. ** automatically when they are closed. If zFilename is ":memory:" then
  38919. ** all information is held in cache. It is never written to disk.
  38920. ** This can be used to implement an in-memory database.
  38921. **
  38922. ** The nExtra parameter specifies the number of bytes of space allocated
  38923. ** along with each page reference. This space is available to the user
  38924. ** via the sqlite3PagerGetExtra() API.
  38925. **
  38926. ** The flags argument is used to specify properties that affect the
  38927. ** operation of the pager. It should be passed some bitwise combination
  38928. ** of the PAGER_* flags.
  38929. **
  38930. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  38931. ** of the xOpen() method of the supplied VFS when opening files.
  38932. **
  38933. ** If the pager object is allocated and the specified file opened
  38934. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  38935. ** the new pager object. If an error occurs, *ppPager is set to NULL
  38936. ** and error code returned. This function may return SQLITE_NOMEM
  38937. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  38938. ** various SQLITE_IO_XXX errors.
  38939. */
  38940. SQLITE_PRIVATE int sqlite3PagerOpen(
  38941. sqlite3_vfs *pVfs, /* The virtual file system to use */
  38942. Pager **ppPager, /* OUT: Return the Pager structure here */
  38943. const char *zFilename, /* Name of the database file to open */
  38944. int nExtra, /* Extra bytes append to each in-memory page */
  38945. int flags, /* flags controlling this file */
  38946. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  38947. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  38948. ){
  38949. u8 *pPtr;
  38950. Pager *pPager = 0; /* Pager object to allocate and return */
  38951. int rc = SQLITE_OK; /* Return code */
  38952. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  38953. int memDb = 0; /* True if this is an in-memory file */
  38954. int readOnly = 0; /* True if this is a read-only file */
  38955. int journalFileSize; /* Bytes to allocate for each journal fd */
  38956. char *zPathname = 0; /* Full path to database file */
  38957. int nPathname = 0; /* Number of bytes in zPathname */
  38958. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  38959. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  38960. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  38961. const char *zUri = 0; /* URI args to copy */
  38962. int nUri = 0; /* Number of bytes of URI args at *zUri */
  38963. /* Figure out how much space is required for each journal file-handle
  38964. ** (there are two of them, the main journal and the sub-journal). This
  38965. ** is the maximum space required for an in-memory journal file handle
  38966. ** and a regular journal file-handle. Note that a "regular journal-handle"
  38967. ** may be a wrapper capable of caching the first portion of the journal
  38968. ** file in memory to implement the atomic-write optimization (see
  38969. ** source file journal.c).
  38970. */
  38971. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  38972. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  38973. }else{
  38974. journalFileSize = ROUND8(sqlite3MemJournalSize());
  38975. }
  38976. /* Set the output variable to NULL in case an error occurs. */
  38977. *ppPager = 0;
  38978. #ifndef SQLITE_OMIT_MEMORYDB
  38979. if( flags & PAGER_MEMORY ){
  38980. memDb = 1;
  38981. if( zFilename && zFilename[0] ){
  38982. zPathname = sqlite3DbStrDup(0, zFilename);
  38983. if( zPathname==0 ) return SQLITE_NOMEM;
  38984. nPathname = sqlite3Strlen30(zPathname);
  38985. zFilename = 0;
  38986. }
  38987. }
  38988. #endif
  38989. /* Compute and store the full pathname in an allocated buffer pointed
  38990. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  38991. ** leave both nPathname and zPathname set to 0.
  38992. */
  38993. if( zFilename && zFilename[0] ){
  38994. const char *z;
  38995. nPathname = pVfs->mxPathname+1;
  38996. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  38997. if( zPathname==0 ){
  38998. return SQLITE_NOMEM;
  38999. }
  39000. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  39001. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  39002. nPathname = sqlite3Strlen30(zPathname);
  39003. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  39004. while( *z ){
  39005. z += sqlite3Strlen30(z)+1;
  39006. z += sqlite3Strlen30(z)+1;
  39007. }
  39008. nUri = (int)(&z[1] - zUri);
  39009. assert( nUri>=0 );
  39010. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  39011. /* This branch is taken when the journal path required by
  39012. ** the database being opened will be more than pVfs->mxPathname
  39013. ** bytes in length. This means the database cannot be opened,
  39014. ** as it will not be possible to open the journal file or even
  39015. ** check for a hot-journal before reading.
  39016. */
  39017. rc = SQLITE_CANTOPEN_BKPT;
  39018. }
  39019. if( rc!=SQLITE_OK ){
  39020. sqlite3DbFree(0, zPathname);
  39021. return rc;
  39022. }
  39023. }
  39024. /* Allocate memory for the Pager structure, PCache object, the
  39025. ** three file descriptors, the database file name and the journal
  39026. ** file name. The layout in memory is as follows:
  39027. **
  39028. ** Pager object (sizeof(Pager) bytes)
  39029. ** PCache object (sqlite3PcacheSize() bytes)
  39030. ** Database file handle (pVfs->szOsFile bytes)
  39031. ** Sub-journal file handle (journalFileSize bytes)
  39032. ** Main journal file handle (journalFileSize bytes)
  39033. ** Database file name (nPathname+1 bytes)
  39034. ** Journal file name (nPathname+8+1 bytes)
  39035. */
  39036. pPtr = (u8 *)sqlite3MallocZero(
  39037. ROUND8(sizeof(*pPager)) + /* Pager structure */
  39038. ROUND8(pcacheSize) + /* PCache object */
  39039. ROUND8(pVfs->szOsFile) + /* The main db file */
  39040. journalFileSize * 2 + /* The two journal files */
  39041. nPathname + 1 + nUri + /* zFilename */
  39042. nPathname + 8 + 2 /* zJournal */
  39043. #ifndef SQLITE_OMIT_WAL
  39044. + nPathname + 4 + 2 /* zWal */
  39045. #endif
  39046. );
  39047. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  39048. if( !pPtr ){
  39049. sqlite3DbFree(0, zPathname);
  39050. return SQLITE_NOMEM;
  39051. }
  39052. pPager = (Pager*)(pPtr);
  39053. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  39054. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  39055. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  39056. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  39057. pPager->zFilename = (char*)(pPtr += journalFileSize);
  39058. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  39059. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  39060. if( zPathname ){
  39061. assert( nPathname>0 );
  39062. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  39063. memcpy(pPager->zFilename, zPathname, nPathname);
  39064. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  39065. memcpy(pPager->zJournal, zPathname, nPathname);
  39066. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  39067. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  39068. #ifndef SQLITE_OMIT_WAL
  39069. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  39070. memcpy(pPager->zWal, zPathname, nPathname);
  39071. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  39072. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  39073. #endif
  39074. sqlite3DbFree(0, zPathname);
  39075. }
  39076. pPager->pVfs = pVfs;
  39077. pPager->vfsFlags = vfsFlags;
  39078. /* Open the pager file.
  39079. */
  39080. if( zFilename && zFilename[0] ){
  39081. int fout = 0; /* VFS flags returned by xOpen() */
  39082. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  39083. assert( !memDb );
  39084. readOnly = (fout&SQLITE_OPEN_READONLY);
  39085. /* If the file was successfully opened for read/write access,
  39086. ** choose a default page size in case we have to create the
  39087. ** database file. The default page size is the maximum of:
  39088. **
  39089. ** + SQLITE_DEFAULT_PAGE_SIZE,
  39090. ** + The value returned by sqlite3OsSectorSize()
  39091. ** + The largest page size that can be written atomically.
  39092. */
  39093. if( rc==SQLITE_OK && !readOnly ){
  39094. setSectorSize(pPager);
  39095. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  39096. if( szPageDflt<pPager->sectorSize ){
  39097. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  39098. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  39099. }else{
  39100. szPageDflt = (u32)pPager->sectorSize;
  39101. }
  39102. }
  39103. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  39104. {
  39105. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  39106. int ii;
  39107. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  39108. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  39109. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  39110. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  39111. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  39112. szPageDflt = ii;
  39113. }
  39114. }
  39115. }
  39116. #endif
  39117. }
  39118. }else{
  39119. /* If a temporary file is requested, it is not opened immediately.
  39120. ** In this case we accept the default page size and delay actually
  39121. ** opening the file until the first call to OsWrite().
  39122. **
  39123. ** This branch is also run for an in-memory database. An in-memory
  39124. ** database is the same as a temp-file that is never written out to
  39125. ** disk and uses an in-memory rollback journal.
  39126. */
  39127. tempFile = 1;
  39128. pPager->eState = PAGER_READER;
  39129. pPager->eLock = EXCLUSIVE_LOCK;
  39130. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  39131. }
  39132. /* The following call to PagerSetPagesize() serves to set the value of
  39133. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  39134. */
  39135. if( rc==SQLITE_OK ){
  39136. assert( pPager->memDb==0 );
  39137. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  39138. testcase( rc!=SQLITE_OK );
  39139. }
  39140. /* If an error occurred in either of the blocks above, free the
  39141. ** Pager structure and close the file.
  39142. */
  39143. if( rc!=SQLITE_OK ){
  39144. assert( !pPager->pTmpSpace );
  39145. sqlite3OsClose(pPager->fd);
  39146. sqlite3_free(pPager);
  39147. return rc;
  39148. }
  39149. /* Initialize the PCache object. */
  39150. assert( nExtra<1000 );
  39151. nExtra = ROUND8(nExtra);
  39152. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  39153. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  39154. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  39155. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  39156. pPager->useJournal = (u8)useJournal;
  39157. /* pPager->stmtOpen = 0; */
  39158. /* pPager->stmtInUse = 0; */
  39159. /* pPager->nRef = 0; */
  39160. /* pPager->stmtSize = 0; */
  39161. /* pPager->stmtJSize = 0; */
  39162. /* pPager->nPage = 0; */
  39163. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  39164. /* pPager->state = PAGER_UNLOCK; */
  39165. #if 0
  39166. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  39167. #endif
  39168. /* pPager->errMask = 0; */
  39169. pPager->tempFile = (u8)tempFile;
  39170. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  39171. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  39172. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  39173. pPager->exclusiveMode = (u8)tempFile;
  39174. pPager->changeCountDone = pPager->tempFile;
  39175. pPager->memDb = (u8)memDb;
  39176. pPager->readOnly = (u8)readOnly;
  39177. assert( useJournal || pPager->tempFile );
  39178. pPager->noSync = pPager->tempFile;
  39179. if( pPager->noSync ){
  39180. assert( pPager->fullSync==0 );
  39181. assert( pPager->syncFlags==0 );
  39182. assert( pPager->walSyncFlags==0 );
  39183. assert( pPager->ckptSyncFlags==0 );
  39184. }else{
  39185. pPager->fullSync = 1;
  39186. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  39187. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  39188. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  39189. }
  39190. /* pPager->pFirst = 0; */
  39191. /* pPager->pFirstSynced = 0; */
  39192. /* pPager->pLast = 0; */
  39193. pPager->nExtra = (u16)nExtra;
  39194. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  39195. assert( isOpen(pPager->fd) || tempFile );
  39196. setSectorSize(pPager);
  39197. if( !useJournal ){
  39198. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  39199. }else if( memDb ){
  39200. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  39201. }
  39202. /* pPager->xBusyHandler = 0; */
  39203. /* pPager->pBusyHandlerArg = 0; */
  39204. pPager->xReiniter = xReinit;
  39205. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  39206. *ppPager = pPager;
  39207. return SQLITE_OK;
  39208. }
  39209. /*
  39210. ** This function is called after transitioning from PAGER_UNLOCK to
  39211. ** PAGER_SHARED state. It tests if there is a hot journal present in
  39212. ** the file-system for the given pager. A hot journal is one that
  39213. ** needs to be played back. According to this function, a hot-journal
  39214. ** file exists if the following criteria are met:
  39215. **
  39216. ** * The journal file exists in the file system, and
  39217. ** * No process holds a RESERVED or greater lock on the database file, and
  39218. ** * The database file itself is greater than 0 bytes in size, and
  39219. ** * The first byte of the journal file exists and is not 0x00.
  39220. **
  39221. ** If the current size of the database file is 0 but a journal file
  39222. ** exists, that is probably an old journal left over from a prior
  39223. ** database with the same name. In this case the journal file is
  39224. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  39225. ** is returned.
  39226. **
  39227. ** This routine does not check if there is a master journal filename
  39228. ** at the end of the file. If there is, and that master journal file
  39229. ** does not exist, then the journal file is not really hot. In this
  39230. ** case this routine will return a false-positive. The pager_playback()
  39231. ** routine will discover that the journal file is not really hot and
  39232. ** will not roll it back.
  39233. **
  39234. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  39235. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  39236. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  39237. ** to determine whether or not a hot-journal file exists, the IO error
  39238. ** code is returned and the value of *pExists is undefined.
  39239. */
  39240. static int hasHotJournal(Pager *pPager, int *pExists){
  39241. sqlite3_vfs * const pVfs = pPager->pVfs;
  39242. int rc = SQLITE_OK; /* Return code */
  39243. int exists = 1; /* True if a journal file is present */
  39244. int jrnlOpen = !!isOpen(pPager->jfd);
  39245. assert( pPager->useJournal );
  39246. assert( isOpen(pPager->fd) );
  39247. assert( pPager->eState==PAGER_OPEN );
  39248. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  39249. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  39250. ));
  39251. *pExists = 0;
  39252. if( !jrnlOpen ){
  39253. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  39254. }
  39255. if( rc==SQLITE_OK && exists ){
  39256. int locked = 0; /* True if some process holds a RESERVED lock */
  39257. /* Race condition here: Another process might have been holding the
  39258. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  39259. ** call above, but then delete the journal and drop the lock before
  39260. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  39261. ** is the case, this routine might think there is a hot journal when
  39262. ** in fact there is none. This results in a false-positive which will
  39263. ** be dealt with by the playback routine. Ticket #3883.
  39264. */
  39265. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  39266. if( rc==SQLITE_OK && !locked ){
  39267. Pgno nPage; /* Number of pages in database file */
  39268. /* Check the size of the database file. If it consists of 0 pages,
  39269. ** then delete the journal file. See the header comment above for
  39270. ** the reasoning here. Delete the obsolete journal file under
  39271. ** a RESERVED lock to avoid race conditions and to avoid violating
  39272. ** [H33020].
  39273. */
  39274. rc = pagerPagecount(pPager, &nPage);
  39275. if( rc==SQLITE_OK ){
  39276. if( nPage==0 ){
  39277. sqlite3BeginBenignMalloc();
  39278. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  39279. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  39280. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  39281. }
  39282. sqlite3EndBenignMalloc();
  39283. }else{
  39284. /* The journal file exists and no other connection has a reserved
  39285. ** or greater lock on the database file. Now check that there is
  39286. ** at least one non-zero bytes at the start of the journal file.
  39287. ** If there is, then we consider this journal to be hot. If not,
  39288. ** it can be ignored.
  39289. */
  39290. if( !jrnlOpen ){
  39291. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  39292. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  39293. }
  39294. if( rc==SQLITE_OK ){
  39295. u8 first = 0;
  39296. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  39297. if( rc==SQLITE_IOERR_SHORT_READ ){
  39298. rc = SQLITE_OK;
  39299. }
  39300. if( !jrnlOpen ){
  39301. sqlite3OsClose(pPager->jfd);
  39302. }
  39303. *pExists = (first!=0);
  39304. }else if( rc==SQLITE_CANTOPEN ){
  39305. /* If we cannot open the rollback journal file in order to see if
  39306. ** its has a zero header, that might be due to an I/O error, or
  39307. ** it might be due to the race condition described above and in
  39308. ** ticket #3883. Either way, assume that the journal is hot.
  39309. ** This might be a false positive. But if it is, then the
  39310. ** automatic journal playback and recovery mechanism will deal
  39311. ** with it under an EXCLUSIVE lock where we do not need to
  39312. ** worry so much with race conditions.
  39313. */
  39314. *pExists = 1;
  39315. rc = SQLITE_OK;
  39316. }
  39317. }
  39318. }
  39319. }
  39320. }
  39321. return rc;
  39322. }
  39323. /*
  39324. ** This function is called to obtain a shared lock on the database file.
  39325. ** It is illegal to call sqlite3PagerAcquire() until after this function
  39326. ** has been successfully called. If a shared-lock is already held when
  39327. ** this function is called, it is a no-op.
  39328. **
  39329. ** The following operations are also performed by this function.
  39330. **
  39331. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  39332. ** on the database file), then an attempt is made to obtain a
  39333. ** SHARED lock on the database file. Immediately after obtaining
  39334. ** the SHARED lock, the file-system is checked for a hot-journal,
  39335. ** which is played back if present. Following any hot-journal
  39336. ** rollback, the contents of the cache are validated by checking
  39337. ** the 'change-counter' field of the database file header and
  39338. ** discarded if they are found to be invalid.
  39339. **
  39340. ** 2) If the pager is running in exclusive-mode, and there are currently
  39341. ** no outstanding references to any pages, and is in the error state,
  39342. ** then an attempt is made to clear the error state by discarding
  39343. ** the contents of the page cache and rolling back any open journal
  39344. ** file.
  39345. **
  39346. ** If everything is successful, SQLITE_OK is returned. If an IO error
  39347. ** occurs while locking the database, checking for a hot-journal file or
  39348. ** rolling back a journal file, the IO error code is returned.
  39349. */
  39350. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  39351. int rc = SQLITE_OK; /* Return code */
  39352. /* This routine is only called from b-tree and only when there are no
  39353. ** outstanding pages. This implies that the pager state should either
  39354. ** be OPEN or READER. READER is only possible if the pager is or was in
  39355. ** exclusive access mode.
  39356. */
  39357. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  39358. assert( assert_pager_state(pPager) );
  39359. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  39360. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  39361. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  39362. int bHotJournal = 1; /* True if there exists a hot journal-file */
  39363. assert( !MEMDB );
  39364. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  39365. if( rc!=SQLITE_OK ){
  39366. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  39367. goto failed;
  39368. }
  39369. /* If a journal file exists, and there is no RESERVED lock on the
  39370. ** database file, then it either needs to be played back or deleted.
  39371. */
  39372. if( pPager->eLock<=SHARED_LOCK ){
  39373. rc = hasHotJournal(pPager, &bHotJournal);
  39374. }
  39375. if( rc!=SQLITE_OK ){
  39376. goto failed;
  39377. }
  39378. if( bHotJournal ){
  39379. /* Get an EXCLUSIVE lock on the database file. At this point it is
  39380. ** important that a RESERVED lock is not obtained on the way to the
  39381. ** EXCLUSIVE lock. If it were, another process might open the
  39382. ** database file, detect the RESERVED lock, and conclude that the
  39383. ** database is safe to read while this process is still rolling the
  39384. ** hot-journal back.
  39385. **
  39386. ** Because the intermediate RESERVED lock is not requested, any
  39387. ** other process attempting to access the database file will get to
  39388. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  39389. ** on the database file.
  39390. **
  39391. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  39392. ** downgraded to SHARED_LOCK before this function returns.
  39393. */
  39394. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  39395. if( rc!=SQLITE_OK ){
  39396. goto failed;
  39397. }
  39398. /* If it is not already open and the file exists on disk, open the
  39399. ** journal for read/write access. Write access is required because
  39400. ** in exclusive-access mode the file descriptor will be kept open
  39401. ** and possibly used for a transaction later on. Also, write-access
  39402. ** is usually required to finalize the journal in journal_mode=persist
  39403. ** mode (and also for journal_mode=truncate on some systems).
  39404. **
  39405. ** If the journal does not exist, it usually means that some
  39406. ** other connection managed to get in and roll it back before
  39407. ** this connection obtained the exclusive lock above. Or, it
  39408. ** may mean that the pager was in the error-state when this
  39409. ** function was called and the journal file does not exist.
  39410. */
  39411. if( !isOpen(pPager->jfd) ){
  39412. sqlite3_vfs * const pVfs = pPager->pVfs;
  39413. int bExists; /* True if journal file exists */
  39414. rc = sqlite3OsAccess(
  39415. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  39416. if( rc==SQLITE_OK && bExists ){
  39417. int fout = 0;
  39418. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  39419. assert( !pPager->tempFile );
  39420. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  39421. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  39422. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  39423. rc = SQLITE_CANTOPEN_BKPT;
  39424. sqlite3OsClose(pPager->jfd);
  39425. }
  39426. }
  39427. }
  39428. /* Playback and delete the journal. Drop the database write
  39429. ** lock and reacquire the read lock. Purge the cache before
  39430. ** playing back the hot-journal so that we don't end up with
  39431. ** an inconsistent cache. Sync the hot journal before playing
  39432. ** it back since the process that crashed and left the hot journal
  39433. ** probably did not sync it and we are required to always sync
  39434. ** the journal before playing it back.
  39435. */
  39436. if( isOpen(pPager->jfd) ){
  39437. assert( rc==SQLITE_OK );
  39438. rc = pagerSyncHotJournal(pPager);
  39439. if( rc==SQLITE_OK ){
  39440. rc = pager_playback(pPager, 1);
  39441. pPager->eState = PAGER_OPEN;
  39442. }
  39443. }else if( !pPager->exclusiveMode ){
  39444. pagerUnlockDb(pPager, SHARED_LOCK);
  39445. }
  39446. if( rc!=SQLITE_OK ){
  39447. /* This branch is taken if an error occurs while trying to open
  39448. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  39449. ** pager_unlock() routine will be called before returning to unlock
  39450. ** the file. If the unlock attempt fails, then Pager.eLock must be
  39451. ** set to UNKNOWN_LOCK (see the comment above the #define for
  39452. ** UNKNOWN_LOCK above for an explanation).
  39453. **
  39454. ** In order to get pager_unlock() to do this, set Pager.eState to
  39455. ** PAGER_ERROR now. This is not actually counted as a transition
  39456. ** to ERROR state in the state diagram at the top of this file,
  39457. ** since we know that the same call to pager_unlock() will very
  39458. ** shortly transition the pager object to the OPEN state. Calling
  39459. ** assert_pager_state() would fail now, as it should not be possible
  39460. ** to be in ERROR state when there are zero outstanding page
  39461. ** references.
  39462. */
  39463. pager_error(pPager, rc);
  39464. goto failed;
  39465. }
  39466. assert( pPager->eState==PAGER_OPEN );
  39467. assert( (pPager->eLock==SHARED_LOCK)
  39468. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  39469. );
  39470. }
  39471. if( !pPager->tempFile
  39472. && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
  39473. ){
  39474. /* The shared-lock has just been acquired on the database file
  39475. ** and there are already pages in the cache (from a previous
  39476. ** read or write transaction). Check to see if the database
  39477. ** has been modified. If the database has changed, flush the
  39478. ** cache.
  39479. **
  39480. ** Database changes is detected by looking at 15 bytes beginning
  39481. ** at offset 24 into the file. The first 4 of these 16 bytes are
  39482. ** a 32-bit counter that is incremented with each change. The
  39483. ** other bytes change randomly with each file change when
  39484. ** a codec is in use.
  39485. **
  39486. ** There is a vanishingly small chance that a change will not be
  39487. ** detected. The chance of an undetected change is so small that
  39488. ** it can be neglected.
  39489. */
  39490. Pgno nPage = 0;
  39491. char dbFileVers[sizeof(pPager->dbFileVers)];
  39492. rc = pagerPagecount(pPager, &nPage);
  39493. if( rc ) goto failed;
  39494. if( nPage>0 ){
  39495. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  39496. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  39497. if( rc!=SQLITE_OK ){
  39498. goto failed;
  39499. }
  39500. }else{
  39501. memset(dbFileVers, 0, sizeof(dbFileVers));
  39502. }
  39503. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  39504. pager_reset(pPager);
  39505. }
  39506. }
  39507. /* If there is a WAL file in the file-system, open this database in WAL
  39508. ** mode. Otherwise, the following function call is a no-op.
  39509. */
  39510. rc = pagerOpenWalIfPresent(pPager);
  39511. #ifndef SQLITE_OMIT_WAL
  39512. assert( pPager->pWal==0 || rc==SQLITE_OK );
  39513. #endif
  39514. }
  39515. if( pagerUseWal(pPager) ){
  39516. assert( rc==SQLITE_OK );
  39517. rc = pagerBeginReadTransaction(pPager);
  39518. }
  39519. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  39520. rc = pagerPagecount(pPager, &pPager->dbSize);
  39521. }
  39522. failed:
  39523. if( rc!=SQLITE_OK ){
  39524. assert( !MEMDB );
  39525. pager_unlock(pPager);
  39526. assert( pPager->eState==PAGER_OPEN );
  39527. }else{
  39528. pPager->eState = PAGER_READER;
  39529. }
  39530. return rc;
  39531. }
  39532. /*
  39533. ** If the reference count has reached zero, rollback any active
  39534. ** transaction and unlock the pager.
  39535. **
  39536. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  39537. ** the rollback journal, the unlock is not performed and there is
  39538. ** nothing to rollback, so this routine is a no-op.
  39539. */
  39540. static void pagerUnlockIfUnused(Pager *pPager){
  39541. if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  39542. pagerUnlockAndRollback(pPager);
  39543. }
  39544. }
  39545. /*
  39546. ** Acquire a reference to page number pgno in pager pPager (a page
  39547. ** reference has type DbPage*). If the requested reference is
  39548. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  39549. **
  39550. ** If the requested page is already in the cache, it is returned.
  39551. ** Otherwise, a new page object is allocated and populated with data
  39552. ** read from the database file. In some cases, the pcache module may
  39553. ** choose not to allocate a new page object and may reuse an existing
  39554. ** object with no outstanding references.
  39555. **
  39556. ** The extra data appended to a page is always initialized to zeros the
  39557. ** first time a page is loaded into memory. If the page requested is
  39558. ** already in the cache when this function is called, then the extra
  39559. ** data is left as it was when the page object was last used.
  39560. **
  39561. ** If the database image is smaller than the requested page or if a
  39562. ** non-zero value is passed as the noContent parameter and the
  39563. ** requested page is not already stored in the cache, then no
  39564. ** actual disk read occurs. In this case the memory image of the
  39565. ** page is initialized to all zeros.
  39566. **
  39567. ** If noContent is true, it means that we do not care about the contents
  39568. ** of the page. This occurs in two seperate scenarios:
  39569. **
  39570. ** a) When reading a free-list leaf page from the database, and
  39571. **
  39572. ** b) When a savepoint is being rolled back and we need to load
  39573. ** a new page into the cache to be filled with the data read
  39574. ** from the savepoint journal.
  39575. **
  39576. ** If noContent is true, then the data returned is zeroed instead of
  39577. ** being read from the database. Additionally, the bits corresponding
  39578. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  39579. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  39580. ** savepoints are set. This means if the page is made writable at any
  39581. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  39582. ** will not be journaled. This saves IO.
  39583. **
  39584. ** The acquisition might fail for several reasons. In all cases,
  39585. ** an appropriate error code is returned and *ppPage is set to NULL.
  39586. **
  39587. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  39588. ** to find a page in the in-memory cache first. If the page is not already
  39589. ** in memory, this routine goes to disk to read it in whereas Lookup()
  39590. ** just returns 0. This routine acquires a read-lock the first time it
  39591. ** has to go to disk, and could also playback an old journal if necessary.
  39592. ** Since Lookup() never goes to disk, it never has to deal with locks
  39593. ** or journal files.
  39594. */
  39595. SQLITE_PRIVATE int sqlite3PagerAcquire(
  39596. Pager *pPager, /* The pager open on the database file */
  39597. Pgno pgno, /* Page number to fetch */
  39598. DbPage **ppPage, /* Write a pointer to the page here */
  39599. int noContent /* Do not bother reading content from disk if true */
  39600. ){
  39601. int rc;
  39602. PgHdr *pPg;
  39603. assert( pPager->eState>=PAGER_READER );
  39604. assert( assert_pager_state(pPager) );
  39605. if( pgno==0 ){
  39606. return SQLITE_CORRUPT_BKPT;
  39607. }
  39608. /* If the pager is in the error state, return an error immediately.
  39609. ** Otherwise, request the page from the PCache layer. */
  39610. if( pPager->errCode!=SQLITE_OK ){
  39611. rc = pPager->errCode;
  39612. }else{
  39613. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  39614. }
  39615. if( rc!=SQLITE_OK ){
  39616. /* Either the call to sqlite3PcacheFetch() returned an error or the
  39617. ** pager was already in the error-state when this function was called.
  39618. ** Set pPg to 0 and jump to the exception handler. */
  39619. pPg = 0;
  39620. goto pager_acquire_err;
  39621. }
  39622. assert( (*ppPage)->pgno==pgno );
  39623. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  39624. if( (*ppPage)->pPager && !noContent ){
  39625. /* In this case the pcache already contains an initialized copy of
  39626. ** the page. Return without further ado. */
  39627. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  39628. pPager->aStat[PAGER_STAT_HIT]++;
  39629. return SQLITE_OK;
  39630. }else{
  39631. /* The pager cache has created a new page. Its content needs to
  39632. ** be initialized. */
  39633. pPg = *ppPage;
  39634. pPg->pPager = pPager;
  39635. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  39636. ** number greater than this, or the unused locking-page, is requested. */
  39637. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  39638. rc = SQLITE_CORRUPT_BKPT;
  39639. goto pager_acquire_err;
  39640. }
  39641. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  39642. if( pgno>pPager->mxPgno ){
  39643. rc = SQLITE_FULL;
  39644. goto pager_acquire_err;
  39645. }
  39646. if( noContent ){
  39647. /* Failure to set the bits in the InJournal bit-vectors is benign.
  39648. ** It merely means that we might do some extra work to journal a
  39649. ** page that does not need to be journaled. Nevertheless, be sure
  39650. ** to test the case where a malloc error occurs while trying to set
  39651. ** a bit in a bit vector.
  39652. */
  39653. sqlite3BeginBenignMalloc();
  39654. if( pgno<=pPager->dbOrigSize ){
  39655. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  39656. testcase( rc==SQLITE_NOMEM );
  39657. }
  39658. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  39659. testcase( rc==SQLITE_NOMEM );
  39660. sqlite3EndBenignMalloc();
  39661. }
  39662. memset(pPg->pData, 0, pPager->pageSize);
  39663. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  39664. }else{
  39665. assert( pPg->pPager==pPager );
  39666. pPager->aStat[PAGER_STAT_MISS]++;
  39667. rc = readDbPage(pPg);
  39668. if( rc!=SQLITE_OK ){
  39669. goto pager_acquire_err;
  39670. }
  39671. }
  39672. pager_set_pagehash(pPg);
  39673. }
  39674. return SQLITE_OK;
  39675. pager_acquire_err:
  39676. assert( rc!=SQLITE_OK );
  39677. if( pPg ){
  39678. sqlite3PcacheDrop(pPg);
  39679. }
  39680. pagerUnlockIfUnused(pPager);
  39681. *ppPage = 0;
  39682. return rc;
  39683. }
  39684. /*
  39685. ** Acquire a page if it is already in the in-memory cache. Do
  39686. ** not read the page from disk. Return a pointer to the page,
  39687. ** or 0 if the page is not in cache.
  39688. **
  39689. ** See also sqlite3PagerGet(). The difference between this routine
  39690. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  39691. ** in the page if the page is not already in cache. This routine
  39692. ** returns NULL if the page is not in cache or if a disk I/O error
  39693. ** has ever happened.
  39694. */
  39695. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  39696. PgHdr *pPg = 0;
  39697. assert( pPager!=0 );
  39698. assert( pgno!=0 );
  39699. assert( pPager->pPCache!=0 );
  39700. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  39701. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  39702. return pPg;
  39703. }
  39704. /*
  39705. ** Release a page reference.
  39706. **
  39707. ** If the number of references to the page drop to zero, then the
  39708. ** page is added to the LRU list. When all references to all pages
  39709. ** are released, a rollback occurs and the lock on the database is
  39710. ** removed.
  39711. */
  39712. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  39713. if( pPg ){
  39714. Pager *pPager = pPg->pPager;
  39715. sqlite3PcacheRelease(pPg);
  39716. pagerUnlockIfUnused(pPager);
  39717. }
  39718. }
  39719. /*
  39720. ** This function is called at the start of every write transaction.
  39721. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  39722. ** file when this routine is called.
  39723. **
  39724. ** Open the journal file for pager pPager and write a journal header
  39725. ** to the start of it. If there are active savepoints, open the sub-journal
  39726. ** as well. This function is only used when the journal file is being
  39727. ** opened to write a rollback log for a transaction. It is not used
  39728. ** when opening a hot journal file to roll it back.
  39729. **
  39730. ** If the journal file is already open (as it may be in exclusive mode),
  39731. ** then this function just writes a journal header to the start of the
  39732. ** already open file.
  39733. **
  39734. ** Whether or not the journal file is opened by this function, the
  39735. ** Pager.pInJournal bitvec structure is allocated.
  39736. **
  39737. ** Return SQLITE_OK if everything is successful. Otherwise, return
  39738. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  39739. ** an IO error code if opening or writing the journal file fails.
  39740. */
  39741. static int pager_open_journal(Pager *pPager){
  39742. int rc = SQLITE_OK; /* Return code */
  39743. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  39744. assert( pPager->eState==PAGER_WRITER_LOCKED );
  39745. assert( assert_pager_state(pPager) );
  39746. assert( pPager->pInJournal==0 );
  39747. /* If already in the error state, this function is a no-op. But on
  39748. ** the other hand, this routine is never called if we are already in
  39749. ** an error state. */
  39750. if( NEVER(pPager->errCode) ) return pPager->errCode;
  39751. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  39752. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  39753. if( pPager->pInJournal==0 ){
  39754. return SQLITE_NOMEM;
  39755. }
  39756. /* Open the journal file if it is not already open. */
  39757. if( !isOpen(pPager->jfd) ){
  39758. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  39759. sqlite3MemJournalOpen(pPager->jfd);
  39760. }else{
  39761. const int flags = /* VFS flags to open journal file */
  39762. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  39763. (pPager->tempFile ?
  39764. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  39765. (SQLITE_OPEN_MAIN_JOURNAL)
  39766. );
  39767. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  39768. rc = sqlite3JournalOpen(
  39769. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  39770. );
  39771. #else
  39772. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  39773. #endif
  39774. }
  39775. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  39776. }
  39777. /* Write the first journal header to the journal file and open
  39778. ** the sub-journal if necessary.
  39779. */
  39780. if( rc==SQLITE_OK ){
  39781. /* TODO: Check if all of these are really required. */
  39782. pPager->nRec = 0;
  39783. pPager->journalOff = 0;
  39784. pPager->setMaster = 0;
  39785. pPager->journalHdr = 0;
  39786. rc = writeJournalHdr(pPager);
  39787. }
  39788. }
  39789. if( rc!=SQLITE_OK ){
  39790. sqlite3BitvecDestroy(pPager->pInJournal);
  39791. pPager->pInJournal = 0;
  39792. }else{
  39793. assert( pPager->eState==PAGER_WRITER_LOCKED );
  39794. pPager->eState = PAGER_WRITER_CACHEMOD;
  39795. }
  39796. return rc;
  39797. }
  39798. /*
  39799. ** Begin a write-transaction on the specified pager object. If a
  39800. ** write-transaction has already been opened, this function is a no-op.
  39801. **
  39802. ** If the exFlag argument is false, then acquire at least a RESERVED
  39803. ** lock on the database file. If exFlag is true, then acquire at least
  39804. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  39805. ** functions need be called.
  39806. **
  39807. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  39808. ** within this transaction will be opened as an in-memory file. This
  39809. ** has no effect if the sub-journal is already opened (as it may be when
  39810. ** running in exclusive mode) or if the transaction does not require a
  39811. ** sub-journal. If the subjInMemory argument is zero, then any required
  39812. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  39813. ** or using a temporary file otherwise.
  39814. */
  39815. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  39816. int rc = SQLITE_OK;
  39817. if( pPager->errCode ) return pPager->errCode;
  39818. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  39819. pPager->subjInMemory = (u8)subjInMemory;
  39820. if( ALWAYS(pPager->eState==PAGER_READER) ){
  39821. assert( pPager->pInJournal==0 );
  39822. if( pagerUseWal(pPager) ){
  39823. /* If the pager is configured to use locking_mode=exclusive, and an
  39824. ** exclusive lock on the database is not already held, obtain it now.
  39825. */
  39826. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  39827. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  39828. if( rc!=SQLITE_OK ){
  39829. return rc;
  39830. }
  39831. sqlite3WalExclusiveMode(pPager->pWal, 1);
  39832. }
  39833. /* Grab the write lock on the log file. If successful, upgrade to
  39834. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  39835. ** The busy-handler is not invoked if another connection already
  39836. ** holds the write-lock. If possible, the upper layer will call it.
  39837. */
  39838. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  39839. }else{
  39840. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  39841. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  39842. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  39843. ** lock, but not when obtaining the RESERVED lock.
  39844. */
  39845. rc = pagerLockDb(pPager, RESERVED_LOCK);
  39846. if( rc==SQLITE_OK && exFlag ){
  39847. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  39848. }
  39849. }
  39850. if( rc==SQLITE_OK ){
  39851. /* Change to WRITER_LOCKED state.
  39852. **
  39853. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  39854. ** when it has an open transaction, but never to DBMOD or FINISHED.
  39855. ** This is because in those states the code to roll back savepoint
  39856. ** transactions may copy data from the sub-journal into the database
  39857. ** file as well as into the page cache. Which would be incorrect in
  39858. ** WAL mode.
  39859. */
  39860. pPager->eState = PAGER_WRITER_LOCKED;
  39861. pPager->dbHintSize = pPager->dbSize;
  39862. pPager->dbFileSize = pPager->dbSize;
  39863. pPager->dbOrigSize = pPager->dbSize;
  39864. pPager->journalOff = 0;
  39865. }
  39866. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  39867. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  39868. assert( assert_pager_state(pPager) );
  39869. }
  39870. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  39871. return rc;
  39872. }
  39873. /*
  39874. ** Mark a single data page as writeable. The page is written into the
  39875. ** main journal or sub-journal as required. If the page is written into
  39876. ** one of the journals, the corresponding bit is set in the
  39877. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  39878. ** of any open savepoints as appropriate.
  39879. */
  39880. static int pager_write(PgHdr *pPg){
  39881. void *pData = pPg->pData;
  39882. Pager *pPager = pPg->pPager;
  39883. int rc = SQLITE_OK;
  39884. /* This routine is not called unless a write-transaction has already
  39885. ** been started. The journal file may or may not be open at this point.
  39886. ** It is never called in the ERROR state.
  39887. */
  39888. assert( pPager->eState==PAGER_WRITER_LOCKED
  39889. || pPager->eState==PAGER_WRITER_CACHEMOD
  39890. || pPager->eState==PAGER_WRITER_DBMOD
  39891. );
  39892. assert( assert_pager_state(pPager) );
  39893. /* If an error has been previously detected, report the same error
  39894. ** again. This should not happen, but the check provides robustness. */
  39895. if( NEVER(pPager->errCode) ) return pPager->errCode;
  39896. /* Higher-level routines never call this function if database is not
  39897. ** writable. But check anyway, just for robustness. */
  39898. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  39899. CHECK_PAGE(pPg);
  39900. /* The journal file needs to be opened. Higher level routines have already
  39901. ** obtained the necessary locks to begin the write-transaction, but the
  39902. ** rollback journal might not yet be open. Open it now if this is the case.
  39903. **
  39904. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  39905. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  39906. ** an error might occur and the pager would end up in WRITER_LOCKED state
  39907. ** with pages marked as dirty in the cache.
  39908. */
  39909. if( pPager->eState==PAGER_WRITER_LOCKED ){
  39910. rc = pager_open_journal(pPager);
  39911. if( rc!=SQLITE_OK ) return rc;
  39912. }
  39913. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  39914. assert( assert_pager_state(pPager) );
  39915. /* Mark the page as dirty. If the page has already been written
  39916. ** to the journal then we can return right away.
  39917. */
  39918. sqlite3PcacheMakeDirty(pPg);
  39919. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  39920. assert( !pagerUseWal(pPager) );
  39921. }else{
  39922. /* The transaction journal now exists and we have a RESERVED or an
  39923. ** EXCLUSIVE lock on the main database file. Write the current page to
  39924. ** the transaction journal if it is not there already.
  39925. */
  39926. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  39927. assert( pagerUseWal(pPager)==0 );
  39928. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  39929. u32 cksum;
  39930. char *pData2;
  39931. i64 iOff = pPager->journalOff;
  39932. /* We should never write to the journal file the page that
  39933. ** contains the database locks. The following assert verifies
  39934. ** that we do not. */
  39935. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  39936. assert( pPager->journalHdr<=pPager->journalOff );
  39937. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  39938. cksum = pager_cksum(pPager, (u8*)pData2);
  39939. /* Even if an IO or diskfull error occurs while journalling the
  39940. ** page in the block above, set the need-sync flag for the page.
  39941. ** Otherwise, when the transaction is rolled back, the logic in
  39942. ** playback_one_page() will think that the page needs to be restored
  39943. ** in the database file. And if an IO error occurs while doing so,
  39944. ** then corruption may follow.
  39945. */
  39946. pPg->flags |= PGHDR_NEED_SYNC;
  39947. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  39948. if( rc!=SQLITE_OK ) return rc;
  39949. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  39950. if( rc!=SQLITE_OK ) return rc;
  39951. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  39952. if( rc!=SQLITE_OK ) return rc;
  39953. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  39954. pPager->journalOff, pPager->pageSize));
  39955. PAGER_INCR(sqlite3_pager_writej_count);
  39956. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  39957. PAGERID(pPager), pPg->pgno,
  39958. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  39959. pPager->journalOff += 8 + pPager->pageSize;
  39960. pPager->nRec++;
  39961. assert( pPager->pInJournal!=0 );
  39962. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  39963. testcase( rc==SQLITE_NOMEM );
  39964. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  39965. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  39966. if( rc!=SQLITE_OK ){
  39967. assert( rc==SQLITE_NOMEM );
  39968. return rc;
  39969. }
  39970. }else{
  39971. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  39972. pPg->flags |= PGHDR_NEED_SYNC;
  39973. }
  39974. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  39975. PAGERID(pPager), pPg->pgno,
  39976. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  39977. }
  39978. }
  39979. /* If the statement journal is open and the page is not in it,
  39980. ** then write the current page to the statement journal. Note that
  39981. ** the statement journal format differs from the standard journal format
  39982. ** in that it omits the checksums and the header.
  39983. */
  39984. if( subjRequiresPage(pPg) ){
  39985. rc = subjournalPage(pPg);
  39986. }
  39987. }
  39988. /* Update the database size and return.
  39989. */
  39990. if( pPager->dbSize<pPg->pgno ){
  39991. pPager->dbSize = pPg->pgno;
  39992. }
  39993. return rc;
  39994. }
  39995. /*
  39996. ** Mark a data page as writeable. This routine must be called before
  39997. ** making changes to a page. The caller must check the return value
  39998. ** of this function and be careful not to change any page data unless
  39999. ** this routine returns SQLITE_OK.
  40000. **
  40001. ** The difference between this function and pager_write() is that this
  40002. ** function also deals with the special case where 2 or more pages
  40003. ** fit on a single disk sector. In this case all co-resident pages
  40004. ** must have been written to the journal file before returning.
  40005. **
  40006. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  40007. ** as appropriate. Otherwise, SQLITE_OK.
  40008. */
  40009. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  40010. int rc = SQLITE_OK;
  40011. PgHdr *pPg = pDbPage;
  40012. Pager *pPager = pPg->pPager;
  40013. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  40014. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  40015. assert( pPager->eState!=PAGER_ERROR );
  40016. assert( assert_pager_state(pPager) );
  40017. if( nPagePerSector>1 ){
  40018. Pgno nPageCount; /* Total number of pages in database file */
  40019. Pgno pg1; /* First page of the sector pPg is located on. */
  40020. int nPage = 0; /* Number of pages starting at pg1 to journal */
  40021. int ii; /* Loop counter */
  40022. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  40023. /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
  40024. ** a journal header to be written between the pages journaled by
  40025. ** this function.
  40026. */
  40027. assert( !MEMDB );
  40028. assert( pPager->doNotSyncSpill==0 );
  40029. pPager->doNotSyncSpill++;
  40030. /* This trick assumes that both the page-size and sector-size are
  40031. ** an integer power of 2. It sets variable pg1 to the identifier
  40032. ** of the first page of the sector pPg is located on.
  40033. */
  40034. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  40035. nPageCount = pPager->dbSize;
  40036. if( pPg->pgno>nPageCount ){
  40037. nPage = (pPg->pgno - pg1)+1;
  40038. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  40039. nPage = nPageCount+1-pg1;
  40040. }else{
  40041. nPage = nPagePerSector;
  40042. }
  40043. assert(nPage>0);
  40044. assert(pg1<=pPg->pgno);
  40045. assert((pg1+nPage)>pPg->pgno);
  40046. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  40047. Pgno pg = pg1+ii;
  40048. PgHdr *pPage;
  40049. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  40050. if( pg!=PAGER_MJ_PGNO(pPager) ){
  40051. rc = sqlite3PagerGet(pPager, pg, &pPage);
  40052. if( rc==SQLITE_OK ){
  40053. rc = pager_write(pPage);
  40054. if( pPage->flags&PGHDR_NEED_SYNC ){
  40055. needSync = 1;
  40056. }
  40057. sqlite3PagerUnref(pPage);
  40058. }
  40059. }
  40060. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  40061. if( pPage->flags&PGHDR_NEED_SYNC ){
  40062. needSync = 1;
  40063. }
  40064. sqlite3PagerUnref(pPage);
  40065. }
  40066. }
  40067. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  40068. ** starting at pg1, then it needs to be set for all of them. Because
  40069. ** writing to any of these nPage pages may damage the others, the
  40070. ** journal file must contain sync()ed copies of all of them
  40071. ** before any of them can be written out to the database file.
  40072. */
  40073. if( rc==SQLITE_OK && needSync ){
  40074. assert( !MEMDB );
  40075. for(ii=0; ii<nPage; ii++){
  40076. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  40077. if( pPage ){
  40078. pPage->flags |= PGHDR_NEED_SYNC;
  40079. sqlite3PagerUnref(pPage);
  40080. }
  40081. }
  40082. }
  40083. assert( pPager->doNotSyncSpill==1 );
  40084. pPager->doNotSyncSpill--;
  40085. }else{
  40086. rc = pager_write(pDbPage);
  40087. }
  40088. return rc;
  40089. }
  40090. /*
  40091. ** Return TRUE if the page given in the argument was previously passed
  40092. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  40093. ** to change the content of the page.
  40094. */
  40095. #ifndef NDEBUG
  40096. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  40097. return pPg->flags&PGHDR_DIRTY;
  40098. }
  40099. #endif
  40100. /*
  40101. ** A call to this routine tells the pager that it is not necessary to
  40102. ** write the information on page pPg back to the disk, even though
  40103. ** that page might be marked as dirty. This happens, for example, when
  40104. ** the page has been added as a leaf of the freelist and so its
  40105. ** content no longer matters.
  40106. **
  40107. ** The overlying software layer calls this routine when all of the data
  40108. ** on the given page is unused. The pager marks the page as clean so
  40109. ** that it does not get written to disk.
  40110. **
  40111. ** Tests show that this optimization can quadruple the speed of large
  40112. ** DELETE operations.
  40113. */
  40114. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  40115. Pager *pPager = pPg->pPager;
  40116. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  40117. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  40118. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  40119. pPg->flags |= PGHDR_DONT_WRITE;
  40120. pager_set_pagehash(pPg);
  40121. }
  40122. }
  40123. /*
  40124. ** This routine is called to increment the value of the database file
  40125. ** change-counter, stored as a 4-byte big-endian integer starting at
  40126. ** byte offset 24 of the pager file. The secondary change counter at
  40127. ** 92 is also updated, as is the SQLite version number at offset 96.
  40128. **
  40129. ** But this only happens if the pPager->changeCountDone flag is false.
  40130. ** To avoid excess churning of page 1, the update only happens once.
  40131. ** See also the pager_write_changecounter() routine that does an
  40132. ** unconditional update of the change counters.
  40133. **
  40134. ** If the isDirectMode flag is zero, then this is done by calling
  40135. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  40136. ** page data. In this case the file will be updated when the current
  40137. ** transaction is committed.
  40138. **
  40139. ** The isDirectMode flag may only be non-zero if the library was compiled
  40140. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  40141. ** if isDirect is non-zero, then the database file is updated directly
  40142. ** by writing an updated version of page 1 using a call to the
  40143. ** sqlite3OsWrite() function.
  40144. */
  40145. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  40146. int rc = SQLITE_OK;
  40147. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  40148. || pPager->eState==PAGER_WRITER_DBMOD
  40149. );
  40150. assert( assert_pager_state(pPager) );
  40151. /* Declare and initialize constant integer 'isDirect'. If the
  40152. ** atomic-write optimization is enabled in this build, then isDirect
  40153. ** is initialized to the value passed as the isDirectMode parameter
  40154. ** to this function. Otherwise, it is always set to zero.
  40155. **
  40156. ** The idea is that if the atomic-write optimization is not
  40157. ** enabled at compile time, the compiler can omit the tests of
  40158. ** 'isDirect' below, as well as the block enclosed in the
  40159. ** "if( isDirect )" condition.
  40160. */
  40161. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  40162. # define DIRECT_MODE 0
  40163. assert( isDirectMode==0 );
  40164. UNUSED_PARAMETER(isDirectMode);
  40165. #else
  40166. # define DIRECT_MODE isDirectMode
  40167. #endif
  40168. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  40169. PgHdr *pPgHdr; /* Reference to page 1 */
  40170. assert( !pPager->tempFile && isOpen(pPager->fd) );
  40171. /* Open page 1 of the file for writing. */
  40172. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  40173. assert( pPgHdr==0 || rc==SQLITE_OK );
  40174. /* If page one was fetched successfully, and this function is not
  40175. ** operating in direct-mode, make page 1 writable. When not in
  40176. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  40177. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  40178. */
  40179. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  40180. rc = sqlite3PagerWrite(pPgHdr);
  40181. }
  40182. if( rc==SQLITE_OK ){
  40183. /* Actually do the update of the change counter */
  40184. pager_write_changecounter(pPgHdr);
  40185. /* If running in direct mode, write the contents of page 1 to the file. */
  40186. if( DIRECT_MODE ){
  40187. const void *zBuf;
  40188. assert( pPager->dbFileSize>0 );
  40189. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  40190. if( rc==SQLITE_OK ){
  40191. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  40192. pPager->aStat[PAGER_STAT_WRITE]++;
  40193. }
  40194. if( rc==SQLITE_OK ){
  40195. pPager->changeCountDone = 1;
  40196. }
  40197. }else{
  40198. pPager->changeCountDone = 1;
  40199. }
  40200. }
  40201. /* Release the page reference. */
  40202. sqlite3PagerUnref(pPgHdr);
  40203. }
  40204. return rc;
  40205. }
  40206. /*
  40207. ** Sync the database file to disk. This is a no-op for in-memory databases
  40208. ** or pages with the Pager.noSync flag set.
  40209. **
  40210. ** If successful, or if called on a pager for which it is a no-op, this
  40211. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  40212. */
  40213. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  40214. int rc = SQLITE_OK;
  40215. if( !pPager->noSync ){
  40216. assert( !MEMDB );
  40217. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  40218. }else if( isOpen(pPager->fd) ){
  40219. assert( !MEMDB );
  40220. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  40221. if( rc==SQLITE_NOTFOUND ){
  40222. rc = SQLITE_OK;
  40223. }
  40224. }
  40225. return rc;
  40226. }
  40227. /*
  40228. ** This function may only be called while a write-transaction is active in
  40229. ** rollback. If the connection is in WAL mode, this call is a no-op.
  40230. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  40231. ** the database file, an attempt is made to obtain one.
  40232. **
  40233. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  40234. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  40235. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  40236. ** returned.
  40237. */
  40238. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  40239. int rc = SQLITE_OK;
  40240. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  40241. || pPager->eState==PAGER_WRITER_DBMOD
  40242. || pPager->eState==PAGER_WRITER_LOCKED
  40243. );
  40244. assert( assert_pager_state(pPager) );
  40245. if( 0==pagerUseWal(pPager) ){
  40246. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  40247. }
  40248. return rc;
  40249. }
  40250. /*
  40251. ** Sync the database file for the pager pPager. zMaster points to the name
  40252. ** of a master journal file that should be written into the individual
  40253. ** journal file. zMaster may be NULL, which is interpreted as no master
  40254. ** journal (a single database transaction).
  40255. **
  40256. ** This routine ensures that:
  40257. **
  40258. ** * The database file change-counter is updated,
  40259. ** * the journal is synced (unless the atomic-write optimization is used),
  40260. ** * all dirty pages are written to the database file,
  40261. ** * the database file is truncated (if required), and
  40262. ** * the database file synced.
  40263. **
  40264. ** The only thing that remains to commit the transaction is to finalize
  40265. ** (delete, truncate or zero the first part of) the journal file (or
  40266. ** delete the master journal file if specified).
  40267. **
  40268. ** Note that if zMaster==NULL, this does not overwrite a previous value
  40269. ** passed to an sqlite3PagerCommitPhaseOne() call.
  40270. **
  40271. ** If the final parameter - noSync - is true, then the database file itself
  40272. ** is not synced. The caller must call sqlite3PagerSync() directly to
  40273. ** sync the database file before calling CommitPhaseTwo() to delete the
  40274. ** journal file in this case.
  40275. */
  40276. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  40277. Pager *pPager, /* Pager object */
  40278. const char *zMaster, /* If not NULL, the master journal name */
  40279. int noSync /* True to omit the xSync on the db file */
  40280. ){
  40281. int rc = SQLITE_OK; /* Return code */
  40282. assert( pPager->eState==PAGER_WRITER_LOCKED
  40283. || pPager->eState==PAGER_WRITER_CACHEMOD
  40284. || pPager->eState==PAGER_WRITER_DBMOD
  40285. || pPager->eState==PAGER_ERROR
  40286. );
  40287. assert( assert_pager_state(pPager) );
  40288. /* If a prior error occurred, report that error again. */
  40289. if( NEVER(pPager->errCode) ) return pPager->errCode;
  40290. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  40291. pPager->zFilename, zMaster, pPager->dbSize));
  40292. /* If no database changes have been made, return early. */
  40293. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  40294. if( MEMDB ){
  40295. /* If this is an in-memory db, or no pages have been written to, or this
  40296. ** function has already been called, it is mostly a no-op. However, any
  40297. ** backup in progress needs to be restarted.
  40298. */
  40299. sqlite3BackupRestart(pPager->pBackup);
  40300. }else{
  40301. if( pagerUseWal(pPager) ){
  40302. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  40303. PgHdr *pPageOne = 0;
  40304. if( pList==0 ){
  40305. /* Must have at least one page for the WAL commit flag.
  40306. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  40307. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  40308. pList = pPageOne;
  40309. pList->pDirty = 0;
  40310. }
  40311. assert( rc==SQLITE_OK );
  40312. if( ALWAYS(pList) ){
  40313. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  40314. }
  40315. sqlite3PagerUnref(pPageOne);
  40316. if( rc==SQLITE_OK ){
  40317. sqlite3PcacheCleanAll(pPager->pPCache);
  40318. }
  40319. }else{
  40320. /* The following block updates the change-counter. Exactly how it
  40321. ** does this depends on whether or not the atomic-update optimization
  40322. ** was enabled at compile time, and if this transaction meets the
  40323. ** runtime criteria to use the operation:
  40324. **
  40325. ** * The file-system supports the atomic-write property for
  40326. ** blocks of size page-size, and
  40327. ** * This commit is not part of a multi-file transaction, and
  40328. ** * Exactly one page has been modified and store in the journal file.
  40329. **
  40330. ** If the optimization was not enabled at compile time, then the
  40331. ** pager_incr_changecounter() function is called to update the change
  40332. ** counter in 'indirect-mode'. If the optimization is compiled in but
  40333. ** is not applicable to this transaction, call sqlite3JournalCreate()
  40334. ** to make sure the journal file has actually been created, then call
  40335. ** pager_incr_changecounter() to update the change-counter in indirect
  40336. ** mode.
  40337. **
  40338. ** Otherwise, if the optimization is both enabled and applicable,
  40339. ** then call pager_incr_changecounter() to update the change-counter
  40340. ** in 'direct' mode. In this case the journal file will never be
  40341. ** created for this transaction.
  40342. */
  40343. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40344. PgHdr *pPg;
  40345. assert( isOpen(pPager->jfd)
  40346. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  40347. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  40348. );
  40349. if( !zMaster && isOpen(pPager->jfd)
  40350. && pPager->journalOff==jrnlBufferSize(pPager)
  40351. && pPager->dbSize>=pPager->dbOrigSize
  40352. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  40353. ){
  40354. /* Update the db file change counter via the direct-write method. The
  40355. ** following call will modify the in-memory representation of page 1
  40356. ** to include the updated change counter and then write page 1
  40357. ** directly to the database file. Because of the atomic-write
  40358. ** property of the host file-system, this is safe.
  40359. */
  40360. rc = pager_incr_changecounter(pPager, 1);
  40361. }else{
  40362. rc = sqlite3JournalCreate(pPager->jfd);
  40363. if( rc==SQLITE_OK ){
  40364. rc = pager_incr_changecounter(pPager, 0);
  40365. }
  40366. }
  40367. #else
  40368. rc = pager_incr_changecounter(pPager, 0);
  40369. #endif
  40370. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40371. /* If this transaction has made the database smaller, then all pages
  40372. ** being discarded by the truncation must be written to the journal
  40373. ** file.
  40374. **
  40375. ** Before reading the pages with page numbers larger than the
  40376. ** current value of Pager.dbSize, set dbSize back to the value
  40377. ** that it took at the start of the transaction. Otherwise, the
  40378. ** calls to sqlite3PagerGet() return zeroed pages instead of
  40379. ** reading data from the database file.
  40380. */
  40381. if( pPager->dbSize<pPager->dbOrigSize
  40382. && pPager->journalMode!=PAGER_JOURNALMODE_OFF
  40383. ){
  40384. Pgno i; /* Iterator variable */
  40385. const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
  40386. const Pgno dbSize = pPager->dbSize; /* Database image size */
  40387. pPager->dbSize = pPager->dbOrigSize;
  40388. for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
  40389. if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
  40390. PgHdr *pPage; /* Page to journal */
  40391. rc = sqlite3PagerGet(pPager, i, &pPage);
  40392. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40393. rc = sqlite3PagerWrite(pPage);
  40394. sqlite3PagerUnref(pPage);
  40395. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40396. }
  40397. }
  40398. pPager->dbSize = dbSize;
  40399. }
  40400. /* Write the master journal name into the journal file. If a master
  40401. ** journal file name has already been written to the journal file,
  40402. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  40403. */
  40404. rc = writeMasterJournal(pPager, zMaster);
  40405. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40406. /* Sync the journal file and write all dirty pages to the database.
  40407. ** If the atomic-update optimization is being used, this sync will not
  40408. ** create the journal file or perform any real IO.
  40409. **
  40410. ** Because the change-counter page was just modified, unless the
  40411. ** atomic-update optimization is used it is almost certain that the
  40412. ** journal requires a sync here. However, in locking_mode=exclusive
  40413. ** on a system under memory pressure it is just possible that this is
  40414. ** not the case. In this case it is likely enough that the redundant
  40415. ** xSync() call will be changed to a no-op by the OS anyhow.
  40416. */
  40417. rc = syncJournal(pPager, 0);
  40418. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40419. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  40420. if( rc!=SQLITE_OK ){
  40421. assert( rc!=SQLITE_IOERR_BLOCKED );
  40422. goto commit_phase_one_exit;
  40423. }
  40424. sqlite3PcacheCleanAll(pPager->pPCache);
  40425. /* If the file on disk is not the same size as the database image,
  40426. ** then use pager_truncate to grow or shrink the file here.
  40427. */
  40428. if( pPager->dbSize!=pPager->dbFileSize ){
  40429. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  40430. assert( pPager->eState==PAGER_WRITER_DBMOD );
  40431. rc = pager_truncate(pPager, nNew);
  40432. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  40433. }
  40434. /* Finally, sync the database file. */
  40435. if( !noSync ){
  40436. rc = sqlite3PagerSync(pPager);
  40437. }
  40438. IOTRACE(("DBSYNC %p\n", pPager))
  40439. }
  40440. }
  40441. commit_phase_one_exit:
  40442. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  40443. pPager->eState = PAGER_WRITER_FINISHED;
  40444. }
  40445. return rc;
  40446. }
  40447. /*
  40448. ** When this function is called, the database file has been completely
  40449. ** updated to reflect the changes made by the current transaction and
  40450. ** synced to disk. The journal file still exists in the file-system
  40451. ** though, and if a failure occurs at this point it will eventually
  40452. ** be used as a hot-journal and the current transaction rolled back.
  40453. **
  40454. ** This function finalizes the journal file, either by deleting,
  40455. ** truncating or partially zeroing it, so that it cannot be used
  40456. ** for hot-journal rollback. Once this is done the transaction is
  40457. ** irrevocably committed.
  40458. **
  40459. ** If an error occurs, an IO error code is returned and the pager
  40460. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  40461. */
  40462. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  40463. int rc = SQLITE_OK; /* Return code */
  40464. /* This routine should not be called if a prior error has occurred.
  40465. ** But if (due to a coding error elsewhere in the system) it does get
  40466. ** called, just return the same error code without doing anything. */
  40467. if( NEVER(pPager->errCode) ) return pPager->errCode;
  40468. assert( pPager->eState==PAGER_WRITER_LOCKED
  40469. || pPager->eState==PAGER_WRITER_FINISHED
  40470. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  40471. );
  40472. assert( assert_pager_state(pPager) );
  40473. /* An optimization. If the database was not actually modified during
  40474. ** this transaction, the pager is running in exclusive-mode and is
  40475. ** using persistent journals, then this function is a no-op.
  40476. **
  40477. ** The start of the journal file currently contains a single journal
  40478. ** header with the nRec field set to 0. If such a journal is used as
  40479. ** a hot-journal during hot-journal rollback, 0 changes will be made
  40480. ** to the database file. So there is no need to zero the journal
  40481. ** header. Since the pager is in exclusive mode, there is no need
  40482. ** to drop any locks either.
  40483. */
  40484. if( pPager->eState==PAGER_WRITER_LOCKED
  40485. && pPager->exclusiveMode
  40486. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40487. ){
  40488. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  40489. pPager->eState = PAGER_READER;
  40490. return SQLITE_OK;
  40491. }
  40492. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  40493. rc = pager_end_transaction(pPager, pPager->setMaster);
  40494. return pager_error(pPager, rc);
  40495. }
  40496. /*
  40497. ** If a write transaction is open, then all changes made within the
  40498. ** transaction are reverted and the current write-transaction is closed.
  40499. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  40500. ** state if an error occurs.
  40501. **
  40502. ** If the pager is already in PAGER_ERROR state when this function is called,
  40503. ** it returns Pager.errCode immediately. No work is performed in this case.
  40504. **
  40505. ** Otherwise, in rollback mode, this function performs two functions:
  40506. **
  40507. ** 1) It rolls back the journal file, restoring all database file and
  40508. ** in-memory cache pages to the state they were in when the transaction
  40509. ** was opened, and
  40510. **
  40511. ** 2) It finalizes the journal file, so that it is not used for hot
  40512. ** rollback at any point in the future.
  40513. **
  40514. ** Finalization of the journal file (task 2) is only performed if the
  40515. ** rollback is successful.
  40516. **
  40517. ** In WAL mode, all cache-entries containing data modified within the
  40518. ** current transaction are either expelled from the cache or reverted to
  40519. ** their pre-transaction state by re-reading data from the database or
  40520. ** WAL files. The WAL transaction is then closed.
  40521. */
  40522. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  40523. int rc = SQLITE_OK; /* Return code */
  40524. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  40525. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  40526. ** the pager is already in the ERROR state, the rollback is not
  40527. ** attempted here. Instead, the error code is returned to the caller.
  40528. */
  40529. assert( assert_pager_state(pPager) );
  40530. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  40531. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  40532. if( pagerUseWal(pPager) ){
  40533. int rc2;
  40534. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  40535. rc2 = pager_end_transaction(pPager, pPager->setMaster);
  40536. if( rc==SQLITE_OK ) rc = rc2;
  40537. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  40538. int eState = pPager->eState;
  40539. rc = pager_end_transaction(pPager, 0);
  40540. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  40541. /* This can happen using journal_mode=off. Move the pager to the error
  40542. ** state to indicate that the contents of the cache may not be trusted.
  40543. ** Any active readers will get SQLITE_ABORT.
  40544. */
  40545. pPager->errCode = SQLITE_ABORT;
  40546. pPager->eState = PAGER_ERROR;
  40547. return rc;
  40548. }
  40549. }else{
  40550. rc = pager_playback(pPager, 0);
  40551. }
  40552. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  40553. assert( rc==SQLITE_OK || rc==SQLITE_FULL
  40554. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  40555. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  40556. ** cache. So call pager_error() on the way out to make any error persistent.
  40557. */
  40558. return pager_error(pPager, rc);
  40559. }
  40560. /*
  40561. ** Return TRUE if the database file is opened read-only. Return FALSE
  40562. ** if the database is (in theory) writable.
  40563. */
  40564. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  40565. return pPager->readOnly;
  40566. }
  40567. /*
  40568. ** Return the number of references to the pager.
  40569. */
  40570. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  40571. return sqlite3PcacheRefCount(pPager->pPCache);
  40572. }
  40573. /*
  40574. ** Return the approximate number of bytes of memory currently
  40575. ** used by the pager and its associated cache.
  40576. */
  40577. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  40578. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  40579. + 5*sizeof(void*);
  40580. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  40581. + sqlite3MallocSize(pPager)
  40582. + pPager->pageSize;
  40583. }
  40584. /*
  40585. ** Return the number of references to the specified page.
  40586. */
  40587. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  40588. return sqlite3PcachePageRefcount(pPage);
  40589. }
  40590. #ifdef SQLITE_TEST
  40591. /*
  40592. ** This routine is used for testing and analysis only.
  40593. */
  40594. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  40595. static int a[11];
  40596. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  40597. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  40598. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  40599. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  40600. a[4] = pPager->eState;
  40601. a[5] = pPager->errCode;
  40602. a[6] = pPager->aStat[PAGER_STAT_HIT];
  40603. a[7] = pPager->aStat[PAGER_STAT_MISS];
  40604. a[8] = 0; /* Used to be pPager->nOvfl */
  40605. a[9] = pPager->nRead;
  40606. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  40607. return a;
  40608. }
  40609. #endif
  40610. /*
  40611. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  40612. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  40613. ** current cache hit or miss count, according to the value of eStat. If the
  40614. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  40615. ** returning.
  40616. */
  40617. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  40618. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  40619. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  40620. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  40621. );
  40622. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  40623. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  40624. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  40625. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  40626. if( reset ){
  40627. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  40628. }
  40629. }
  40630. /*
  40631. ** Return true if this is an in-memory pager.
  40632. */
  40633. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  40634. return MEMDB;
  40635. }
  40636. /*
  40637. ** Check that there are at least nSavepoint savepoints open. If there are
  40638. ** currently less than nSavepoints open, then open one or more savepoints
  40639. ** to make up the difference. If the number of savepoints is already
  40640. ** equal to nSavepoint, then this function is a no-op.
  40641. **
  40642. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  40643. ** occurs while opening the sub-journal file, then an IO error code is
  40644. ** returned. Otherwise, SQLITE_OK.
  40645. */
  40646. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  40647. int rc = SQLITE_OK; /* Return code */
  40648. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  40649. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  40650. assert( assert_pager_state(pPager) );
  40651. if( nSavepoint>nCurrent && pPager->useJournal ){
  40652. int ii; /* Iterator variable */
  40653. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  40654. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  40655. ** if the allocation fails. Otherwise, zero the new portion in case a
  40656. ** malloc failure occurs while populating it in the for(...) loop below.
  40657. */
  40658. aNew = (PagerSavepoint *)sqlite3Realloc(
  40659. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  40660. );
  40661. if( !aNew ){
  40662. return SQLITE_NOMEM;
  40663. }
  40664. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  40665. pPager->aSavepoint = aNew;
  40666. /* Populate the PagerSavepoint structures just allocated. */
  40667. for(ii=nCurrent; ii<nSavepoint; ii++){
  40668. aNew[ii].nOrig = pPager->dbSize;
  40669. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  40670. aNew[ii].iOffset = pPager->journalOff;
  40671. }else{
  40672. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  40673. }
  40674. aNew[ii].iSubRec = pPager->nSubRec;
  40675. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  40676. if( !aNew[ii].pInSavepoint ){
  40677. return SQLITE_NOMEM;
  40678. }
  40679. if( pagerUseWal(pPager) ){
  40680. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  40681. }
  40682. pPager->nSavepoint = ii+1;
  40683. }
  40684. assert( pPager->nSavepoint==nSavepoint );
  40685. assertTruncateConstraint(pPager);
  40686. }
  40687. return rc;
  40688. }
  40689. /*
  40690. ** This function is called to rollback or release (commit) a savepoint.
  40691. ** The savepoint to release or rollback need not be the most recently
  40692. ** created savepoint.
  40693. **
  40694. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  40695. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  40696. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  40697. ** that have occurred since the specified savepoint was created.
  40698. **
  40699. ** The savepoint to rollback or release is identified by parameter
  40700. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  40701. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  40702. ** on the most recently created savepoint. If iSavepoint is greater than
  40703. ** (Pager.nSavepoint-1), then this function is a no-op.
  40704. **
  40705. ** If a negative value is passed to this function, then the current
  40706. ** transaction is rolled back. This is different to calling
  40707. ** sqlite3PagerRollback() because this function does not terminate
  40708. ** the transaction or unlock the database, it just restores the
  40709. ** contents of the database to its original state.
  40710. **
  40711. ** In any case, all savepoints with an index greater than iSavepoint
  40712. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  40713. ** then savepoint iSavepoint is also destroyed.
  40714. **
  40715. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  40716. ** or an IO error code if an IO error occurs while rolling back a
  40717. ** savepoint. If no errors occur, SQLITE_OK is returned.
  40718. */
  40719. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  40720. int rc = pPager->errCode; /* Return code */
  40721. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  40722. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  40723. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  40724. int ii; /* Iterator variable */
  40725. int nNew; /* Number of remaining savepoints after this op. */
  40726. /* Figure out how many savepoints will still be active after this
  40727. ** operation. Store this value in nNew. Then free resources associated
  40728. ** with any savepoints that are destroyed by this operation.
  40729. */
  40730. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  40731. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  40732. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  40733. }
  40734. pPager->nSavepoint = nNew;
  40735. /* If this is a release of the outermost savepoint, truncate
  40736. ** the sub-journal to zero bytes in size. */
  40737. if( op==SAVEPOINT_RELEASE ){
  40738. if( nNew==0 && isOpen(pPager->sjfd) ){
  40739. /* Only truncate if it is an in-memory sub-journal. */
  40740. if( sqlite3IsMemJournal(pPager->sjfd) ){
  40741. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  40742. assert( rc==SQLITE_OK );
  40743. }
  40744. pPager->nSubRec = 0;
  40745. }
  40746. }
  40747. /* Else this is a rollback operation, playback the specified savepoint.
  40748. ** If this is a temp-file, it is possible that the journal file has
  40749. ** not yet been opened. In this case there have been no changes to
  40750. ** the database file, so the playback operation can be skipped.
  40751. */
  40752. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  40753. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  40754. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  40755. assert(rc!=SQLITE_DONE);
  40756. }
  40757. }
  40758. return rc;
  40759. }
  40760. /*
  40761. ** Return the full pathname of the database file.
  40762. **
  40763. ** Except, if the pager is in-memory only, then return an empty string if
  40764. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  40765. ** used to report the filename to the user, for compatibility with legacy
  40766. ** behavior. But when the Btree needs to know the filename for matching to
  40767. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  40768. ** participate in shared-cache.
  40769. */
  40770. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  40771. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  40772. }
  40773. /*
  40774. ** Return the VFS structure for the pager.
  40775. */
  40776. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  40777. return pPager->pVfs;
  40778. }
  40779. /*
  40780. ** Return the file handle for the database file associated
  40781. ** with the pager. This might return NULL if the file has
  40782. ** not yet been opened.
  40783. */
  40784. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  40785. return pPager->fd;
  40786. }
  40787. /*
  40788. ** Return the full pathname of the journal file.
  40789. */
  40790. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  40791. return pPager->zJournal;
  40792. }
  40793. /*
  40794. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  40795. ** if fsync()s are executed normally.
  40796. */
  40797. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  40798. return pPager->noSync;
  40799. }
  40800. #ifdef SQLITE_HAS_CODEC
  40801. /*
  40802. ** Set or retrieve the codec for this pager
  40803. */
  40804. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  40805. Pager *pPager,
  40806. void *(*xCodec)(void*,void*,Pgno,int),
  40807. void (*xCodecSizeChng)(void*,int,int),
  40808. void (*xCodecFree)(void*),
  40809. void *pCodec
  40810. ){
  40811. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  40812. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  40813. pPager->xCodecSizeChng = xCodecSizeChng;
  40814. pPager->xCodecFree = xCodecFree;
  40815. pPager->pCodec = pCodec;
  40816. pagerReportSize(pPager);
  40817. }
  40818. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  40819. return pPager->pCodec;
  40820. }
  40821. #endif
  40822. #ifndef SQLITE_OMIT_AUTOVACUUM
  40823. /*
  40824. ** Move the page pPg to location pgno in the file.
  40825. **
  40826. ** There must be no references to the page previously located at
  40827. ** pgno (which we call pPgOld) though that page is allowed to be
  40828. ** in cache. If the page previously located at pgno is not already
  40829. ** in the rollback journal, it is not put there by by this routine.
  40830. **
  40831. ** References to the page pPg remain valid. Updating any
  40832. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  40833. ** allocated along with the page) is the responsibility of the caller.
  40834. **
  40835. ** A transaction must be active when this routine is called. It used to be
  40836. ** required that a statement transaction was not active, but this restriction
  40837. ** has been removed (CREATE INDEX needs to move a page when a statement
  40838. ** transaction is active).
  40839. **
  40840. ** If the fourth argument, isCommit, is non-zero, then this page is being
  40841. ** moved as part of a database reorganization just before the transaction
  40842. ** is being committed. In this case, it is guaranteed that the database page
  40843. ** pPg refers to will not be written to again within this transaction.
  40844. **
  40845. ** This function may return SQLITE_NOMEM or an IO error code if an error
  40846. ** occurs. Otherwise, it returns SQLITE_OK.
  40847. */
  40848. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  40849. PgHdr *pPgOld; /* The page being overwritten. */
  40850. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  40851. int rc; /* Return code */
  40852. Pgno origPgno; /* The original page number */
  40853. assert( pPg->nRef>0 );
  40854. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  40855. || pPager->eState==PAGER_WRITER_DBMOD
  40856. );
  40857. assert( assert_pager_state(pPager) );
  40858. /* In order to be able to rollback, an in-memory database must journal
  40859. ** the page we are moving from.
  40860. */
  40861. if( MEMDB ){
  40862. rc = sqlite3PagerWrite(pPg);
  40863. if( rc ) return rc;
  40864. }
  40865. /* If the page being moved is dirty and has not been saved by the latest
  40866. ** savepoint, then save the current contents of the page into the
  40867. ** sub-journal now. This is required to handle the following scenario:
  40868. **
  40869. ** BEGIN;
  40870. ** <journal page X, then modify it in memory>
  40871. ** SAVEPOINT one;
  40872. ** <Move page X to location Y>
  40873. ** ROLLBACK TO one;
  40874. **
  40875. ** If page X were not written to the sub-journal here, it would not
  40876. ** be possible to restore its contents when the "ROLLBACK TO one"
  40877. ** statement were is processed.
  40878. **
  40879. ** subjournalPage() may need to allocate space to store pPg->pgno into
  40880. ** one or more savepoint bitvecs. This is the reason this function
  40881. ** may return SQLITE_NOMEM.
  40882. */
  40883. if( pPg->flags&PGHDR_DIRTY
  40884. && subjRequiresPage(pPg)
  40885. && SQLITE_OK!=(rc = subjournalPage(pPg))
  40886. ){
  40887. return rc;
  40888. }
  40889. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  40890. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  40891. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  40892. /* If the journal needs to be sync()ed before page pPg->pgno can
  40893. ** be written to, store pPg->pgno in local variable needSyncPgno.
  40894. **
  40895. ** If the isCommit flag is set, there is no need to remember that
  40896. ** the journal needs to be sync()ed before database page pPg->pgno
  40897. ** can be written to. The caller has already promised not to write to it.
  40898. */
  40899. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  40900. needSyncPgno = pPg->pgno;
  40901. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  40902. assert( pPg->flags&PGHDR_DIRTY );
  40903. }
  40904. /* If the cache contains a page with page-number pgno, remove it
  40905. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  40906. ** page pgno before the 'move' operation, it needs to be retained
  40907. ** for the page moved there.
  40908. */
  40909. pPg->flags &= ~PGHDR_NEED_SYNC;
  40910. pPgOld = pager_lookup(pPager, pgno);
  40911. assert( !pPgOld || pPgOld->nRef==1 );
  40912. if( pPgOld ){
  40913. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  40914. if( MEMDB ){
  40915. /* Do not discard pages from an in-memory database since we might
  40916. ** need to rollback later. Just move the page out of the way. */
  40917. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  40918. }else{
  40919. sqlite3PcacheDrop(pPgOld);
  40920. }
  40921. }
  40922. origPgno = pPg->pgno;
  40923. sqlite3PcacheMove(pPg, pgno);
  40924. sqlite3PcacheMakeDirty(pPg);
  40925. /* For an in-memory database, make sure the original page continues
  40926. ** to exist, in case the transaction needs to roll back. Use pPgOld
  40927. ** as the original page since it has already been allocated.
  40928. */
  40929. if( MEMDB ){
  40930. assert( pPgOld );
  40931. sqlite3PcacheMove(pPgOld, origPgno);
  40932. sqlite3PagerUnref(pPgOld);
  40933. }
  40934. if( needSyncPgno ){
  40935. /* If needSyncPgno is non-zero, then the journal file needs to be
  40936. ** sync()ed before any data is written to database file page needSyncPgno.
  40937. ** Currently, no such page exists in the page-cache and the
  40938. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  40939. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  40940. ** flag.
  40941. **
  40942. ** If the attempt to load the page into the page-cache fails, (due
  40943. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  40944. ** array. Otherwise, if the page is loaded and written again in
  40945. ** this transaction, it may be written to the database file before
  40946. ** it is synced into the journal file. This way, it may end up in
  40947. ** the journal file twice, but that is not a problem.
  40948. */
  40949. PgHdr *pPgHdr;
  40950. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  40951. if( rc!=SQLITE_OK ){
  40952. if( needSyncPgno<=pPager->dbOrigSize ){
  40953. assert( pPager->pTmpSpace!=0 );
  40954. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  40955. }
  40956. return rc;
  40957. }
  40958. pPgHdr->flags |= PGHDR_NEED_SYNC;
  40959. sqlite3PcacheMakeDirty(pPgHdr);
  40960. sqlite3PagerUnref(pPgHdr);
  40961. }
  40962. return SQLITE_OK;
  40963. }
  40964. #endif
  40965. /*
  40966. ** Return a pointer to the data for the specified page.
  40967. */
  40968. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  40969. assert( pPg->nRef>0 || pPg->pPager->memDb );
  40970. return pPg->pData;
  40971. }
  40972. /*
  40973. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  40974. ** allocated along with the specified page.
  40975. */
  40976. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  40977. return pPg->pExtra;
  40978. }
  40979. /*
  40980. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  40981. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  40982. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  40983. ** the locking-mode is set to the value specified.
  40984. **
  40985. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  40986. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  40987. ** locking-mode.
  40988. */
  40989. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  40990. assert( eMode==PAGER_LOCKINGMODE_QUERY
  40991. || eMode==PAGER_LOCKINGMODE_NORMAL
  40992. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  40993. assert( PAGER_LOCKINGMODE_QUERY<0 );
  40994. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  40995. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  40996. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  40997. pPager->exclusiveMode = (u8)eMode;
  40998. }
  40999. return (int)pPager->exclusiveMode;
  41000. }
  41001. /*
  41002. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  41003. **
  41004. ** PAGER_JOURNALMODE_DELETE
  41005. ** PAGER_JOURNALMODE_TRUNCATE
  41006. ** PAGER_JOURNALMODE_PERSIST
  41007. ** PAGER_JOURNALMODE_OFF
  41008. ** PAGER_JOURNALMODE_MEMORY
  41009. ** PAGER_JOURNALMODE_WAL
  41010. **
  41011. ** The journalmode is set to the value specified if the change is allowed.
  41012. ** The change may be disallowed for the following reasons:
  41013. **
  41014. ** * An in-memory database can only have its journal_mode set to _OFF
  41015. ** or _MEMORY.
  41016. **
  41017. ** * Temporary databases cannot have _WAL journalmode.
  41018. **
  41019. ** The returned indicate the current (possibly updated) journal-mode.
  41020. */
  41021. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  41022. u8 eOld = pPager->journalMode; /* Prior journalmode */
  41023. #ifdef SQLITE_DEBUG
  41024. /* The print_pager_state() routine is intended to be used by the debugger
  41025. ** only. We invoke it once here to suppress a compiler warning. */
  41026. print_pager_state(pPager);
  41027. #endif
  41028. /* The eMode parameter is always valid */
  41029. assert( eMode==PAGER_JOURNALMODE_DELETE
  41030. || eMode==PAGER_JOURNALMODE_TRUNCATE
  41031. || eMode==PAGER_JOURNALMODE_PERSIST
  41032. || eMode==PAGER_JOURNALMODE_OFF
  41033. || eMode==PAGER_JOURNALMODE_WAL
  41034. || eMode==PAGER_JOURNALMODE_MEMORY );
  41035. /* This routine is only called from the OP_JournalMode opcode, and
  41036. ** the logic there will never allow a temporary file to be changed
  41037. ** to WAL mode.
  41038. */
  41039. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  41040. /* Do allow the journalmode of an in-memory database to be set to
  41041. ** anything other than MEMORY or OFF
  41042. */
  41043. if( MEMDB ){
  41044. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  41045. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  41046. eMode = eOld;
  41047. }
  41048. }
  41049. if( eMode!=eOld ){
  41050. /* Change the journal mode. */
  41051. assert( pPager->eState!=PAGER_ERROR );
  41052. pPager->journalMode = (u8)eMode;
  41053. /* When transistioning from TRUNCATE or PERSIST to any other journal
  41054. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  41055. ** delete the journal file.
  41056. */
  41057. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  41058. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  41059. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  41060. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  41061. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  41062. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  41063. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  41064. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  41065. /* In this case we would like to delete the journal file. If it is
  41066. ** not possible, then that is not a problem. Deleting the journal file
  41067. ** here is an optimization only.
  41068. **
  41069. ** Before deleting the journal file, obtain a RESERVED lock on the
  41070. ** database file. This ensures that the journal file is not deleted
  41071. ** while it is in use by some other client.
  41072. */
  41073. sqlite3OsClose(pPager->jfd);
  41074. if( pPager->eLock>=RESERVED_LOCK ){
  41075. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  41076. }else{
  41077. int rc = SQLITE_OK;
  41078. int state = pPager->eState;
  41079. assert( state==PAGER_OPEN || state==PAGER_READER );
  41080. if( state==PAGER_OPEN ){
  41081. rc = sqlite3PagerSharedLock(pPager);
  41082. }
  41083. if( pPager->eState==PAGER_READER ){
  41084. assert( rc==SQLITE_OK );
  41085. rc = pagerLockDb(pPager, RESERVED_LOCK);
  41086. }
  41087. if( rc==SQLITE_OK ){
  41088. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  41089. }
  41090. if( rc==SQLITE_OK && state==PAGER_READER ){
  41091. pagerUnlockDb(pPager, SHARED_LOCK);
  41092. }else if( state==PAGER_OPEN ){
  41093. pager_unlock(pPager);
  41094. }
  41095. assert( state==pPager->eState );
  41096. }
  41097. }
  41098. }
  41099. /* Return the new journal mode */
  41100. return (int)pPager->journalMode;
  41101. }
  41102. /*
  41103. ** Return the current journal mode.
  41104. */
  41105. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  41106. return (int)pPager->journalMode;
  41107. }
  41108. /*
  41109. ** Return TRUE if the pager is in a state where it is OK to change the
  41110. ** journalmode. Journalmode changes can only happen when the database
  41111. ** is unmodified.
  41112. */
  41113. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  41114. assert( assert_pager_state(pPager) );
  41115. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  41116. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  41117. return 1;
  41118. }
  41119. /*
  41120. ** Get/set the size-limit used for persistent journal files.
  41121. **
  41122. ** Setting the size limit to -1 means no limit is enforced.
  41123. ** An attempt to set a limit smaller than -1 is a no-op.
  41124. */
  41125. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  41126. if( iLimit>=-1 ){
  41127. pPager->journalSizeLimit = iLimit;
  41128. sqlite3WalLimit(pPager->pWal, iLimit);
  41129. }
  41130. return pPager->journalSizeLimit;
  41131. }
  41132. /*
  41133. ** Return a pointer to the pPager->pBackup variable. The backup module
  41134. ** in backup.c maintains the content of this variable. This module
  41135. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  41136. ** sqlite3BackupUpdate() only.
  41137. */
  41138. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  41139. return &pPager->pBackup;
  41140. }
  41141. #ifndef SQLITE_OMIT_VACUUM
  41142. /*
  41143. ** Unless this is an in-memory or temporary database, clear the pager cache.
  41144. */
  41145. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  41146. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  41147. }
  41148. #endif
  41149. #ifndef SQLITE_OMIT_WAL
  41150. /*
  41151. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  41152. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  41153. ** or wal_blocking_checkpoint() API functions.
  41154. **
  41155. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  41156. */
  41157. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  41158. int rc = SQLITE_OK;
  41159. if( pPager->pWal ){
  41160. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  41161. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  41162. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  41163. pnLog, pnCkpt
  41164. );
  41165. }
  41166. return rc;
  41167. }
  41168. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  41169. return sqlite3WalCallback(pPager->pWal);
  41170. }
  41171. /*
  41172. ** Return true if the underlying VFS for the given pager supports the
  41173. ** primitives necessary for write-ahead logging.
  41174. */
  41175. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  41176. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  41177. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  41178. }
  41179. /*
  41180. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  41181. ** is obtained instead, immediately release it.
  41182. */
  41183. static int pagerExclusiveLock(Pager *pPager){
  41184. int rc; /* Return code */
  41185. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  41186. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  41187. if( rc!=SQLITE_OK ){
  41188. /* If the attempt to grab the exclusive lock failed, release the
  41189. ** pending lock that may have been obtained instead. */
  41190. pagerUnlockDb(pPager, SHARED_LOCK);
  41191. }
  41192. return rc;
  41193. }
  41194. /*
  41195. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  41196. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  41197. ** lock on the database file and use heap-memory to store the wal-index
  41198. ** in. Otherwise, use the normal shared-memory.
  41199. */
  41200. static int pagerOpenWal(Pager *pPager){
  41201. int rc = SQLITE_OK;
  41202. assert( pPager->pWal==0 && pPager->tempFile==0 );
  41203. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  41204. /* If the pager is already in exclusive-mode, the WAL module will use
  41205. ** heap-memory for the wal-index instead of the VFS shared-memory
  41206. ** implementation. Take the exclusive lock now, before opening the WAL
  41207. ** file, to make sure this is safe.
  41208. */
  41209. if( pPager->exclusiveMode ){
  41210. rc = pagerExclusiveLock(pPager);
  41211. }
  41212. /* Open the connection to the log file. If this operation fails,
  41213. ** (e.g. due to malloc() failure), return an error code.
  41214. */
  41215. if( rc==SQLITE_OK ){
  41216. rc = sqlite3WalOpen(pPager->pVfs,
  41217. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  41218. pPager->journalSizeLimit, &pPager->pWal
  41219. );
  41220. }
  41221. return rc;
  41222. }
  41223. /*
  41224. ** The caller must be holding a SHARED lock on the database file to call
  41225. ** this function.
  41226. **
  41227. ** If the pager passed as the first argument is open on a real database
  41228. ** file (not a temp file or an in-memory database), and the WAL file
  41229. ** is not already open, make an attempt to open it now. If successful,
  41230. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  41231. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  41232. ** not modified in either case.
  41233. **
  41234. ** If the pager is open on a temp-file (or in-memory database), or if
  41235. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  41236. ** without doing anything.
  41237. */
  41238. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  41239. Pager *pPager, /* Pager object */
  41240. int *pbOpen /* OUT: Set to true if call is a no-op */
  41241. ){
  41242. int rc = SQLITE_OK; /* Return code */
  41243. assert( assert_pager_state(pPager) );
  41244. assert( pPager->eState==PAGER_OPEN || pbOpen );
  41245. assert( pPager->eState==PAGER_READER || !pbOpen );
  41246. assert( pbOpen==0 || *pbOpen==0 );
  41247. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  41248. if( !pPager->tempFile && !pPager->pWal ){
  41249. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  41250. /* Close any rollback journal previously open */
  41251. sqlite3OsClose(pPager->jfd);
  41252. rc = pagerOpenWal(pPager);
  41253. if( rc==SQLITE_OK ){
  41254. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  41255. pPager->eState = PAGER_OPEN;
  41256. }
  41257. }else{
  41258. *pbOpen = 1;
  41259. }
  41260. return rc;
  41261. }
  41262. /*
  41263. ** This function is called to close the connection to the log file prior
  41264. ** to switching from WAL to rollback mode.
  41265. **
  41266. ** Before closing the log file, this function attempts to take an
  41267. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  41268. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  41269. ** If successful, the EXCLUSIVE lock is not released before returning.
  41270. */
  41271. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  41272. int rc = SQLITE_OK;
  41273. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  41274. /* If the log file is not already open, but does exist in the file-system,
  41275. ** it may need to be checkpointed before the connection can switch to
  41276. ** rollback mode. Open it now so this can happen.
  41277. */
  41278. if( !pPager->pWal ){
  41279. int logexists = 0;
  41280. rc = pagerLockDb(pPager, SHARED_LOCK);
  41281. if( rc==SQLITE_OK ){
  41282. rc = sqlite3OsAccess(
  41283. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  41284. );
  41285. }
  41286. if( rc==SQLITE_OK && logexists ){
  41287. rc = pagerOpenWal(pPager);
  41288. }
  41289. }
  41290. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  41291. ** the database file, the log and log-summary files will be deleted.
  41292. */
  41293. if( rc==SQLITE_OK && pPager->pWal ){
  41294. rc = pagerExclusiveLock(pPager);
  41295. if( rc==SQLITE_OK ){
  41296. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  41297. pPager->pageSize, (u8*)pPager->pTmpSpace);
  41298. pPager->pWal = 0;
  41299. }
  41300. }
  41301. return rc;
  41302. }
  41303. #endif /* !SQLITE_OMIT_WAL */
  41304. #ifdef SQLITE_ENABLE_ZIPVFS
  41305. /*
  41306. ** A read-lock must be held on the pager when this function is called. If
  41307. ** the pager is in WAL mode and the WAL file currently contains one or more
  41308. ** frames, return the size in bytes of the page images stored within the
  41309. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  41310. ** is empty, return 0.
  41311. */
  41312. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  41313. assert( pPager->eState==PAGER_READER );
  41314. return sqlite3WalFramesize(pPager->pWal);
  41315. }
  41316. #endif
  41317. #ifdef SQLITE_HAS_CODEC
  41318. /*
  41319. ** This function is called by the wal module when writing page content
  41320. ** into the log file.
  41321. **
  41322. ** This function returns a pointer to a buffer containing the encrypted
  41323. ** page content. If a malloc fails, this function may return NULL.
  41324. */
  41325. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  41326. void *aData = 0;
  41327. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  41328. return aData;
  41329. }
  41330. #endif /* SQLITE_HAS_CODEC */
  41331. #endif /* SQLITE_OMIT_DISKIO */
  41332. /************** End of pager.c ***********************************************/
  41333. /************** Begin file wal.c *********************************************/
  41334. /*
  41335. ** 2010 February 1
  41336. **
  41337. ** The author disclaims copyright to this source code. In place of
  41338. ** a legal notice, here is a blessing:
  41339. **
  41340. ** May you do good and not evil.
  41341. ** May you find forgiveness for yourself and forgive others.
  41342. ** May you share freely, never taking more than you give.
  41343. **
  41344. *************************************************************************
  41345. **
  41346. ** This file contains the implementation of a write-ahead log (WAL) used in
  41347. ** "journal_mode=WAL" mode.
  41348. **
  41349. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  41350. **
  41351. ** A WAL file consists of a header followed by zero or more "frames".
  41352. ** Each frame records the revised content of a single page from the
  41353. ** database file. All changes to the database are recorded by writing
  41354. ** frames into the WAL. Transactions commit when a frame is written that
  41355. ** contains a commit marker. A single WAL can and usually does record
  41356. ** multiple transactions. Periodically, the content of the WAL is
  41357. ** transferred back into the database file in an operation called a
  41358. ** "checkpoint".
  41359. **
  41360. ** A single WAL file can be used multiple times. In other words, the
  41361. ** WAL can fill up with frames and then be checkpointed and then new
  41362. ** frames can overwrite the old ones. A WAL always grows from beginning
  41363. ** toward the end. Checksums and counters attached to each frame are
  41364. ** used to determine which frames within the WAL are valid and which
  41365. ** are leftovers from prior checkpoints.
  41366. **
  41367. ** The WAL header is 32 bytes in size and consists of the following eight
  41368. ** big-endian 32-bit unsigned integer values:
  41369. **
  41370. ** 0: Magic number. 0x377f0682 or 0x377f0683
  41371. ** 4: File format version. Currently 3007000
  41372. ** 8: Database page size. Example: 1024
  41373. ** 12: Checkpoint sequence number
  41374. ** 16: Salt-1, random integer incremented with each checkpoint
  41375. ** 20: Salt-2, a different random integer changing with each ckpt
  41376. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  41377. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  41378. **
  41379. ** Immediately following the wal-header are zero or more frames. Each
  41380. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  41381. ** of page data. The frame-header is six big-endian 32-bit unsigned
  41382. ** integer values, as follows:
  41383. **
  41384. ** 0: Page number.
  41385. ** 4: For commit records, the size of the database image in pages
  41386. ** after the commit. For all other records, zero.
  41387. ** 8: Salt-1 (copied from the header)
  41388. ** 12: Salt-2 (copied from the header)
  41389. ** 16: Checksum-1.
  41390. ** 20: Checksum-2.
  41391. **
  41392. ** A frame is considered valid if and only if the following conditions are
  41393. ** true:
  41394. **
  41395. ** (1) The salt-1 and salt-2 values in the frame-header match
  41396. ** salt values in the wal-header
  41397. **
  41398. ** (2) The checksum values in the final 8 bytes of the frame-header
  41399. ** exactly match the checksum computed consecutively on the
  41400. ** WAL header and the first 8 bytes and the content of all frames
  41401. ** up to and including the current frame.
  41402. **
  41403. ** The checksum is computed using 32-bit big-endian integers if the
  41404. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  41405. ** is computed using little-endian if the magic number is 0x377f0682.
  41406. ** The checksum values are always stored in the frame header in a
  41407. ** big-endian format regardless of which byte order is used to compute
  41408. ** the checksum. The checksum is computed by interpreting the input as
  41409. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  41410. ** algorithm used for the checksum is as follows:
  41411. **
  41412. ** for i from 0 to n-1 step 2:
  41413. ** s0 += x[i] + s1;
  41414. ** s1 += x[i+1] + s0;
  41415. ** endfor
  41416. **
  41417. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  41418. ** in reverse order (the largest fibonacci weight occurs on the first element
  41419. ** of the sequence being summed.) The s1 value spans all 32-bit
  41420. ** terms of the sequence whereas s0 omits the final term.
  41421. **
  41422. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  41423. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  41424. ** The VFS.xSync operations serve as write barriers - all writes launched
  41425. ** before the xSync must complete before any write that launches after the
  41426. ** xSync begins.
  41427. **
  41428. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  41429. ** value is randomized. This prevents old and new frames in the WAL from
  41430. ** being considered valid at the same time and being checkpointing together
  41431. ** following a crash.
  41432. **
  41433. ** READER ALGORITHM
  41434. **
  41435. ** To read a page from the database (call it page number P), a reader
  41436. ** first checks the WAL to see if it contains page P. If so, then the
  41437. ** last valid instance of page P that is a followed by a commit frame
  41438. ** or is a commit frame itself becomes the value read. If the WAL
  41439. ** contains no copies of page P that are valid and which are a commit
  41440. ** frame or are followed by a commit frame, then page P is read from
  41441. ** the database file.
  41442. **
  41443. ** To start a read transaction, the reader records the index of the last
  41444. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  41445. ** for all subsequent read operations. New transactions can be appended
  41446. ** to the WAL, but as long as the reader uses its original mxFrame value
  41447. ** and ignores the newly appended content, it will see a consistent snapshot
  41448. ** of the database from a single point in time. This technique allows
  41449. ** multiple concurrent readers to view different versions of the database
  41450. ** content simultaneously.
  41451. **
  41452. ** The reader algorithm in the previous paragraphs works correctly, but
  41453. ** because frames for page P can appear anywhere within the WAL, the
  41454. ** reader has to scan the entire WAL looking for page P frames. If the
  41455. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  41456. ** and read performance suffers. To overcome this problem, a separate
  41457. ** data structure called the wal-index is maintained to expedite the
  41458. ** search for frames of a particular page.
  41459. **
  41460. ** WAL-INDEX FORMAT
  41461. **
  41462. ** Conceptually, the wal-index is shared memory, though VFS implementations
  41463. ** might choose to implement the wal-index using a mmapped file. Because
  41464. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  41465. ** on a network filesystem. All users of the database must be able to
  41466. ** share memory.
  41467. **
  41468. ** The wal-index is transient. After a crash, the wal-index can (and should
  41469. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  41470. ** to either truncate or zero the header of the wal-index when the last
  41471. ** connection to it closes. Because the wal-index is transient, it can
  41472. ** use an architecture-specific format; it does not have to be cross-platform.
  41473. ** Hence, unlike the database and WAL file formats which store all values
  41474. ** as big endian, the wal-index can store multi-byte values in the native
  41475. ** byte order of the host computer.
  41476. **
  41477. ** The purpose of the wal-index is to answer this question quickly: Given
  41478. ** a page number P and a maximum frame index M, return the index of the
  41479. ** last frame in the wal before frame M for page P in the WAL, or return
  41480. ** NULL if there are no frames for page P in the WAL prior to M.
  41481. **
  41482. ** The wal-index consists of a header region, followed by an one or
  41483. ** more index blocks.
  41484. **
  41485. ** The wal-index header contains the total number of frames within the WAL
  41486. ** in the mxFrame field.
  41487. **
  41488. ** Each index block except for the first contains information on
  41489. ** HASHTABLE_NPAGE frames. The first index block contains information on
  41490. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  41491. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  41492. ** first index block are the same size as all other index blocks in the
  41493. ** wal-index.
  41494. **
  41495. ** Each index block contains two sections, a page-mapping that contains the
  41496. ** database page number associated with each wal frame, and a hash-table
  41497. ** that allows readers to query an index block for a specific page number.
  41498. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  41499. ** for the first index block) 32-bit page numbers. The first entry in the
  41500. ** first index-block contains the database page number corresponding to the
  41501. ** first frame in the WAL file. The first entry in the second index block
  41502. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  41503. ** the log, and so on.
  41504. **
  41505. ** The last index block in a wal-index usually contains less than the full
  41506. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  41507. ** depending on the contents of the WAL file. This does not change the
  41508. ** allocated size of the page-mapping array - the page-mapping array merely
  41509. ** contains unused entries.
  41510. **
  41511. ** Even without using the hash table, the last frame for page P
  41512. ** can be found by scanning the page-mapping sections of each index block
  41513. ** starting with the last index block and moving toward the first, and
  41514. ** within each index block, starting at the end and moving toward the
  41515. ** beginning. The first entry that equals P corresponds to the frame
  41516. ** holding the content for that page.
  41517. **
  41518. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  41519. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  41520. ** hash table for each page number in the mapping section, so the hash
  41521. ** table is never more than half full. The expected number of collisions
  41522. ** prior to finding a match is 1. Each entry of the hash table is an
  41523. ** 1-based index of an entry in the mapping section of the same
  41524. ** index block. Let K be the 1-based index of the largest entry in
  41525. ** the mapping section. (For index blocks other than the last, K will
  41526. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  41527. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  41528. ** contain a value of 0.
  41529. **
  41530. ** To look for page P in the hash table, first compute a hash iKey on
  41531. ** P as follows:
  41532. **
  41533. ** iKey = (P * 383) % HASHTABLE_NSLOT
  41534. **
  41535. ** Then start scanning entries of the hash table, starting with iKey
  41536. ** (wrapping around to the beginning when the end of the hash table is
  41537. ** reached) until an unused hash slot is found. Let the first unused slot
  41538. ** be at index iUnused. (iUnused might be less than iKey if there was
  41539. ** wrap-around.) Because the hash table is never more than half full,
  41540. ** the search is guaranteed to eventually hit an unused entry. Let
  41541. ** iMax be the value between iKey and iUnused, closest to iUnused,
  41542. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  41543. ** no hash slot such that aHash[i]==p) then page P is not in the
  41544. ** current index block. Otherwise the iMax-th mapping entry of the
  41545. ** current index block corresponds to the last entry that references
  41546. ** page P.
  41547. **
  41548. ** A hash search begins with the last index block and moves toward the
  41549. ** first index block, looking for entries corresponding to page P. On
  41550. ** average, only two or three slots in each index block need to be
  41551. ** examined in order to either find the last entry for page P, or to
  41552. ** establish that no such entry exists in the block. Each index block
  41553. ** holds over 4000 entries. So two or three index blocks are sufficient
  41554. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  41555. ** comparisons (on average) suffice to either locate a frame in the
  41556. ** WAL or to establish that the frame does not exist in the WAL. This
  41557. ** is much faster than scanning the entire 10MB WAL.
  41558. **
  41559. ** Note that entries are added in order of increasing K. Hence, one
  41560. ** reader might be using some value K0 and a second reader that started
  41561. ** at a later time (after additional transactions were added to the WAL
  41562. ** and to the wal-index) might be using a different value K1, where K1>K0.
  41563. ** Both readers can use the same hash table and mapping section to get
  41564. ** the correct result. There may be entries in the hash table with
  41565. ** K>K0 but to the first reader, those entries will appear to be unused
  41566. ** slots in the hash table and so the first reader will get an answer as
  41567. ** if no values greater than K0 had ever been inserted into the hash table
  41568. ** in the first place - which is what reader one wants. Meanwhile, the
  41569. ** second reader using K1 will see additional values that were inserted
  41570. ** later, which is exactly what reader two wants.
  41571. **
  41572. ** When a rollback occurs, the value of K is decreased. Hash table entries
  41573. ** that correspond to frames greater than the new K value are removed
  41574. ** from the hash table at this point.
  41575. */
  41576. #ifndef SQLITE_OMIT_WAL
  41577. /*
  41578. ** Trace output macros
  41579. */
  41580. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  41581. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  41582. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  41583. #else
  41584. # define WALTRACE(X)
  41585. #endif
  41586. /*
  41587. ** The maximum (and only) versions of the wal and wal-index formats
  41588. ** that may be interpreted by this version of SQLite.
  41589. **
  41590. ** If a client begins recovering a WAL file and finds that (a) the checksum
  41591. ** values in the wal-header are correct and (b) the version field is not
  41592. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  41593. **
  41594. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  41595. ** checksum test is successful) and finds that the version field is not
  41596. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  41597. ** returns SQLITE_CANTOPEN.
  41598. */
  41599. #define WAL_MAX_VERSION 3007000
  41600. #define WALINDEX_MAX_VERSION 3007000
  41601. /*
  41602. ** Indices of various locking bytes. WAL_NREADER is the number
  41603. ** of available reader locks and should be at least 3.
  41604. */
  41605. #define WAL_WRITE_LOCK 0
  41606. #define WAL_ALL_BUT_WRITE 1
  41607. #define WAL_CKPT_LOCK 1
  41608. #define WAL_RECOVER_LOCK 2
  41609. #define WAL_READ_LOCK(I) (3+(I))
  41610. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  41611. /* Object declarations */
  41612. typedef struct WalIndexHdr WalIndexHdr;
  41613. typedef struct WalIterator WalIterator;
  41614. typedef struct WalCkptInfo WalCkptInfo;
  41615. /*
  41616. ** The following object holds a copy of the wal-index header content.
  41617. **
  41618. ** The actual header in the wal-index consists of two copies of this
  41619. ** object.
  41620. **
  41621. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  41622. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  41623. ** added in 3.7.1 when support for 64K pages was added.
  41624. */
  41625. struct WalIndexHdr {
  41626. u32 iVersion; /* Wal-index version */
  41627. u32 unused; /* Unused (padding) field */
  41628. u32 iChange; /* Counter incremented each transaction */
  41629. u8 isInit; /* 1 when initialized */
  41630. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  41631. u16 szPage; /* Database page size in bytes. 1==64K */
  41632. u32 mxFrame; /* Index of last valid frame in the WAL */
  41633. u32 nPage; /* Size of database in pages */
  41634. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  41635. u32 aSalt[2]; /* Two salt values copied from WAL header */
  41636. u32 aCksum[2]; /* Checksum over all prior fields */
  41637. };
  41638. /*
  41639. ** A copy of the following object occurs in the wal-index immediately
  41640. ** following the second copy of the WalIndexHdr. This object stores
  41641. ** information used by checkpoint.
  41642. **
  41643. ** nBackfill is the number of frames in the WAL that have been written
  41644. ** back into the database. (We call the act of moving content from WAL to
  41645. ** database "backfilling".) The nBackfill number is never greater than
  41646. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  41647. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  41648. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  41649. ** mxFrame back to zero when the WAL is reset.
  41650. **
  41651. ** There is one entry in aReadMark[] for each reader lock. If a reader
  41652. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  41653. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  41654. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  41655. ** a special case; its value is never used and it exists as a place-holder
  41656. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  41657. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  41658. ** directly from the database.
  41659. **
  41660. ** The value of aReadMark[K] may only be changed by a thread that
  41661. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  41662. ** aReadMark[K] cannot changed while there is a reader is using that mark
  41663. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  41664. **
  41665. ** The checkpointer may only transfer frames from WAL to database where
  41666. ** the frame numbers are less than or equal to every aReadMark[] that is
  41667. ** in use (that is, every aReadMark[j] for which there is a corresponding
  41668. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  41669. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  41670. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  41671. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  41672. ** in the WAL has been backfilled into the database) then new readers
  41673. ** will choose aReadMark[0] which has value 0 and hence such reader will
  41674. ** get all their all content directly from the database file and ignore
  41675. ** the WAL.
  41676. **
  41677. ** Writers normally append new frames to the end of the WAL. However,
  41678. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  41679. ** written back into the database) and if no readers are using the WAL
  41680. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  41681. ** the writer will first "reset" the WAL back to the beginning and start
  41682. ** writing new content beginning at frame 1.
  41683. **
  41684. ** We assume that 32-bit loads are atomic and so no locks are needed in
  41685. ** order to read from any aReadMark[] entries.
  41686. */
  41687. struct WalCkptInfo {
  41688. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  41689. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  41690. };
  41691. #define READMARK_NOT_USED 0xffffffff
  41692. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  41693. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  41694. ** only support mandatory file-locks, we do not read or write data
  41695. ** from the region of the file on which locks are applied.
  41696. */
  41697. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  41698. #define WALINDEX_LOCK_RESERVED 16
  41699. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  41700. /* Size of header before each frame in wal */
  41701. #define WAL_FRAME_HDRSIZE 24
  41702. /* Size of write ahead log header, including checksum. */
  41703. /* #define WAL_HDRSIZE 24 */
  41704. #define WAL_HDRSIZE 32
  41705. /* WAL magic value. Either this value, or the same value with the least
  41706. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  41707. ** big-endian format in the first 4 bytes of a WAL file.
  41708. **
  41709. ** If the LSB is set, then the checksums for each frame within the WAL
  41710. ** file are calculated by treating all data as an array of 32-bit
  41711. ** big-endian words. Otherwise, they are calculated by interpreting
  41712. ** all data as 32-bit little-endian words.
  41713. */
  41714. #define WAL_MAGIC 0x377f0682
  41715. /*
  41716. ** Return the offset of frame iFrame in the write-ahead log file,
  41717. ** assuming a database page size of szPage bytes. The offset returned
  41718. ** is to the start of the write-ahead log frame-header.
  41719. */
  41720. #define walFrameOffset(iFrame, szPage) ( \
  41721. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  41722. )
  41723. /*
  41724. ** An open write-ahead log file is represented by an instance of the
  41725. ** following object.
  41726. */
  41727. struct Wal {
  41728. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  41729. sqlite3_file *pDbFd; /* File handle for the database file */
  41730. sqlite3_file *pWalFd; /* File handle for WAL file */
  41731. u32 iCallback; /* Value to pass to log callback (or 0) */
  41732. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  41733. int nWiData; /* Size of array apWiData */
  41734. int szFirstBlock; /* Size of first block written to WAL file */
  41735. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  41736. u32 szPage; /* Database page size */
  41737. i16 readLock; /* Which read lock is being held. -1 for none */
  41738. u8 syncFlags; /* Flags to use to sync header writes */
  41739. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  41740. u8 writeLock; /* True if in a write transaction */
  41741. u8 ckptLock; /* True if holding a checkpoint lock */
  41742. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  41743. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  41744. u8 syncHeader; /* Fsync the WAL header if true */
  41745. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  41746. WalIndexHdr hdr; /* Wal-index header for current transaction */
  41747. const char *zWalName; /* Name of WAL file */
  41748. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  41749. #ifdef SQLITE_DEBUG
  41750. u8 lockError; /* True if a locking error has occurred */
  41751. #endif
  41752. };
  41753. /*
  41754. ** Candidate values for Wal.exclusiveMode.
  41755. */
  41756. #define WAL_NORMAL_MODE 0
  41757. #define WAL_EXCLUSIVE_MODE 1
  41758. #define WAL_HEAPMEMORY_MODE 2
  41759. /*
  41760. ** Possible values for WAL.readOnly
  41761. */
  41762. #define WAL_RDWR 0 /* Normal read/write connection */
  41763. #define WAL_RDONLY 1 /* The WAL file is readonly */
  41764. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  41765. /*
  41766. ** Each page of the wal-index mapping contains a hash-table made up of
  41767. ** an array of HASHTABLE_NSLOT elements of the following type.
  41768. */
  41769. typedef u16 ht_slot;
  41770. /*
  41771. ** This structure is used to implement an iterator that loops through
  41772. ** all frames in the WAL in database page order. Where two or more frames
  41773. ** correspond to the same database page, the iterator visits only the
  41774. ** frame most recently written to the WAL (in other words, the frame with
  41775. ** the largest index).
  41776. **
  41777. ** The internals of this structure are only accessed by:
  41778. **
  41779. ** walIteratorInit() - Create a new iterator,
  41780. ** walIteratorNext() - Step an iterator,
  41781. ** walIteratorFree() - Free an iterator.
  41782. **
  41783. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  41784. */
  41785. struct WalIterator {
  41786. int iPrior; /* Last result returned from the iterator */
  41787. int nSegment; /* Number of entries in aSegment[] */
  41788. struct WalSegment {
  41789. int iNext; /* Next slot in aIndex[] not yet returned */
  41790. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  41791. u32 *aPgno; /* Array of page numbers. */
  41792. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  41793. int iZero; /* Frame number associated with aPgno[0] */
  41794. } aSegment[1]; /* One for every 32KB page in the wal-index */
  41795. };
  41796. /*
  41797. ** Define the parameters of the hash tables in the wal-index file. There
  41798. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  41799. ** wal-index.
  41800. **
  41801. ** Changing any of these constants will alter the wal-index format and
  41802. ** create incompatibilities.
  41803. */
  41804. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  41805. #define HASHTABLE_HASH_1 383 /* Should be prime */
  41806. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  41807. /*
  41808. ** The block of page numbers associated with the first hash-table in a
  41809. ** wal-index is smaller than usual. This is so that there is a complete
  41810. ** hash-table on each aligned 32KB page of the wal-index.
  41811. */
  41812. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  41813. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  41814. #define WALINDEX_PGSZ ( \
  41815. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  41816. )
  41817. /*
  41818. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  41819. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  41820. ** numbered from zero.
  41821. **
  41822. ** If this call is successful, *ppPage is set to point to the wal-index
  41823. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  41824. ** then an SQLite error code is returned and *ppPage is set to 0.
  41825. */
  41826. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  41827. int rc = SQLITE_OK;
  41828. /* Enlarge the pWal->apWiData[] array if required */
  41829. if( pWal->nWiData<=iPage ){
  41830. int nByte = sizeof(u32*)*(iPage+1);
  41831. volatile u32 **apNew;
  41832. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  41833. if( !apNew ){
  41834. *ppPage = 0;
  41835. return SQLITE_NOMEM;
  41836. }
  41837. memset((void*)&apNew[pWal->nWiData], 0,
  41838. sizeof(u32*)*(iPage+1-pWal->nWiData));
  41839. pWal->apWiData = apNew;
  41840. pWal->nWiData = iPage+1;
  41841. }
  41842. /* Request a pointer to the required page from the VFS */
  41843. if( pWal->apWiData[iPage]==0 ){
  41844. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  41845. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  41846. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  41847. }else{
  41848. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  41849. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  41850. );
  41851. if( rc==SQLITE_READONLY ){
  41852. pWal->readOnly |= WAL_SHM_RDONLY;
  41853. rc = SQLITE_OK;
  41854. }
  41855. }
  41856. }
  41857. *ppPage = pWal->apWiData[iPage];
  41858. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  41859. return rc;
  41860. }
  41861. /*
  41862. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  41863. */
  41864. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  41865. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  41866. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  41867. }
  41868. /*
  41869. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  41870. */
  41871. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  41872. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  41873. return (volatile WalIndexHdr*)pWal->apWiData[0];
  41874. }
  41875. /*
  41876. ** The argument to this macro must be of type u32. On a little-endian
  41877. ** architecture, it returns the u32 value that results from interpreting
  41878. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  41879. ** returns the value that would be produced by intepreting the 4 bytes
  41880. ** of the input value as a little-endian integer.
  41881. */
  41882. #define BYTESWAP32(x) ( \
  41883. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  41884. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  41885. )
  41886. /*
  41887. ** Generate or extend an 8 byte checksum based on the data in
  41888. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  41889. ** initial values of 0 and 0 if aIn==NULL).
  41890. **
  41891. ** The checksum is written back into aOut[] before returning.
  41892. **
  41893. ** nByte must be a positive multiple of 8.
  41894. */
  41895. static void walChecksumBytes(
  41896. int nativeCksum, /* True for native byte-order, false for non-native */
  41897. u8 *a, /* Content to be checksummed */
  41898. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  41899. const u32 *aIn, /* Initial checksum value input */
  41900. u32 *aOut /* OUT: Final checksum value output */
  41901. ){
  41902. u32 s1, s2;
  41903. u32 *aData = (u32 *)a;
  41904. u32 *aEnd = (u32 *)&a[nByte];
  41905. if( aIn ){
  41906. s1 = aIn[0];
  41907. s2 = aIn[1];
  41908. }else{
  41909. s1 = s2 = 0;
  41910. }
  41911. assert( nByte>=8 );
  41912. assert( (nByte&0x00000007)==0 );
  41913. if( nativeCksum ){
  41914. do {
  41915. s1 += *aData++ + s2;
  41916. s2 += *aData++ + s1;
  41917. }while( aData<aEnd );
  41918. }else{
  41919. do {
  41920. s1 += BYTESWAP32(aData[0]) + s2;
  41921. s2 += BYTESWAP32(aData[1]) + s1;
  41922. aData += 2;
  41923. }while( aData<aEnd );
  41924. }
  41925. aOut[0] = s1;
  41926. aOut[1] = s2;
  41927. }
  41928. static void walShmBarrier(Wal *pWal){
  41929. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  41930. sqlite3OsShmBarrier(pWal->pDbFd);
  41931. }
  41932. }
  41933. /*
  41934. ** Write the header information in pWal->hdr into the wal-index.
  41935. **
  41936. ** The checksum on pWal->hdr is updated before it is written.
  41937. */
  41938. static void walIndexWriteHdr(Wal *pWal){
  41939. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  41940. const int nCksum = offsetof(WalIndexHdr, aCksum);
  41941. assert( pWal->writeLock );
  41942. pWal->hdr.isInit = 1;
  41943. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  41944. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  41945. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  41946. walShmBarrier(pWal);
  41947. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  41948. }
  41949. /*
  41950. ** This function encodes a single frame header and writes it to a buffer
  41951. ** supplied by the caller. A frame-header is made up of a series of
  41952. ** 4-byte big-endian integers, as follows:
  41953. **
  41954. ** 0: Page number.
  41955. ** 4: For commit records, the size of the database image in pages
  41956. ** after the commit. For all other records, zero.
  41957. ** 8: Salt-1 (copied from the wal-header)
  41958. ** 12: Salt-2 (copied from the wal-header)
  41959. ** 16: Checksum-1.
  41960. ** 20: Checksum-2.
  41961. */
  41962. static void walEncodeFrame(
  41963. Wal *pWal, /* The write-ahead log */
  41964. u32 iPage, /* Database page number for frame */
  41965. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  41966. u8 *aData, /* Pointer to page data */
  41967. u8 *aFrame /* OUT: Write encoded frame here */
  41968. ){
  41969. int nativeCksum; /* True for native byte-order checksums */
  41970. u32 *aCksum = pWal->hdr.aFrameCksum;
  41971. assert( WAL_FRAME_HDRSIZE==24 );
  41972. sqlite3Put4byte(&aFrame[0], iPage);
  41973. sqlite3Put4byte(&aFrame[4], nTruncate);
  41974. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  41975. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  41976. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  41977. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  41978. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  41979. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  41980. }
  41981. /*
  41982. ** Check to see if the frame with header in aFrame[] and content
  41983. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  41984. ** *pnTruncate and return true. Return if the frame is not valid.
  41985. */
  41986. static int walDecodeFrame(
  41987. Wal *pWal, /* The write-ahead log */
  41988. u32 *piPage, /* OUT: Database page number for frame */
  41989. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  41990. u8 *aData, /* Pointer to page data (for checksum) */
  41991. u8 *aFrame /* Frame data */
  41992. ){
  41993. int nativeCksum; /* True for native byte-order checksums */
  41994. u32 *aCksum = pWal->hdr.aFrameCksum;
  41995. u32 pgno; /* Page number of the frame */
  41996. assert( WAL_FRAME_HDRSIZE==24 );
  41997. /* A frame is only valid if the salt values in the frame-header
  41998. ** match the salt values in the wal-header.
  41999. */
  42000. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  42001. return 0;
  42002. }
  42003. /* A frame is only valid if the page number is creater than zero.
  42004. */
  42005. pgno = sqlite3Get4byte(&aFrame[0]);
  42006. if( pgno==0 ){
  42007. return 0;
  42008. }
  42009. /* A frame is only valid if a checksum of the WAL header,
  42010. ** all prior frams, the first 16 bytes of this frame-header,
  42011. ** and the frame-data matches the checksum in the last 8
  42012. ** bytes of this frame-header.
  42013. */
  42014. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  42015. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  42016. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  42017. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  42018. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  42019. ){
  42020. /* Checksum failed. */
  42021. return 0;
  42022. }
  42023. /* If we reach this point, the frame is valid. Return the page number
  42024. ** and the new database size.
  42025. */
  42026. *piPage = pgno;
  42027. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  42028. return 1;
  42029. }
  42030. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  42031. /*
  42032. ** Names of locks. This routine is used to provide debugging output and is not
  42033. ** a part of an ordinary build.
  42034. */
  42035. static const char *walLockName(int lockIdx){
  42036. if( lockIdx==WAL_WRITE_LOCK ){
  42037. return "WRITE-LOCK";
  42038. }else if( lockIdx==WAL_CKPT_LOCK ){
  42039. return "CKPT-LOCK";
  42040. }else if( lockIdx==WAL_RECOVER_LOCK ){
  42041. return "RECOVER-LOCK";
  42042. }else{
  42043. static char zName[15];
  42044. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  42045. lockIdx-WAL_READ_LOCK(0));
  42046. return zName;
  42047. }
  42048. }
  42049. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  42050. /*
  42051. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  42052. ** A lock cannot be moved directly between shared and exclusive - it must go
  42053. ** through the unlocked state first.
  42054. **
  42055. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  42056. */
  42057. static int walLockShared(Wal *pWal, int lockIdx){
  42058. int rc;
  42059. if( pWal->exclusiveMode ) return SQLITE_OK;
  42060. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  42061. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  42062. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  42063. walLockName(lockIdx), rc ? "failed" : "ok"));
  42064. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  42065. return rc;
  42066. }
  42067. static void walUnlockShared(Wal *pWal, int lockIdx){
  42068. if( pWal->exclusiveMode ) return;
  42069. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  42070. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  42071. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  42072. }
  42073. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  42074. int rc;
  42075. if( pWal->exclusiveMode ) return SQLITE_OK;
  42076. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  42077. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  42078. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  42079. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  42080. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  42081. return rc;
  42082. }
  42083. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  42084. if( pWal->exclusiveMode ) return;
  42085. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  42086. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  42087. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  42088. walLockName(lockIdx), n));
  42089. }
  42090. /*
  42091. ** Compute a hash on a page number. The resulting hash value must land
  42092. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  42093. ** the hash to the next value in the event of a collision.
  42094. */
  42095. static int walHash(u32 iPage){
  42096. assert( iPage>0 );
  42097. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  42098. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  42099. }
  42100. static int walNextHash(int iPriorHash){
  42101. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  42102. }
  42103. /*
  42104. ** Return pointers to the hash table and page number array stored on
  42105. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  42106. ** numbered starting from 0.
  42107. **
  42108. ** Set output variable *paHash to point to the start of the hash table
  42109. ** in the wal-index file. Set *piZero to one less than the frame
  42110. ** number of the first frame indexed by this hash table. If a
  42111. ** slot in the hash table is set to N, it refers to frame number
  42112. ** (*piZero+N) in the log.
  42113. **
  42114. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  42115. ** first frame indexed by the hash table, frame (*piZero+1).
  42116. */
  42117. static int walHashGet(
  42118. Wal *pWal, /* WAL handle */
  42119. int iHash, /* Find the iHash'th table */
  42120. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  42121. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  42122. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  42123. ){
  42124. int rc; /* Return code */
  42125. volatile u32 *aPgno;
  42126. rc = walIndexPage(pWal, iHash, &aPgno);
  42127. assert( rc==SQLITE_OK || iHash>0 );
  42128. if( rc==SQLITE_OK ){
  42129. u32 iZero;
  42130. volatile ht_slot *aHash;
  42131. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  42132. if( iHash==0 ){
  42133. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  42134. iZero = 0;
  42135. }else{
  42136. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  42137. }
  42138. *paPgno = &aPgno[-1];
  42139. *paHash = aHash;
  42140. *piZero = iZero;
  42141. }
  42142. return rc;
  42143. }
  42144. /*
  42145. ** Return the number of the wal-index page that contains the hash-table
  42146. ** and page-number array that contain entries corresponding to WAL frame
  42147. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  42148. ** are numbered starting from 0.
  42149. */
  42150. static int walFramePage(u32 iFrame){
  42151. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  42152. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  42153. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  42154. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  42155. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  42156. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  42157. );
  42158. return iHash;
  42159. }
  42160. /*
  42161. ** Return the page number associated with frame iFrame in this WAL.
  42162. */
  42163. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  42164. int iHash = walFramePage(iFrame);
  42165. if( iHash==0 ){
  42166. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  42167. }
  42168. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  42169. }
  42170. /*
  42171. ** Remove entries from the hash table that point to WAL slots greater
  42172. ** than pWal->hdr.mxFrame.
  42173. **
  42174. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  42175. ** to a rollback or savepoint.
  42176. **
  42177. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  42178. ** updated. Any later hash tables will be automatically cleared when
  42179. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  42180. ** actually needed.
  42181. */
  42182. static void walCleanupHash(Wal *pWal){
  42183. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  42184. volatile u32 *aPgno = 0; /* Page number array for hash table */
  42185. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  42186. int iLimit = 0; /* Zero values greater than this */
  42187. int nByte; /* Number of bytes to zero in aPgno[] */
  42188. int i; /* Used to iterate through aHash[] */
  42189. assert( pWal->writeLock );
  42190. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  42191. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  42192. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  42193. if( pWal->hdr.mxFrame==0 ) return;
  42194. /* Obtain pointers to the hash-table and page-number array containing
  42195. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  42196. ** that the page said hash-table and array reside on is already mapped.
  42197. */
  42198. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  42199. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  42200. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  42201. /* Zero all hash-table entries that correspond to frame numbers greater
  42202. ** than pWal->hdr.mxFrame.
  42203. */
  42204. iLimit = pWal->hdr.mxFrame - iZero;
  42205. assert( iLimit>0 );
  42206. for(i=0; i<HASHTABLE_NSLOT; i++){
  42207. if( aHash[i]>iLimit ){
  42208. aHash[i] = 0;
  42209. }
  42210. }
  42211. /* Zero the entries in the aPgno array that correspond to frames with
  42212. ** frame numbers greater than pWal->hdr.mxFrame.
  42213. */
  42214. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  42215. memset((void *)&aPgno[iLimit+1], 0, nByte);
  42216. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  42217. /* Verify that the every entry in the mapping region is still reachable
  42218. ** via the hash table even after the cleanup.
  42219. */
  42220. if( iLimit ){
  42221. int i; /* Loop counter */
  42222. int iKey; /* Hash key */
  42223. for(i=1; i<=iLimit; i++){
  42224. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  42225. if( aHash[iKey]==i ) break;
  42226. }
  42227. assert( aHash[iKey]==i );
  42228. }
  42229. }
  42230. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  42231. }
  42232. /*
  42233. ** Set an entry in the wal-index that will map database page number
  42234. ** pPage into WAL frame iFrame.
  42235. */
  42236. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  42237. int rc; /* Return code */
  42238. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  42239. volatile u32 *aPgno = 0; /* Page number array */
  42240. volatile ht_slot *aHash = 0; /* Hash table */
  42241. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  42242. /* Assuming the wal-index file was successfully mapped, populate the
  42243. ** page number array and hash table entry.
  42244. */
  42245. if( rc==SQLITE_OK ){
  42246. int iKey; /* Hash table key */
  42247. int idx; /* Value to write to hash-table slot */
  42248. int nCollide; /* Number of hash collisions */
  42249. idx = iFrame - iZero;
  42250. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  42251. /* If this is the first entry to be added to this hash-table, zero the
  42252. ** entire hash table and aPgno[] array before proceding.
  42253. */
  42254. if( idx==1 ){
  42255. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  42256. memset((void*)&aPgno[1], 0, nByte);
  42257. }
  42258. /* If the entry in aPgno[] is already set, then the previous writer
  42259. ** must have exited unexpectedly in the middle of a transaction (after
  42260. ** writing one or more dirty pages to the WAL to free up memory).
  42261. ** Remove the remnants of that writers uncommitted transaction from
  42262. ** the hash-table before writing any new entries.
  42263. */
  42264. if( aPgno[idx] ){
  42265. walCleanupHash(pWal);
  42266. assert( !aPgno[idx] );
  42267. }
  42268. /* Write the aPgno[] array entry and the hash-table slot. */
  42269. nCollide = idx;
  42270. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  42271. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  42272. }
  42273. aPgno[idx] = iPage;
  42274. aHash[iKey] = (ht_slot)idx;
  42275. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  42276. /* Verify that the number of entries in the hash table exactly equals
  42277. ** the number of entries in the mapping region.
  42278. */
  42279. {
  42280. int i; /* Loop counter */
  42281. int nEntry = 0; /* Number of entries in the hash table */
  42282. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  42283. assert( nEntry==idx );
  42284. }
  42285. /* Verify that the every entry in the mapping region is reachable
  42286. ** via the hash table. This turns out to be a really, really expensive
  42287. ** thing to check, so only do this occasionally - not on every
  42288. ** iteration.
  42289. */
  42290. if( (idx&0x3ff)==0 ){
  42291. int i; /* Loop counter */
  42292. for(i=1; i<=idx; i++){
  42293. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  42294. if( aHash[iKey]==i ) break;
  42295. }
  42296. assert( aHash[iKey]==i );
  42297. }
  42298. }
  42299. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  42300. }
  42301. return rc;
  42302. }
  42303. /*
  42304. ** Recover the wal-index by reading the write-ahead log file.
  42305. **
  42306. ** This routine first tries to establish an exclusive lock on the
  42307. ** wal-index to prevent other threads/processes from doing anything
  42308. ** with the WAL or wal-index while recovery is running. The
  42309. ** WAL_RECOVER_LOCK is also held so that other threads will know
  42310. ** that this thread is running recovery. If unable to establish
  42311. ** the necessary locks, this routine returns SQLITE_BUSY.
  42312. */
  42313. static int walIndexRecover(Wal *pWal){
  42314. int rc; /* Return Code */
  42315. i64 nSize; /* Size of log file */
  42316. u32 aFrameCksum[2] = {0, 0};
  42317. int iLock; /* Lock offset to lock for checkpoint */
  42318. int nLock; /* Number of locks to hold */
  42319. /* Obtain an exclusive lock on all byte in the locking range not already
  42320. ** locked by the caller. The caller is guaranteed to have locked the
  42321. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  42322. ** If successful, the same bytes that are locked here are unlocked before
  42323. ** this function returns.
  42324. */
  42325. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  42326. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  42327. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  42328. assert( pWal->writeLock );
  42329. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  42330. nLock = SQLITE_SHM_NLOCK - iLock;
  42331. rc = walLockExclusive(pWal, iLock, nLock);
  42332. if( rc ){
  42333. return rc;
  42334. }
  42335. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  42336. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  42337. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  42338. if( rc!=SQLITE_OK ){
  42339. goto recovery_error;
  42340. }
  42341. if( nSize>WAL_HDRSIZE ){
  42342. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  42343. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  42344. int szFrame; /* Number of bytes in buffer aFrame[] */
  42345. u8 *aData; /* Pointer to data part of aFrame buffer */
  42346. int iFrame; /* Index of last frame read */
  42347. i64 iOffset; /* Next offset to read from log file */
  42348. int szPage; /* Page size according to the log */
  42349. u32 magic; /* Magic value read from WAL header */
  42350. u32 version; /* Magic value read from WAL header */
  42351. int isValid; /* True if this frame is valid */
  42352. /* Read in the WAL header. */
  42353. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  42354. if( rc!=SQLITE_OK ){
  42355. goto recovery_error;
  42356. }
  42357. /* If the database page size is not a power of two, or is greater than
  42358. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  42359. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  42360. ** WAL file.
  42361. */
  42362. magic = sqlite3Get4byte(&aBuf[0]);
  42363. szPage = sqlite3Get4byte(&aBuf[8]);
  42364. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  42365. || szPage&(szPage-1)
  42366. || szPage>SQLITE_MAX_PAGE_SIZE
  42367. || szPage<512
  42368. ){
  42369. goto finished;
  42370. }
  42371. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  42372. pWal->szPage = szPage;
  42373. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  42374. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  42375. /* Verify that the WAL header checksum is correct */
  42376. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  42377. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  42378. );
  42379. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  42380. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  42381. ){
  42382. goto finished;
  42383. }
  42384. /* Verify that the version number on the WAL format is one that
  42385. ** are able to understand */
  42386. version = sqlite3Get4byte(&aBuf[4]);
  42387. if( version!=WAL_MAX_VERSION ){
  42388. rc = SQLITE_CANTOPEN_BKPT;
  42389. goto finished;
  42390. }
  42391. /* Malloc a buffer to read frames into. */
  42392. szFrame = szPage + WAL_FRAME_HDRSIZE;
  42393. aFrame = (u8 *)sqlite3_malloc(szFrame);
  42394. if( !aFrame ){
  42395. rc = SQLITE_NOMEM;
  42396. goto recovery_error;
  42397. }
  42398. aData = &aFrame[WAL_FRAME_HDRSIZE];
  42399. /* Read all frames from the log file. */
  42400. iFrame = 0;
  42401. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  42402. u32 pgno; /* Database page number for frame */
  42403. u32 nTruncate; /* dbsize field from frame header */
  42404. /* Read and decode the next log frame. */
  42405. iFrame++;
  42406. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  42407. if( rc!=SQLITE_OK ) break;
  42408. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  42409. if( !isValid ) break;
  42410. rc = walIndexAppend(pWal, iFrame, pgno);
  42411. if( rc!=SQLITE_OK ) break;
  42412. /* If nTruncate is non-zero, this is a commit record. */
  42413. if( nTruncate ){
  42414. pWal->hdr.mxFrame = iFrame;
  42415. pWal->hdr.nPage = nTruncate;
  42416. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  42417. testcase( szPage<=32768 );
  42418. testcase( szPage>=65536 );
  42419. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  42420. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  42421. }
  42422. }
  42423. sqlite3_free(aFrame);
  42424. }
  42425. finished:
  42426. if( rc==SQLITE_OK ){
  42427. volatile WalCkptInfo *pInfo;
  42428. int i;
  42429. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  42430. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  42431. walIndexWriteHdr(pWal);
  42432. /* Reset the checkpoint-header. This is safe because this thread is
  42433. ** currently holding locks that exclude all other readers, writers and
  42434. ** checkpointers.
  42435. */
  42436. pInfo = walCkptInfo(pWal);
  42437. pInfo->nBackfill = 0;
  42438. pInfo->aReadMark[0] = 0;
  42439. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  42440. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  42441. /* If more than one frame was recovered from the log file, report an
  42442. ** event via sqlite3_log(). This is to help with identifying performance
  42443. ** problems caused by applications routinely shutting down without
  42444. ** checkpointing the log file.
  42445. */
  42446. if( pWal->hdr.nPage ){
  42447. sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
  42448. pWal->hdr.nPage, pWal->zWalName
  42449. );
  42450. }
  42451. }
  42452. recovery_error:
  42453. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  42454. walUnlockExclusive(pWal, iLock, nLock);
  42455. return rc;
  42456. }
  42457. /*
  42458. ** Close an open wal-index.
  42459. */
  42460. static void walIndexClose(Wal *pWal, int isDelete){
  42461. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  42462. int i;
  42463. for(i=0; i<pWal->nWiData; i++){
  42464. sqlite3_free((void *)pWal->apWiData[i]);
  42465. pWal->apWiData[i] = 0;
  42466. }
  42467. }else{
  42468. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  42469. }
  42470. }
  42471. /*
  42472. ** Open a connection to the WAL file zWalName. The database file must
  42473. ** already be opened on connection pDbFd. The buffer that zWalName points
  42474. ** to must remain valid for the lifetime of the returned Wal* handle.
  42475. **
  42476. ** A SHARED lock should be held on the database file when this function
  42477. ** is called. The purpose of this SHARED lock is to prevent any other
  42478. ** client from unlinking the WAL or wal-index file. If another process
  42479. ** were to do this just after this client opened one of these files, the
  42480. ** system would be badly broken.
  42481. **
  42482. ** If the log file is successfully opened, SQLITE_OK is returned and
  42483. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  42484. ** an SQLite error code is returned and *ppWal is left unmodified.
  42485. */
  42486. SQLITE_PRIVATE int sqlite3WalOpen(
  42487. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  42488. sqlite3_file *pDbFd, /* The open database file */
  42489. const char *zWalName, /* Name of the WAL file */
  42490. int bNoShm, /* True to run in heap-memory mode */
  42491. i64 mxWalSize, /* Truncate WAL to this size on reset */
  42492. Wal **ppWal /* OUT: Allocated Wal handle */
  42493. ){
  42494. int rc; /* Return Code */
  42495. Wal *pRet; /* Object to allocate and return */
  42496. int flags; /* Flags passed to OsOpen() */
  42497. assert( zWalName && zWalName[0] );
  42498. assert( pDbFd );
  42499. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  42500. ** this source file. Verify that the #defines of the locking byte offsets
  42501. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  42502. */
  42503. #ifdef WIN_SHM_BASE
  42504. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  42505. #endif
  42506. #ifdef UNIX_SHM_BASE
  42507. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  42508. #endif
  42509. /* Allocate an instance of struct Wal to return. */
  42510. *ppWal = 0;
  42511. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  42512. if( !pRet ){
  42513. return SQLITE_NOMEM;
  42514. }
  42515. pRet->pVfs = pVfs;
  42516. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  42517. pRet->pDbFd = pDbFd;
  42518. pRet->readLock = -1;
  42519. pRet->mxWalSize = mxWalSize;
  42520. pRet->zWalName = zWalName;
  42521. pRet->syncHeader = 1;
  42522. pRet->padToSectorBoundary = 1;
  42523. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  42524. /* Open file handle on the write-ahead log file. */
  42525. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  42526. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  42527. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  42528. pRet->readOnly = WAL_RDONLY;
  42529. }
  42530. if( rc!=SQLITE_OK ){
  42531. walIndexClose(pRet, 0);
  42532. sqlite3OsClose(pRet->pWalFd);
  42533. sqlite3_free(pRet);
  42534. }else{
  42535. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  42536. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  42537. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  42538. pRet->padToSectorBoundary = 0;
  42539. }
  42540. *ppWal = pRet;
  42541. WALTRACE(("WAL%d: opened\n", pRet));
  42542. }
  42543. return rc;
  42544. }
  42545. /*
  42546. ** Change the size to which the WAL file is trucated on each reset.
  42547. */
  42548. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  42549. if( pWal ) pWal->mxWalSize = iLimit;
  42550. }
  42551. /*
  42552. ** Find the smallest page number out of all pages held in the WAL that
  42553. ** has not been returned by any prior invocation of this method on the
  42554. ** same WalIterator object. Write into *piFrame the frame index where
  42555. ** that page was last written into the WAL. Write into *piPage the page
  42556. ** number.
  42557. **
  42558. ** Return 0 on success. If there are no pages in the WAL with a page
  42559. ** number larger than *piPage, then return 1.
  42560. */
  42561. static int walIteratorNext(
  42562. WalIterator *p, /* Iterator */
  42563. u32 *piPage, /* OUT: The page number of the next page */
  42564. u32 *piFrame /* OUT: Wal frame index of next page */
  42565. ){
  42566. u32 iMin; /* Result pgno must be greater than iMin */
  42567. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  42568. int i; /* For looping through segments */
  42569. iMin = p->iPrior;
  42570. assert( iMin<0xffffffff );
  42571. for(i=p->nSegment-1; i>=0; i--){
  42572. struct WalSegment *pSegment = &p->aSegment[i];
  42573. while( pSegment->iNext<pSegment->nEntry ){
  42574. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  42575. if( iPg>iMin ){
  42576. if( iPg<iRet ){
  42577. iRet = iPg;
  42578. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  42579. }
  42580. break;
  42581. }
  42582. pSegment->iNext++;
  42583. }
  42584. }
  42585. *piPage = p->iPrior = iRet;
  42586. return (iRet==0xFFFFFFFF);
  42587. }
  42588. /*
  42589. ** This function merges two sorted lists into a single sorted list.
  42590. **
  42591. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  42592. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  42593. ** is guaranteed for all J<K:
  42594. **
  42595. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  42596. ** aContent[aRight[J]] < aContent[aRight[K]]
  42597. **
  42598. ** This routine overwrites aRight[] with a new (probably longer) sequence
  42599. ** of indices such that the aRight[] contains every index that appears in
  42600. ** either aLeft[] or the old aRight[] and such that the second condition
  42601. ** above is still met.
  42602. **
  42603. ** The aContent[aLeft[X]] values will be unique for all X. And the
  42604. ** aContent[aRight[X]] values will be unique too. But there might be
  42605. ** one or more combinations of X and Y such that
  42606. **
  42607. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  42608. **
  42609. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  42610. */
  42611. static void walMerge(
  42612. const u32 *aContent, /* Pages in wal - keys for the sort */
  42613. ht_slot *aLeft, /* IN: Left hand input list */
  42614. int nLeft, /* IN: Elements in array *paLeft */
  42615. ht_slot **paRight, /* IN/OUT: Right hand input list */
  42616. int *pnRight, /* IN/OUT: Elements in *paRight */
  42617. ht_slot *aTmp /* Temporary buffer */
  42618. ){
  42619. int iLeft = 0; /* Current index in aLeft */
  42620. int iRight = 0; /* Current index in aRight */
  42621. int iOut = 0; /* Current index in output buffer */
  42622. int nRight = *pnRight;
  42623. ht_slot *aRight = *paRight;
  42624. assert( nLeft>0 && nRight>0 );
  42625. while( iRight<nRight || iLeft<nLeft ){
  42626. ht_slot logpage;
  42627. Pgno dbpage;
  42628. if( (iLeft<nLeft)
  42629. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  42630. ){
  42631. logpage = aLeft[iLeft++];
  42632. }else{
  42633. logpage = aRight[iRight++];
  42634. }
  42635. dbpage = aContent[logpage];
  42636. aTmp[iOut++] = logpage;
  42637. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  42638. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  42639. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  42640. }
  42641. *paRight = aLeft;
  42642. *pnRight = iOut;
  42643. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  42644. }
  42645. /*
  42646. ** Sort the elements in list aList using aContent[] as the sort key.
  42647. ** Remove elements with duplicate keys, preferring to keep the
  42648. ** larger aList[] values.
  42649. **
  42650. ** The aList[] entries are indices into aContent[]. The values in
  42651. ** aList[] are to be sorted so that for all J<K:
  42652. **
  42653. ** aContent[aList[J]] < aContent[aList[K]]
  42654. **
  42655. ** For any X and Y such that
  42656. **
  42657. ** aContent[aList[X]] == aContent[aList[Y]]
  42658. **
  42659. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  42660. ** the smaller.
  42661. */
  42662. static void walMergesort(
  42663. const u32 *aContent, /* Pages in wal */
  42664. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  42665. ht_slot *aList, /* IN/OUT: List to sort */
  42666. int *pnList /* IN/OUT: Number of elements in aList[] */
  42667. ){
  42668. struct Sublist {
  42669. int nList; /* Number of elements in aList */
  42670. ht_slot *aList; /* Pointer to sub-list content */
  42671. };
  42672. const int nList = *pnList; /* Size of input list */
  42673. int nMerge = 0; /* Number of elements in list aMerge */
  42674. ht_slot *aMerge = 0; /* List to be merged */
  42675. int iList; /* Index into input list */
  42676. int iSub = 0; /* Index into aSub array */
  42677. struct Sublist aSub[13]; /* Array of sub-lists */
  42678. memset(aSub, 0, sizeof(aSub));
  42679. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  42680. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  42681. for(iList=0; iList<nList; iList++){
  42682. nMerge = 1;
  42683. aMerge = &aList[iList];
  42684. for(iSub=0; iList & (1<<iSub); iSub++){
  42685. struct Sublist *p = &aSub[iSub];
  42686. assert( p->aList && p->nList<=(1<<iSub) );
  42687. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  42688. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  42689. }
  42690. aSub[iSub].aList = aMerge;
  42691. aSub[iSub].nList = nMerge;
  42692. }
  42693. for(iSub++; iSub<ArraySize(aSub); iSub++){
  42694. if( nList & (1<<iSub) ){
  42695. struct Sublist *p = &aSub[iSub];
  42696. assert( p->nList<=(1<<iSub) );
  42697. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  42698. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  42699. }
  42700. }
  42701. assert( aMerge==aList );
  42702. *pnList = nMerge;
  42703. #ifdef SQLITE_DEBUG
  42704. {
  42705. int i;
  42706. for(i=1; i<*pnList; i++){
  42707. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  42708. }
  42709. }
  42710. #endif
  42711. }
  42712. /*
  42713. ** Free an iterator allocated by walIteratorInit().
  42714. */
  42715. static void walIteratorFree(WalIterator *p){
  42716. sqlite3ScratchFree(p);
  42717. }
  42718. /*
  42719. ** Construct a WalInterator object that can be used to loop over all
  42720. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  42721. ** lock.
  42722. **
  42723. ** On success, make *pp point to the newly allocated WalInterator object
  42724. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  42725. ** returns an error, the value of *pp is undefined.
  42726. **
  42727. ** The calling routine should invoke walIteratorFree() to destroy the
  42728. ** WalIterator object when it has finished with it.
  42729. */
  42730. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  42731. WalIterator *p; /* Return value */
  42732. int nSegment; /* Number of segments to merge */
  42733. u32 iLast; /* Last frame in log */
  42734. int nByte; /* Number of bytes to allocate */
  42735. int i; /* Iterator variable */
  42736. ht_slot *aTmp; /* Temp space used by merge-sort */
  42737. int rc = SQLITE_OK; /* Return Code */
  42738. /* This routine only runs while holding the checkpoint lock. And
  42739. ** it only runs if there is actually content in the log (mxFrame>0).
  42740. */
  42741. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  42742. iLast = pWal->hdr.mxFrame;
  42743. /* Allocate space for the WalIterator object. */
  42744. nSegment = walFramePage(iLast) + 1;
  42745. nByte = sizeof(WalIterator)
  42746. + (nSegment-1)*sizeof(struct WalSegment)
  42747. + iLast*sizeof(ht_slot);
  42748. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  42749. if( !p ){
  42750. return SQLITE_NOMEM;
  42751. }
  42752. memset(p, 0, nByte);
  42753. p->nSegment = nSegment;
  42754. /* Allocate temporary space used by the merge-sort routine. This block
  42755. ** of memory will be freed before this function returns.
  42756. */
  42757. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  42758. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  42759. );
  42760. if( !aTmp ){
  42761. rc = SQLITE_NOMEM;
  42762. }
  42763. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  42764. volatile ht_slot *aHash;
  42765. u32 iZero;
  42766. volatile u32 *aPgno;
  42767. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  42768. if( rc==SQLITE_OK ){
  42769. int j; /* Counter variable */
  42770. int nEntry; /* Number of entries in this segment */
  42771. ht_slot *aIndex; /* Sorted index for this segment */
  42772. aPgno++;
  42773. if( (i+1)==nSegment ){
  42774. nEntry = (int)(iLast - iZero);
  42775. }else{
  42776. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  42777. }
  42778. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  42779. iZero++;
  42780. for(j=0; j<nEntry; j++){
  42781. aIndex[j] = (ht_slot)j;
  42782. }
  42783. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  42784. p->aSegment[i].iZero = iZero;
  42785. p->aSegment[i].nEntry = nEntry;
  42786. p->aSegment[i].aIndex = aIndex;
  42787. p->aSegment[i].aPgno = (u32 *)aPgno;
  42788. }
  42789. }
  42790. sqlite3ScratchFree(aTmp);
  42791. if( rc!=SQLITE_OK ){
  42792. walIteratorFree(p);
  42793. }
  42794. *pp = p;
  42795. return rc;
  42796. }
  42797. /*
  42798. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  42799. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  42800. ** busy-handler function. Invoke it and retry the lock until either the
  42801. ** lock is successfully obtained or the busy-handler returns 0.
  42802. */
  42803. static int walBusyLock(
  42804. Wal *pWal, /* WAL connection */
  42805. int (*xBusy)(void*), /* Function to call when busy */
  42806. void *pBusyArg, /* Context argument for xBusyHandler */
  42807. int lockIdx, /* Offset of first byte to lock */
  42808. int n /* Number of bytes to lock */
  42809. ){
  42810. int rc;
  42811. do {
  42812. rc = walLockExclusive(pWal, lockIdx, n);
  42813. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  42814. return rc;
  42815. }
  42816. /*
  42817. ** The cache of the wal-index header must be valid to call this function.
  42818. ** Return the page-size in bytes used by the database.
  42819. */
  42820. static int walPagesize(Wal *pWal){
  42821. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  42822. }
  42823. /*
  42824. ** Copy as much content as we can from the WAL back into the database file
  42825. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  42826. **
  42827. ** The amount of information copies from WAL to database might be limited
  42828. ** by active readers. This routine will never overwrite a database page
  42829. ** that a concurrent reader might be using.
  42830. **
  42831. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  42832. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  42833. ** checkpoints are always run by a background thread or background
  42834. ** process, foreground threads will never block on a lengthy fsync call.
  42835. **
  42836. ** Fsync is called on the WAL before writing content out of the WAL and
  42837. ** into the database. This ensures that if the new content is persistent
  42838. ** in the WAL and can be recovered following a power-loss or hard reset.
  42839. **
  42840. ** Fsync is also called on the database file if (and only if) the entire
  42841. ** WAL content is copied into the database file. This second fsync makes
  42842. ** it safe to delete the WAL since the new content will persist in the
  42843. ** database file.
  42844. **
  42845. ** This routine uses and updates the nBackfill field of the wal-index header.
  42846. ** This is the only routine tha will increase the value of nBackfill.
  42847. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  42848. ** its value.)
  42849. **
  42850. ** The caller must be holding sufficient locks to ensure that no other
  42851. ** checkpoint is running (in any other thread or process) at the same
  42852. ** time.
  42853. */
  42854. static int walCheckpoint(
  42855. Wal *pWal, /* Wal connection */
  42856. int eMode, /* One of PASSIVE, FULL or RESTART */
  42857. int (*xBusyCall)(void*), /* Function to call when busy */
  42858. void *pBusyArg, /* Context argument for xBusyHandler */
  42859. int sync_flags, /* Flags for OsSync() (or 0) */
  42860. u8 *zBuf /* Temporary buffer to use */
  42861. ){
  42862. int rc; /* Return code */
  42863. int szPage; /* Database page-size */
  42864. WalIterator *pIter = 0; /* Wal iterator context */
  42865. u32 iDbpage = 0; /* Next database page to write */
  42866. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  42867. u32 mxSafeFrame; /* Max frame that can be backfilled */
  42868. u32 mxPage; /* Max database page to write */
  42869. int i; /* Loop counter */
  42870. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  42871. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  42872. szPage = walPagesize(pWal);
  42873. testcase( szPage<=32768 );
  42874. testcase( szPage>=65536 );
  42875. pInfo = walCkptInfo(pWal);
  42876. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  42877. /* Allocate the iterator */
  42878. rc = walIteratorInit(pWal, &pIter);
  42879. if( rc!=SQLITE_OK ){
  42880. return rc;
  42881. }
  42882. assert( pIter );
  42883. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  42884. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  42885. ** safe to write into the database. Frames beyond mxSafeFrame might
  42886. ** overwrite database pages that are in use by active readers and thus
  42887. ** cannot be backfilled from the WAL.
  42888. */
  42889. mxSafeFrame = pWal->hdr.mxFrame;
  42890. mxPage = pWal->hdr.nPage;
  42891. for(i=1; i<WAL_NREADER; i++){
  42892. u32 y = pInfo->aReadMark[i];
  42893. if( mxSafeFrame>y ){
  42894. assert( y<=pWal->hdr.mxFrame );
  42895. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  42896. if( rc==SQLITE_OK ){
  42897. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  42898. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  42899. }else if( rc==SQLITE_BUSY ){
  42900. mxSafeFrame = y;
  42901. xBusy = 0;
  42902. }else{
  42903. goto walcheckpoint_out;
  42904. }
  42905. }
  42906. }
  42907. if( pInfo->nBackfill<mxSafeFrame
  42908. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  42909. ){
  42910. i64 nSize; /* Current size of database file */
  42911. u32 nBackfill = pInfo->nBackfill;
  42912. /* Sync the WAL to disk */
  42913. if( sync_flags ){
  42914. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  42915. }
  42916. /* If the database file may grow as a result of this checkpoint, hint
  42917. ** about the eventual size of the db file to the VFS layer.
  42918. */
  42919. if( rc==SQLITE_OK ){
  42920. i64 nReq = ((i64)mxPage * szPage);
  42921. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  42922. if( rc==SQLITE_OK && nSize<nReq ){
  42923. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  42924. }
  42925. }
  42926. /* Iterate through the contents of the WAL, copying data to the db file. */
  42927. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  42928. i64 iOffset;
  42929. assert( walFramePgno(pWal, iFrame)==iDbpage );
  42930. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  42931. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  42932. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  42933. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  42934. if( rc!=SQLITE_OK ) break;
  42935. iOffset = (iDbpage-1)*(i64)szPage;
  42936. testcase( IS_BIG_INT(iOffset) );
  42937. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  42938. if( rc!=SQLITE_OK ) break;
  42939. }
  42940. /* If work was actually accomplished... */
  42941. if( rc==SQLITE_OK ){
  42942. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  42943. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  42944. testcase( IS_BIG_INT(szDb) );
  42945. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  42946. if( rc==SQLITE_OK && sync_flags ){
  42947. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  42948. }
  42949. }
  42950. if( rc==SQLITE_OK ){
  42951. pInfo->nBackfill = mxSafeFrame;
  42952. }
  42953. }
  42954. /* Release the reader lock held while backfilling */
  42955. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  42956. }
  42957. if( rc==SQLITE_BUSY ){
  42958. /* Reset the return code so as not to report a checkpoint failure
  42959. ** just because there are active readers. */
  42960. rc = SQLITE_OK;
  42961. }
  42962. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  42963. ** file has been copied into the database file, then block until all
  42964. ** readers have finished using the wal file. This ensures that the next
  42965. ** process to write to the database restarts the wal file.
  42966. */
  42967. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  42968. assert( pWal->writeLock );
  42969. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  42970. rc = SQLITE_BUSY;
  42971. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  42972. assert( mxSafeFrame==pWal->hdr.mxFrame );
  42973. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  42974. if( rc==SQLITE_OK ){
  42975. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  42976. }
  42977. }
  42978. }
  42979. walcheckpoint_out:
  42980. walIteratorFree(pIter);
  42981. return rc;
  42982. }
  42983. /*
  42984. ** If the WAL file is currently larger than nMax bytes in size, truncate
  42985. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  42986. */
  42987. static void walLimitSize(Wal *pWal, i64 nMax){
  42988. i64 sz;
  42989. int rx;
  42990. sqlite3BeginBenignMalloc();
  42991. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  42992. if( rx==SQLITE_OK && (sz > nMax ) ){
  42993. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  42994. }
  42995. sqlite3EndBenignMalloc();
  42996. if( rx ){
  42997. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  42998. }
  42999. }
  43000. /*
  43001. ** Close a connection to a log file.
  43002. */
  43003. SQLITE_PRIVATE int sqlite3WalClose(
  43004. Wal *pWal, /* Wal to close */
  43005. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  43006. int nBuf,
  43007. u8 *zBuf /* Buffer of at least nBuf bytes */
  43008. ){
  43009. int rc = SQLITE_OK;
  43010. if( pWal ){
  43011. int isDelete = 0; /* True to unlink wal and wal-index files */
  43012. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  43013. ** ordinary, rollback-mode locking methods, this guarantees that the
  43014. ** connection associated with this log file is the only connection to
  43015. ** the database. In this case checkpoint the database and unlink both
  43016. ** the wal and wal-index files.
  43017. **
  43018. ** The EXCLUSIVE lock is not released before returning.
  43019. */
  43020. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  43021. if( rc==SQLITE_OK ){
  43022. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  43023. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  43024. }
  43025. rc = sqlite3WalCheckpoint(
  43026. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  43027. );
  43028. if( rc==SQLITE_OK ){
  43029. int bPersist = -1;
  43030. sqlite3OsFileControlHint(
  43031. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  43032. );
  43033. if( bPersist!=1 ){
  43034. /* Try to delete the WAL file if the checkpoint completed and
  43035. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  43036. ** mode (!bPersist) */
  43037. isDelete = 1;
  43038. }else if( pWal->mxWalSize>=0 ){
  43039. /* Try to truncate the WAL file to zero bytes if the checkpoint
  43040. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  43041. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  43042. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  43043. ** to zero bytes as truncating to the journal_size_limit might
  43044. ** leave a corrupt WAL file on disk. */
  43045. walLimitSize(pWal, 0);
  43046. }
  43047. }
  43048. }
  43049. walIndexClose(pWal, isDelete);
  43050. sqlite3OsClose(pWal->pWalFd);
  43051. if( isDelete ){
  43052. sqlite3BeginBenignMalloc();
  43053. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  43054. sqlite3EndBenignMalloc();
  43055. }
  43056. WALTRACE(("WAL%p: closed\n", pWal));
  43057. sqlite3_free((void *)pWal->apWiData);
  43058. sqlite3_free(pWal);
  43059. }
  43060. return rc;
  43061. }
  43062. /*
  43063. ** Try to read the wal-index header. Return 0 on success and 1 if
  43064. ** there is a problem.
  43065. **
  43066. ** The wal-index is in shared memory. Another thread or process might
  43067. ** be writing the header at the same time this procedure is trying to
  43068. ** read it, which might result in inconsistency. A dirty read is detected
  43069. ** by verifying that both copies of the header are the same and also by
  43070. ** a checksum on the header.
  43071. **
  43072. ** If and only if the read is consistent and the header is different from
  43073. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  43074. ** and *pChanged is set to 1.
  43075. **
  43076. ** If the checksum cannot be verified return non-zero. If the header
  43077. ** is read successfully and the checksum verified, return zero.
  43078. */
  43079. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  43080. u32 aCksum[2]; /* Checksum on the header content */
  43081. WalIndexHdr h1, h2; /* Two copies of the header content */
  43082. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  43083. /* The first page of the wal-index must be mapped at this point. */
  43084. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  43085. /* Read the header. This might happen concurrently with a write to the
  43086. ** same area of shared memory on a different CPU in a SMP,
  43087. ** meaning it is possible that an inconsistent snapshot is read
  43088. ** from the file. If this happens, return non-zero.
  43089. **
  43090. ** There are two copies of the header at the beginning of the wal-index.
  43091. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  43092. ** Memory barriers are used to prevent the compiler or the hardware from
  43093. ** reordering the reads and writes.
  43094. */
  43095. aHdr = walIndexHdr(pWal);
  43096. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  43097. walShmBarrier(pWal);
  43098. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  43099. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  43100. return 1; /* Dirty read */
  43101. }
  43102. if( h1.isInit==0 ){
  43103. return 1; /* Malformed header - probably all zeros */
  43104. }
  43105. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  43106. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  43107. return 1; /* Checksum does not match */
  43108. }
  43109. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  43110. *pChanged = 1;
  43111. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  43112. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  43113. testcase( pWal->szPage<=32768 );
  43114. testcase( pWal->szPage>=65536 );
  43115. }
  43116. /* The header was successfully read. Return zero. */
  43117. return 0;
  43118. }
  43119. /*
  43120. ** Read the wal-index header from the wal-index and into pWal->hdr.
  43121. ** If the wal-header appears to be corrupt, try to reconstruct the
  43122. ** wal-index from the WAL before returning.
  43123. **
  43124. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  43125. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  43126. ** to 0.
  43127. **
  43128. ** If the wal-index header is successfully read, return SQLITE_OK.
  43129. ** Otherwise an SQLite error code.
  43130. */
  43131. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  43132. int rc; /* Return code */
  43133. int badHdr; /* True if a header read failed */
  43134. volatile u32 *page0; /* Chunk of wal-index containing header */
  43135. /* Ensure that page 0 of the wal-index (the page that contains the
  43136. ** wal-index header) is mapped. Return early if an error occurs here.
  43137. */
  43138. assert( pChanged );
  43139. rc = walIndexPage(pWal, 0, &page0);
  43140. if( rc!=SQLITE_OK ){
  43141. return rc;
  43142. };
  43143. assert( page0 || pWal->writeLock==0 );
  43144. /* If the first page of the wal-index has been mapped, try to read the
  43145. ** wal-index header immediately, without holding any lock. This usually
  43146. ** works, but may fail if the wal-index header is corrupt or currently
  43147. ** being modified by another thread or process.
  43148. */
  43149. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  43150. /* If the first attempt failed, it might have been due to a race
  43151. ** with a writer. So get a WRITE lock and try again.
  43152. */
  43153. assert( badHdr==0 || pWal->writeLock==0 );
  43154. if( badHdr ){
  43155. if( pWal->readOnly & WAL_SHM_RDONLY ){
  43156. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  43157. walUnlockShared(pWal, WAL_WRITE_LOCK);
  43158. rc = SQLITE_READONLY_RECOVERY;
  43159. }
  43160. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  43161. pWal->writeLock = 1;
  43162. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  43163. badHdr = walIndexTryHdr(pWal, pChanged);
  43164. if( badHdr ){
  43165. /* If the wal-index header is still malformed even while holding
  43166. ** a WRITE lock, it can only mean that the header is corrupted and
  43167. ** needs to be reconstructed. So run recovery to do exactly that.
  43168. */
  43169. rc = walIndexRecover(pWal);
  43170. *pChanged = 1;
  43171. }
  43172. }
  43173. pWal->writeLock = 0;
  43174. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  43175. }
  43176. }
  43177. /* If the header is read successfully, check the version number to make
  43178. ** sure the wal-index was not constructed with some future format that
  43179. ** this version of SQLite cannot understand.
  43180. */
  43181. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  43182. rc = SQLITE_CANTOPEN_BKPT;
  43183. }
  43184. return rc;
  43185. }
  43186. /*
  43187. ** This is the value that walTryBeginRead returns when it needs to
  43188. ** be retried.
  43189. */
  43190. #define WAL_RETRY (-1)
  43191. /*
  43192. ** Attempt to start a read transaction. This might fail due to a race or
  43193. ** other transient condition. When that happens, it returns WAL_RETRY to
  43194. ** indicate to the caller that it is safe to retry immediately.
  43195. **
  43196. ** On success return SQLITE_OK. On a permanent failure (such an
  43197. ** I/O error or an SQLITE_BUSY because another process is running
  43198. ** recovery) return a positive error code.
  43199. **
  43200. ** The useWal parameter is true to force the use of the WAL and disable
  43201. ** the case where the WAL is bypassed because it has been completely
  43202. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  43203. ** to make a copy of the wal-index header into pWal->hdr. If the
  43204. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  43205. ** to the caller that the local paget cache is obsolete and needs to be
  43206. ** flushed.) When useWal==1, the wal-index header is assumed to already
  43207. ** be loaded and the pChanged parameter is unused.
  43208. **
  43209. ** The caller must set the cnt parameter to the number of prior calls to
  43210. ** this routine during the current read attempt that returned WAL_RETRY.
  43211. ** This routine will start taking more aggressive measures to clear the
  43212. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  43213. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  43214. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  43215. ** and is not honoring the locking protocol. There is a vanishingly small
  43216. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  43217. ** bad luck when there is lots of contention for the wal-index, but that
  43218. ** possibility is so small that it can be safely neglected, we believe.
  43219. **
  43220. ** On success, this routine obtains a read lock on
  43221. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  43222. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  43223. ** that means the Wal does not hold any read lock. The reader must not
  43224. ** access any database page that is modified by a WAL frame up to and
  43225. ** including frame number aReadMark[pWal->readLock]. The reader will
  43226. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  43227. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  43228. ** completely and get all content directly from the database file.
  43229. ** If the useWal parameter is 1 then the WAL will never be ignored and
  43230. ** this routine will always set pWal->readLock>0 on success.
  43231. ** When the read transaction is completed, the caller must release the
  43232. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  43233. **
  43234. ** This routine uses the nBackfill and aReadMark[] fields of the header
  43235. ** to select a particular WAL_READ_LOCK() that strives to let the
  43236. ** checkpoint process do as much work as possible. This routine might
  43237. ** update values of the aReadMark[] array in the header, but if it does
  43238. ** so it takes care to hold an exclusive lock on the corresponding
  43239. ** WAL_READ_LOCK() while changing values.
  43240. */
  43241. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  43242. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  43243. u32 mxReadMark; /* Largest aReadMark[] value */
  43244. int mxI; /* Index of largest aReadMark[] value */
  43245. int i; /* Loop counter */
  43246. int rc = SQLITE_OK; /* Return code */
  43247. assert( pWal->readLock<0 ); /* Not currently locked */
  43248. /* Take steps to avoid spinning forever if there is a protocol error.
  43249. **
  43250. ** Circumstances that cause a RETRY should only last for the briefest
  43251. ** instances of time. No I/O or other system calls are done while the
  43252. ** locks are held, so the locks should not be held for very long. But
  43253. ** if we are unlucky, another process that is holding a lock might get
  43254. ** paged out or take a page-fault that is time-consuming to resolve,
  43255. ** during the few nanoseconds that it is holding the lock. In that case,
  43256. ** it might take longer than normal for the lock to free.
  43257. **
  43258. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  43259. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  43260. ** is more of a scheduler yield than an actual delay. But on the 10th
  43261. ** an subsequent retries, the delays start becoming longer and longer,
  43262. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  43263. ** The total delay time before giving up is less than 1 second.
  43264. */
  43265. if( cnt>5 ){
  43266. int nDelay = 1; /* Pause time in microseconds */
  43267. if( cnt>100 ){
  43268. VVA_ONLY( pWal->lockError = 1; )
  43269. return SQLITE_PROTOCOL;
  43270. }
  43271. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  43272. sqlite3OsSleep(pWal->pVfs, nDelay);
  43273. }
  43274. if( !useWal ){
  43275. rc = walIndexReadHdr(pWal, pChanged);
  43276. if( rc==SQLITE_BUSY ){
  43277. /* If there is not a recovery running in another thread or process
  43278. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  43279. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  43280. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  43281. ** would be technically correct. But the race is benign since with
  43282. ** WAL_RETRY this routine will be called again and will probably be
  43283. ** right on the second iteration.
  43284. */
  43285. if( pWal->apWiData[0]==0 ){
  43286. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  43287. ** We assume this is a transient condition, so return WAL_RETRY. The
  43288. ** xShmMap() implementation used by the default unix and win32 VFS
  43289. ** modules may return SQLITE_BUSY due to a race condition in the
  43290. ** code that determines whether or not the shared-memory region
  43291. ** must be zeroed before the requested page is returned.
  43292. */
  43293. rc = WAL_RETRY;
  43294. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  43295. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  43296. rc = WAL_RETRY;
  43297. }else if( rc==SQLITE_BUSY ){
  43298. rc = SQLITE_BUSY_RECOVERY;
  43299. }
  43300. }
  43301. if( rc!=SQLITE_OK ){
  43302. return rc;
  43303. }
  43304. }
  43305. pInfo = walCkptInfo(pWal);
  43306. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  43307. /* The WAL has been completely backfilled (or it is empty).
  43308. ** and can be safely ignored.
  43309. */
  43310. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  43311. walShmBarrier(pWal);
  43312. if( rc==SQLITE_OK ){
  43313. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  43314. /* It is not safe to allow the reader to continue here if frames
  43315. ** may have been appended to the log before READ_LOCK(0) was obtained.
  43316. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  43317. ** which implies that the database file contains a trustworthy
  43318. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  43319. ** happening, this is usually correct.
  43320. **
  43321. ** However, if frames have been appended to the log (or if the log
  43322. ** is wrapped and written for that matter) before the READ_LOCK(0)
  43323. ** is obtained, that is not necessarily true. A checkpointer may
  43324. ** have started to backfill the appended frames but crashed before
  43325. ** it finished. Leaving a corrupt image in the database file.
  43326. */
  43327. walUnlockShared(pWal, WAL_READ_LOCK(0));
  43328. return WAL_RETRY;
  43329. }
  43330. pWal->readLock = 0;
  43331. return SQLITE_OK;
  43332. }else if( rc!=SQLITE_BUSY ){
  43333. return rc;
  43334. }
  43335. }
  43336. /* If we get this far, it means that the reader will want to use
  43337. ** the WAL to get at content from recent commits. The job now is
  43338. ** to select one of the aReadMark[] entries that is closest to
  43339. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  43340. */
  43341. mxReadMark = 0;
  43342. mxI = 0;
  43343. for(i=1; i<WAL_NREADER; i++){
  43344. u32 thisMark = pInfo->aReadMark[i];
  43345. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  43346. assert( thisMark!=READMARK_NOT_USED );
  43347. mxReadMark = thisMark;
  43348. mxI = i;
  43349. }
  43350. }
  43351. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  43352. {
  43353. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  43354. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  43355. ){
  43356. for(i=1; i<WAL_NREADER; i++){
  43357. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  43358. if( rc==SQLITE_OK ){
  43359. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  43360. mxI = i;
  43361. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  43362. break;
  43363. }else if( rc!=SQLITE_BUSY ){
  43364. return rc;
  43365. }
  43366. }
  43367. }
  43368. if( mxI==0 ){
  43369. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  43370. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  43371. }
  43372. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  43373. if( rc ){
  43374. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  43375. }
  43376. /* Now that the read-lock has been obtained, check that neither the
  43377. ** value in the aReadMark[] array or the contents of the wal-index
  43378. ** header have changed.
  43379. **
  43380. ** It is necessary to check that the wal-index header did not change
  43381. ** between the time it was read and when the shared-lock was obtained
  43382. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  43383. ** that the log file may have been wrapped by a writer, or that frames
  43384. ** that occur later in the log than pWal->hdr.mxFrame may have been
  43385. ** copied into the database by a checkpointer. If either of these things
  43386. ** happened, then reading the database with the current value of
  43387. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  43388. ** instead.
  43389. **
  43390. ** This does not guarantee that the copy of the wal-index header is up to
  43391. ** date before proceeding. That would not be possible without somehow
  43392. ** blocking writers. It only guarantees that a dangerous checkpoint or
  43393. ** log-wrap (either of which would require an exclusive lock on
  43394. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  43395. */
  43396. walShmBarrier(pWal);
  43397. if( pInfo->aReadMark[mxI]!=mxReadMark
  43398. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  43399. ){
  43400. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  43401. return WAL_RETRY;
  43402. }else{
  43403. assert( mxReadMark<=pWal->hdr.mxFrame );
  43404. pWal->readLock = (i16)mxI;
  43405. }
  43406. }
  43407. return rc;
  43408. }
  43409. /*
  43410. ** Begin a read transaction on the database.
  43411. **
  43412. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  43413. ** it takes a snapshot of the state of the WAL and wal-index for the current
  43414. ** instant in time. The current thread will continue to use this snapshot.
  43415. ** Other threads might append new content to the WAL and wal-index but
  43416. ** that extra content is ignored by the current thread.
  43417. **
  43418. ** If the database contents have changes since the previous read
  43419. ** transaction, then *pChanged is set to 1 before returning. The
  43420. ** Pager layer will use this to know that is cache is stale and
  43421. ** needs to be flushed.
  43422. */
  43423. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  43424. int rc; /* Return code */
  43425. int cnt = 0; /* Number of TryBeginRead attempts */
  43426. do{
  43427. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  43428. }while( rc==WAL_RETRY );
  43429. testcase( (rc&0xff)==SQLITE_BUSY );
  43430. testcase( (rc&0xff)==SQLITE_IOERR );
  43431. testcase( rc==SQLITE_PROTOCOL );
  43432. testcase( rc==SQLITE_OK );
  43433. return rc;
  43434. }
  43435. /*
  43436. ** Finish with a read transaction. All this does is release the
  43437. ** read-lock.
  43438. */
  43439. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  43440. sqlite3WalEndWriteTransaction(pWal);
  43441. if( pWal->readLock>=0 ){
  43442. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  43443. pWal->readLock = -1;
  43444. }
  43445. }
  43446. /*
  43447. ** Read a page from the WAL, if it is present in the WAL and if the
  43448. ** current read transaction is configured to use the WAL.
  43449. **
  43450. ** The *pInWal is set to 1 if the requested page is in the WAL and
  43451. ** has been loaded. Or *pInWal is set to 0 if the page was not in
  43452. ** the WAL and needs to be read out of the database.
  43453. */
  43454. SQLITE_PRIVATE int sqlite3WalRead(
  43455. Wal *pWal, /* WAL handle */
  43456. Pgno pgno, /* Database page number to read data for */
  43457. int *pInWal, /* OUT: True if data is read from WAL */
  43458. int nOut, /* Size of buffer pOut in bytes */
  43459. u8 *pOut /* Buffer to write page data to */
  43460. ){
  43461. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  43462. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  43463. int iHash; /* Used to loop through N hash tables */
  43464. /* This routine is only be called from within a read transaction. */
  43465. assert( pWal->readLock>=0 || pWal->lockError );
  43466. /* If the "last page" field of the wal-index header snapshot is 0, then
  43467. ** no data will be read from the wal under any circumstances. Return early
  43468. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  43469. ** then the WAL is ignored by the reader so return early, as if the
  43470. ** WAL were empty.
  43471. */
  43472. if( iLast==0 || pWal->readLock==0 ){
  43473. *pInWal = 0;
  43474. return SQLITE_OK;
  43475. }
  43476. /* Search the hash table or tables for an entry matching page number
  43477. ** pgno. Each iteration of the following for() loop searches one
  43478. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  43479. **
  43480. ** This code might run concurrently to the code in walIndexAppend()
  43481. ** that adds entries to the wal-index (and possibly to this hash
  43482. ** table). This means the value just read from the hash
  43483. ** slot (aHash[iKey]) may have been added before or after the
  43484. ** current read transaction was opened. Values added after the
  43485. ** read transaction was opened may have been written incorrectly -
  43486. ** i.e. these slots may contain garbage data. However, we assume
  43487. ** that any slots written before the current read transaction was
  43488. ** opened remain unmodified.
  43489. **
  43490. ** For the reasons above, the if(...) condition featured in the inner
  43491. ** loop of the following block is more stringent that would be required
  43492. ** if we had exclusive access to the hash-table:
  43493. **
  43494. ** (aPgno[iFrame]==pgno):
  43495. ** This condition filters out normal hash-table collisions.
  43496. **
  43497. ** (iFrame<=iLast):
  43498. ** This condition filters out entries that were added to the hash
  43499. ** table after the current read-transaction had started.
  43500. */
  43501. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  43502. volatile ht_slot *aHash; /* Pointer to hash table */
  43503. volatile u32 *aPgno; /* Pointer to array of page numbers */
  43504. u32 iZero; /* Frame number corresponding to aPgno[0] */
  43505. int iKey; /* Hash slot index */
  43506. int nCollide; /* Number of hash collisions remaining */
  43507. int rc; /* Error code */
  43508. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  43509. if( rc!=SQLITE_OK ){
  43510. return rc;
  43511. }
  43512. nCollide = HASHTABLE_NSLOT;
  43513. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  43514. u32 iFrame = aHash[iKey] + iZero;
  43515. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  43516. /* assert( iFrame>iRead ); -- not true if there is corruption */
  43517. iRead = iFrame;
  43518. }
  43519. if( (nCollide--)==0 ){
  43520. return SQLITE_CORRUPT_BKPT;
  43521. }
  43522. }
  43523. }
  43524. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  43525. /* If expensive assert() statements are available, do a linear search
  43526. ** of the wal-index file content. Make sure the results agree with the
  43527. ** result obtained using the hash indexes above. */
  43528. {
  43529. u32 iRead2 = 0;
  43530. u32 iTest;
  43531. for(iTest=iLast; iTest>0; iTest--){
  43532. if( walFramePgno(pWal, iTest)==pgno ){
  43533. iRead2 = iTest;
  43534. break;
  43535. }
  43536. }
  43537. assert( iRead==iRead2 );
  43538. }
  43539. #endif
  43540. /* If iRead is non-zero, then it is the log frame number that contains the
  43541. ** required page. Read and return data from the log file.
  43542. */
  43543. if( iRead ){
  43544. int sz;
  43545. i64 iOffset;
  43546. sz = pWal->hdr.szPage;
  43547. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  43548. testcase( sz<=32768 );
  43549. testcase( sz>=65536 );
  43550. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  43551. *pInWal = 1;
  43552. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  43553. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  43554. }
  43555. *pInWal = 0;
  43556. return SQLITE_OK;
  43557. }
  43558. /*
  43559. ** Return the size of the database in pages (or zero, if unknown).
  43560. */
  43561. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  43562. if( pWal && ALWAYS(pWal->readLock>=0) ){
  43563. return pWal->hdr.nPage;
  43564. }
  43565. return 0;
  43566. }
  43567. /*
  43568. ** This function starts a write transaction on the WAL.
  43569. **
  43570. ** A read transaction must have already been started by a prior call
  43571. ** to sqlite3WalBeginReadTransaction().
  43572. **
  43573. ** If another thread or process has written into the database since
  43574. ** the read transaction was started, then it is not possible for this
  43575. ** thread to write as doing so would cause a fork. So this routine
  43576. ** returns SQLITE_BUSY in that case and no write transaction is started.
  43577. **
  43578. ** There can only be a single writer active at a time.
  43579. */
  43580. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  43581. int rc;
  43582. /* Cannot start a write transaction without first holding a read
  43583. ** transaction. */
  43584. assert( pWal->readLock>=0 );
  43585. if( pWal->readOnly ){
  43586. return SQLITE_READONLY;
  43587. }
  43588. /* Only one writer allowed at a time. Get the write lock. Return
  43589. ** SQLITE_BUSY if unable.
  43590. */
  43591. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  43592. if( rc ){
  43593. return rc;
  43594. }
  43595. pWal->writeLock = 1;
  43596. /* If another connection has written to the database file since the
  43597. ** time the read transaction on this connection was started, then
  43598. ** the write is disallowed.
  43599. */
  43600. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  43601. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  43602. pWal->writeLock = 0;
  43603. rc = SQLITE_BUSY;
  43604. }
  43605. return rc;
  43606. }
  43607. /*
  43608. ** End a write transaction. The commit has already been done. This
  43609. ** routine merely releases the lock.
  43610. */
  43611. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  43612. if( pWal->writeLock ){
  43613. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  43614. pWal->writeLock = 0;
  43615. pWal->truncateOnCommit = 0;
  43616. }
  43617. return SQLITE_OK;
  43618. }
  43619. /*
  43620. ** If any data has been written (but not committed) to the log file, this
  43621. ** function moves the write-pointer back to the start of the transaction.
  43622. **
  43623. ** Additionally, the callback function is invoked for each frame written
  43624. ** to the WAL since the start of the transaction. If the callback returns
  43625. ** other than SQLITE_OK, it is not invoked again and the error code is
  43626. ** returned to the caller.
  43627. **
  43628. ** Otherwise, if the callback function does not return an error, this
  43629. ** function returns SQLITE_OK.
  43630. */
  43631. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  43632. int rc = SQLITE_OK;
  43633. if( ALWAYS(pWal->writeLock) ){
  43634. Pgno iMax = pWal->hdr.mxFrame;
  43635. Pgno iFrame;
  43636. /* Restore the clients cache of the wal-index header to the state it
  43637. ** was in before the client began writing to the database.
  43638. */
  43639. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  43640. for(iFrame=pWal->hdr.mxFrame+1;
  43641. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  43642. iFrame++
  43643. ){
  43644. /* This call cannot fail. Unless the page for which the page number
  43645. ** is passed as the second argument is (a) in the cache and
  43646. ** (b) has an outstanding reference, then xUndo is either a no-op
  43647. ** (if (a) is false) or simply expels the page from the cache (if (b)
  43648. ** is false).
  43649. **
  43650. ** If the upper layer is doing a rollback, it is guaranteed that there
  43651. ** are no outstanding references to any page other than page 1. And
  43652. ** page 1 is never written to the log until the transaction is
  43653. ** committed. As a result, the call to xUndo may not fail.
  43654. */
  43655. assert( walFramePgno(pWal, iFrame)!=1 );
  43656. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  43657. }
  43658. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  43659. }
  43660. assert( rc==SQLITE_OK );
  43661. return rc;
  43662. }
  43663. /*
  43664. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  43665. ** values. This function populates the array with values required to
  43666. ** "rollback" the write position of the WAL handle back to the current
  43667. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  43668. */
  43669. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  43670. assert( pWal->writeLock );
  43671. aWalData[0] = pWal->hdr.mxFrame;
  43672. aWalData[1] = pWal->hdr.aFrameCksum[0];
  43673. aWalData[2] = pWal->hdr.aFrameCksum[1];
  43674. aWalData[3] = pWal->nCkpt;
  43675. }
  43676. /*
  43677. ** Move the write position of the WAL back to the point identified by
  43678. ** the values in the aWalData[] array. aWalData must point to an array
  43679. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  43680. ** by a call to WalSavepoint().
  43681. */
  43682. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  43683. int rc = SQLITE_OK;
  43684. assert( pWal->writeLock );
  43685. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  43686. if( aWalData[3]!=pWal->nCkpt ){
  43687. /* This savepoint was opened immediately after the write-transaction
  43688. ** was started. Right after that, the writer decided to wrap around
  43689. ** to the start of the log. Update the savepoint values to match.
  43690. */
  43691. aWalData[0] = 0;
  43692. aWalData[3] = pWal->nCkpt;
  43693. }
  43694. if( aWalData[0]<pWal->hdr.mxFrame ){
  43695. pWal->hdr.mxFrame = aWalData[0];
  43696. pWal->hdr.aFrameCksum[0] = aWalData[1];
  43697. pWal->hdr.aFrameCksum[1] = aWalData[2];
  43698. walCleanupHash(pWal);
  43699. }
  43700. return rc;
  43701. }
  43702. /*
  43703. ** This function is called just before writing a set of frames to the log
  43704. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  43705. ** to the current log file, it is possible to overwrite the start of the
  43706. ** existing log file with the new frames (i.e. "reset" the log). If so,
  43707. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  43708. ** unchanged.
  43709. **
  43710. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  43711. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  43712. ** if an error occurs.
  43713. */
  43714. static int walRestartLog(Wal *pWal){
  43715. int rc = SQLITE_OK;
  43716. int cnt;
  43717. if( pWal->readLock==0 ){
  43718. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  43719. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  43720. if( pInfo->nBackfill>0 ){
  43721. u32 salt1;
  43722. sqlite3_randomness(4, &salt1);
  43723. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  43724. if( rc==SQLITE_OK ){
  43725. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  43726. ** readers are currently using the WAL), then the transactions
  43727. ** frames will overwrite the start of the existing log. Update the
  43728. ** wal-index header to reflect this.
  43729. **
  43730. ** In theory it would be Ok to update the cache of the header only
  43731. ** at this point. But updating the actual wal-index header is also
  43732. ** safe and means there is no special case for sqlite3WalUndo()
  43733. ** to handle if this transaction is rolled back.
  43734. */
  43735. int i; /* Loop counter */
  43736. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  43737. pWal->nCkpt++;
  43738. pWal->hdr.mxFrame = 0;
  43739. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  43740. aSalt[1] = salt1;
  43741. walIndexWriteHdr(pWal);
  43742. pInfo->nBackfill = 0;
  43743. pInfo->aReadMark[1] = 0;
  43744. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  43745. assert( pInfo->aReadMark[0]==0 );
  43746. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  43747. }else if( rc!=SQLITE_BUSY ){
  43748. return rc;
  43749. }
  43750. }
  43751. walUnlockShared(pWal, WAL_READ_LOCK(0));
  43752. pWal->readLock = -1;
  43753. cnt = 0;
  43754. do{
  43755. int notUsed;
  43756. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  43757. }while( rc==WAL_RETRY );
  43758. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  43759. testcase( (rc&0xff)==SQLITE_IOERR );
  43760. testcase( rc==SQLITE_PROTOCOL );
  43761. testcase( rc==SQLITE_OK );
  43762. }
  43763. return rc;
  43764. }
  43765. /*
  43766. ** Information about the current state of the WAL file and where
  43767. ** the next fsync should occur - passed from sqlite3WalFrames() into
  43768. ** walWriteToLog().
  43769. */
  43770. typedef struct WalWriter {
  43771. Wal *pWal; /* The complete WAL information */
  43772. sqlite3_file *pFd; /* The WAL file to which we write */
  43773. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  43774. int syncFlags; /* Flags for the fsync */
  43775. int szPage; /* Size of one page */
  43776. } WalWriter;
  43777. /*
  43778. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  43779. ** Do a sync when crossing the p->iSyncPoint boundary.
  43780. **
  43781. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  43782. ** first write the part before iSyncPoint, then sync, then write the
  43783. ** rest.
  43784. */
  43785. static int walWriteToLog(
  43786. WalWriter *p, /* WAL to write to */
  43787. void *pContent, /* Content to be written */
  43788. int iAmt, /* Number of bytes to write */
  43789. sqlite3_int64 iOffset /* Start writing at this offset */
  43790. ){
  43791. int rc;
  43792. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  43793. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  43794. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  43795. if( rc ) return rc;
  43796. iOffset += iFirstAmt;
  43797. iAmt -= iFirstAmt;
  43798. pContent = (void*)(iFirstAmt + (char*)pContent);
  43799. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  43800. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  43801. if( iAmt==0 || rc ) return rc;
  43802. }
  43803. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  43804. return rc;
  43805. }
  43806. /*
  43807. ** Write out a single frame of the WAL
  43808. */
  43809. static int walWriteOneFrame(
  43810. WalWriter *p, /* Where to write the frame */
  43811. PgHdr *pPage, /* The page of the frame to be written */
  43812. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  43813. sqlite3_int64 iOffset /* Byte offset at which to write */
  43814. ){
  43815. int rc; /* Result code from subfunctions */
  43816. void *pData; /* Data actually written */
  43817. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  43818. #if defined(SQLITE_HAS_CODEC)
  43819. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  43820. #else
  43821. pData = pPage->pData;
  43822. #endif
  43823. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  43824. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  43825. if( rc ) return rc;
  43826. /* Write the page data */
  43827. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  43828. return rc;
  43829. }
  43830. /*
  43831. ** Write a set of frames to the log. The caller must hold the write-lock
  43832. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  43833. */
  43834. SQLITE_PRIVATE int sqlite3WalFrames(
  43835. Wal *pWal, /* Wal handle to write to */
  43836. int szPage, /* Database page-size in bytes */
  43837. PgHdr *pList, /* List of dirty pages to write */
  43838. Pgno nTruncate, /* Database size after this commit */
  43839. int isCommit, /* True if this is a commit */
  43840. int sync_flags /* Flags to pass to OsSync() (or 0) */
  43841. ){
  43842. int rc; /* Used to catch return codes */
  43843. u32 iFrame; /* Next frame address */
  43844. PgHdr *p; /* Iterator to run through pList with. */
  43845. PgHdr *pLast = 0; /* Last frame in list */
  43846. int nExtra = 0; /* Number of extra copies of last page */
  43847. int szFrame; /* The size of a single frame */
  43848. i64 iOffset; /* Next byte to write in WAL file */
  43849. WalWriter w; /* The writer */
  43850. assert( pList );
  43851. assert( pWal->writeLock );
  43852. /* If this frame set completes a transaction, then nTruncate>0. If
  43853. ** nTruncate==0 then this frame set does not complete the transaction. */
  43854. assert( (isCommit!=0)==(nTruncate!=0) );
  43855. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  43856. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  43857. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  43858. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  43859. }
  43860. #endif
  43861. /* See if it is possible to write these frames into the start of the
  43862. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  43863. */
  43864. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  43865. return rc;
  43866. }
  43867. /* If this is the first frame written into the log, write the WAL
  43868. ** header to the start of the WAL file. See comments at the top of
  43869. ** this source file for a description of the WAL header format.
  43870. */
  43871. iFrame = pWal->hdr.mxFrame;
  43872. if( iFrame==0 ){
  43873. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  43874. u32 aCksum[2]; /* Checksum for wal-header */
  43875. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  43876. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  43877. sqlite3Put4byte(&aWalHdr[8], szPage);
  43878. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  43879. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  43880. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  43881. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  43882. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  43883. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  43884. pWal->szPage = szPage;
  43885. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  43886. pWal->hdr.aFrameCksum[0] = aCksum[0];
  43887. pWal->hdr.aFrameCksum[1] = aCksum[1];
  43888. pWal->truncateOnCommit = 1;
  43889. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  43890. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  43891. if( rc!=SQLITE_OK ){
  43892. return rc;
  43893. }
  43894. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  43895. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  43896. ** an out-of-order write following a WAL restart could result in
  43897. ** database corruption. See the ticket:
  43898. **
  43899. ** http://localhost:591/sqlite/info/ff5be73dee
  43900. */
  43901. if( pWal->syncHeader && sync_flags ){
  43902. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  43903. if( rc ) return rc;
  43904. }
  43905. }
  43906. assert( (int)pWal->szPage==szPage );
  43907. /* Setup information needed to write frames into the WAL */
  43908. w.pWal = pWal;
  43909. w.pFd = pWal->pWalFd;
  43910. w.iSyncPoint = 0;
  43911. w.syncFlags = sync_flags;
  43912. w.szPage = szPage;
  43913. iOffset = walFrameOffset(iFrame+1, szPage);
  43914. szFrame = szPage + WAL_FRAME_HDRSIZE;
  43915. /* Write all frames into the log file exactly once */
  43916. for(p=pList; p; p=p->pDirty){
  43917. int nDbSize; /* 0 normally. Positive == commit flag */
  43918. iFrame++;
  43919. assert( iOffset==walFrameOffset(iFrame, szPage) );
  43920. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  43921. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  43922. if( rc ) return rc;
  43923. pLast = p;
  43924. iOffset += szFrame;
  43925. }
  43926. /* If this is the end of a transaction, then we might need to pad
  43927. ** the transaction and/or sync the WAL file.
  43928. **
  43929. ** Padding and syncing only occur if this set of frames complete a
  43930. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  43931. ** or synchonous==OFF, then no padding or syncing are needed.
  43932. **
  43933. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  43934. ** needed and only the sync is done. If padding is needed, then the
  43935. ** final frame is repeated (with its commit mark) until the next sector
  43936. ** boundary is crossed. Only the part of the WAL prior to the last
  43937. ** sector boundary is synced; the part of the last frame that extends
  43938. ** past the sector boundary is written after the sync.
  43939. */
  43940. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  43941. if( pWal->padToSectorBoundary ){
  43942. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  43943. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  43944. while( iOffset<w.iSyncPoint ){
  43945. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  43946. if( rc ) return rc;
  43947. iOffset += szFrame;
  43948. nExtra++;
  43949. }
  43950. }else{
  43951. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  43952. }
  43953. }
  43954. /* If this frame set completes the first transaction in the WAL and
  43955. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  43956. ** journal size limit, if possible.
  43957. */
  43958. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  43959. i64 sz = pWal->mxWalSize;
  43960. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  43961. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  43962. }
  43963. walLimitSize(pWal, sz);
  43964. pWal->truncateOnCommit = 0;
  43965. }
  43966. /* Append data to the wal-index. It is not necessary to lock the
  43967. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  43968. ** guarantees that there are no other writers, and no data that may
  43969. ** be in use by existing readers is being overwritten.
  43970. */
  43971. iFrame = pWal->hdr.mxFrame;
  43972. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  43973. iFrame++;
  43974. rc = walIndexAppend(pWal, iFrame, p->pgno);
  43975. }
  43976. while( rc==SQLITE_OK && nExtra>0 ){
  43977. iFrame++;
  43978. nExtra--;
  43979. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  43980. }
  43981. if( rc==SQLITE_OK ){
  43982. /* Update the private copy of the header. */
  43983. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  43984. testcase( szPage<=32768 );
  43985. testcase( szPage>=65536 );
  43986. pWal->hdr.mxFrame = iFrame;
  43987. if( isCommit ){
  43988. pWal->hdr.iChange++;
  43989. pWal->hdr.nPage = nTruncate;
  43990. }
  43991. /* If this is a commit, update the wal-index header too. */
  43992. if( isCommit ){
  43993. walIndexWriteHdr(pWal);
  43994. pWal->iCallback = iFrame;
  43995. }
  43996. }
  43997. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  43998. return rc;
  43999. }
  44000. /*
  44001. ** This routine is called to implement sqlite3_wal_checkpoint() and
  44002. ** related interfaces.
  44003. **
  44004. ** Obtain a CHECKPOINT lock and then backfill as much information as
  44005. ** we can from WAL into the database.
  44006. **
  44007. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  44008. ** callback. In this case this function runs a blocking checkpoint.
  44009. */
  44010. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  44011. Wal *pWal, /* Wal connection */
  44012. int eMode, /* PASSIVE, FULL or RESTART */
  44013. int (*xBusy)(void*), /* Function to call when busy */
  44014. void *pBusyArg, /* Context argument for xBusyHandler */
  44015. int sync_flags, /* Flags to sync db file with (or 0) */
  44016. int nBuf, /* Size of temporary buffer */
  44017. u8 *zBuf, /* Temporary buffer to use */
  44018. int *pnLog, /* OUT: Number of frames in WAL */
  44019. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  44020. ){
  44021. int rc; /* Return code */
  44022. int isChanged = 0; /* True if a new wal-index header is loaded */
  44023. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  44024. assert( pWal->ckptLock==0 );
  44025. assert( pWal->writeLock==0 );
  44026. if( pWal->readOnly ) return SQLITE_READONLY;
  44027. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  44028. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  44029. if( rc ){
  44030. /* Usually this is SQLITE_BUSY meaning that another thread or process
  44031. ** is already running a checkpoint, or maybe a recovery. But it might
  44032. ** also be SQLITE_IOERR. */
  44033. return rc;
  44034. }
  44035. pWal->ckptLock = 1;
  44036. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  44037. ** to prevent any writers from running while the checkpoint is underway.
  44038. ** This has to be done before the call to walIndexReadHdr() below.
  44039. **
  44040. ** If the writer lock cannot be obtained, then a passive checkpoint is
  44041. ** run instead. Since the checkpointer is not holding the writer lock,
  44042. ** there is no point in blocking waiting for any readers. Assuming no
  44043. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  44044. */
  44045. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  44046. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  44047. if( rc==SQLITE_OK ){
  44048. pWal->writeLock = 1;
  44049. }else if( rc==SQLITE_BUSY ){
  44050. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  44051. rc = SQLITE_OK;
  44052. }
  44053. }
  44054. /* Read the wal-index header. */
  44055. if( rc==SQLITE_OK ){
  44056. rc = walIndexReadHdr(pWal, &isChanged);
  44057. }
  44058. /* Copy data from the log to the database file. */
  44059. if( rc==SQLITE_OK ){
  44060. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  44061. rc = SQLITE_CORRUPT_BKPT;
  44062. }else{
  44063. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  44064. }
  44065. /* If no error occurred, set the output variables. */
  44066. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  44067. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  44068. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  44069. }
  44070. }
  44071. if( isChanged ){
  44072. /* If a new wal-index header was loaded before the checkpoint was
  44073. ** performed, then the pager-cache associated with pWal is now
  44074. ** out of date. So zero the cached wal-index header to ensure that
  44075. ** next time the pager opens a snapshot on this database it knows that
  44076. ** the cache needs to be reset.
  44077. */
  44078. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  44079. }
  44080. /* Release the locks. */
  44081. sqlite3WalEndWriteTransaction(pWal);
  44082. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  44083. pWal->ckptLock = 0;
  44084. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  44085. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  44086. }
  44087. /* Return the value to pass to a sqlite3_wal_hook callback, the
  44088. ** number of frames in the WAL at the point of the last commit since
  44089. ** sqlite3WalCallback() was called. If no commits have occurred since
  44090. ** the last call, then return 0.
  44091. */
  44092. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  44093. u32 ret = 0;
  44094. if( pWal ){
  44095. ret = pWal->iCallback;
  44096. pWal->iCallback = 0;
  44097. }
  44098. return (int)ret;
  44099. }
  44100. /*
  44101. ** This function is called to change the WAL subsystem into or out
  44102. ** of locking_mode=EXCLUSIVE.
  44103. **
  44104. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  44105. ** into locking_mode=NORMAL. This means that we must acquire a lock
  44106. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  44107. ** or if the acquisition of the lock fails, then return 0. If the
  44108. ** transition out of exclusive-mode is successful, return 1. This
  44109. ** operation must occur while the pager is still holding the exclusive
  44110. ** lock on the main database file.
  44111. **
  44112. ** If op is one, then change from locking_mode=NORMAL into
  44113. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  44114. ** be released. Return 1 if the transition is made and 0 if the
  44115. ** WAL is already in exclusive-locking mode - meaning that this
  44116. ** routine is a no-op. The pager must already hold the exclusive lock
  44117. ** on the main database file before invoking this operation.
  44118. **
  44119. ** If op is negative, then do a dry-run of the op==1 case but do
  44120. ** not actually change anything. The pager uses this to see if it
  44121. ** should acquire the database exclusive lock prior to invoking
  44122. ** the op==1 case.
  44123. */
  44124. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  44125. int rc;
  44126. assert( pWal->writeLock==0 );
  44127. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  44128. /* pWal->readLock is usually set, but might be -1 if there was a
  44129. ** prior error while attempting to acquire are read-lock. This cannot
  44130. ** happen if the connection is actually in exclusive mode (as no xShmLock
  44131. ** locks are taken in this case). Nor should the pager attempt to
  44132. ** upgrade to exclusive-mode following such an error.
  44133. */
  44134. assert( pWal->readLock>=0 || pWal->lockError );
  44135. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  44136. if( op==0 ){
  44137. if( pWal->exclusiveMode ){
  44138. pWal->exclusiveMode = 0;
  44139. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  44140. pWal->exclusiveMode = 1;
  44141. }
  44142. rc = pWal->exclusiveMode==0;
  44143. }else{
  44144. /* Already in locking_mode=NORMAL */
  44145. rc = 0;
  44146. }
  44147. }else if( op>0 ){
  44148. assert( pWal->exclusiveMode==0 );
  44149. assert( pWal->readLock>=0 );
  44150. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  44151. pWal->exclusiveMode = 1;
  44152. rc = 1;
  44153. }else{
  44154. rc = pWal->exclusiveMode==0;
  44155. }
  44156. return rc;
  44157. }
  44158. /*
  44159. ** Return true if the argument is non-NULL and the WAL module is using
  44160. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  44161. ** WAL module is using shared-memory, return false.
  44162. */
  44163. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  44164. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  44165. }
  44166. #ifdef SQLITE_ENABLE_ZIPVFS
  44167. /*
  44168. ** If the argument is not NULL, it points to a Wal object that holds a
  44169. ** read-lock. This function returns the database page-size if it is known,
  44170. ** or zero if it is not (or if pWal is NULL).
  44171. */
  44172. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  44173. assert( pWal==0 || pWal->readLock>=0 );
  44174. return (pWal ? pWal->szPage : 0);
  44175. }
  44176. #endif
  44177. #endif /* #ifndef SQLITE_OMIT_WAL */
  44178. /************** End of wal.c *************************************************/
  44179. /************** Begin file btmutex.c *****************************************/
  44180. /*
  44181. ** 2007 August 27
  44182. **
  44183. ** The author disclaims copyright to this source code. In place of
  44184. ** a legal notice, here is a blessing:
  44185. **
  44186. ** May you do good and not evil.
  44187. ** May you find forgiveness for yourself and forgive others.
  44188. ** May you share freely, never taking more than you give.
  44189. **
  44190. *************************************************************************
  44191. **
  44192. ** This file contains code used to implement mutexes on Btree objects.
  44193. ** This code really belongs in btree.c. But btree.c is getting too
  44194. ** big and we want to break it down some. This packaged seemed like
  44195. ** a good breakout.
  44196. */
  44197. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  44198. /************** Begin file btreeInt.h ****************************************/
  44199. /*
  44200. ** 2004 April 6
  44201. **
  44202. ** The author disclaims copyright to this source code. In place of
  44203. ** a legal notice, here is a blessing:
  44204. **
  44205. ** May you do good and not evil.
  44206. ** May you find forgiveness for yourself and forgive others.
  44207. ** May you share freely, never taking more than you give.
  44208. **
  44209. *************************************************************************
  44210. ** This file implements a external (disk-based) database using BTrees.
  44211. ** For a detailed discussion of BTrees, refer to
  44212. **
  44213. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  44214. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  44215. ** Publishing Company, Reading, Massachusetts.
  44216. **
  44217. ** The basic idea is that each page of the file contains N database
  44218. ** entries and N+1 pointers to subpages.
  44219. **
  44220. ** ----------------------------------------------------------------
  44221. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  44222. ** ----------------------------------------------------------------
  44223. **
  44224. ** All of the keys on the page that Ptr(0) points to have values less
  44225. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  44226. ** values greater than Key(0) and less than Key(1). All of the keys
  44227. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  44228. ** so forth.
  44229. **
  44230. ** Finding a particular key requires reading O(log(M)) pages from the
  44231. ** disk where M is the number of entries in the tree.
  44232. **
  44233. ** In this implementation, a single file can hold one or more separate
  44234. ** BTrees. Each BTree is identified by the index of its root page. The
  44235. ** key and data for any entry are combined to form the "payload". A
  44236. ** fixed amount of payload can be carried directly on the database
  44237. ** page. If the payload is larger than the preset amount then surplus
  44238. ** bytes are stored on overflow pages. The payload for an entry
  44239. ** and the preceding pointer are combined to form a "Cell". Each
  44240. ** page has a small header which contains the Ptr(N) pointer and other
  44241. ** information such as the size of key and data.
  44242. **
  44243. ** FORMAT DETAILS
  44244. **
  44245. ** The file is divided into pages. The first page is called page 1,
  44246. ** the second is page 2, and so forth. A page number of zero indicates
  44247. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  44248. ** Each page can be either a btree page, a freelist page, an overflow
  44249. ** page, or a pointer-map page.
  44250. **
  44251. ** The first page is always a btree page. The first 100 bytes of the first
  44252. ** page contain a special header (the "file header") that describes the file.
  44253. ** The format of the file header is as follows:
  44254. **
  44255. ** OFFSET SIZE DESCRIPTION
  44256. ** 0 16 Header string: "SQLite format 3\000"
  44257. ** 16 2 Page size in bytes.
  44258. ** 18 1 File format write version
  44259. ** 19 1 File format read version
  44260. ** 20 1 Bytes of unused space at the end of each page
  44261. ** 21 1 Max embedded payload fraction
  44262. ** 22 1 Min embedded payload fraction
  44263. ** 23 1 Min leaf payload fraction
  44264. ** 24 4 File change counter
  44265. ** 28 4 Reserved for future use
  44266. ** 32 4 First freelist page
  44267. ** 36 4 Number of freelist pages in the file
  44268. ** 40 60 15 4-byte meta values passed to higher layers
  44269. **
  44270. ** 40 4 Schema cookie
  44271. ** 44 4 File format of schema layer
  44272. ** 48 4 Size of page cache
  44273. ** 52 4 Largest root-page (auto/incr_vacuum)
  44274. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  44275. ** 60 4 User version
  44276. ** 64 4 Incremental vacuum mode
  44277. ** 68 4 unused
  44278. ** 72 4 unused
  44279. ** 76 4 unused
  44280. **
  44281. ** All of the integer values are big-endian (most significant byte first).
  44282. **
  44283. ** The file change counter is incremented when the database is changed
  44284. ** This counter allows other processes to know when the file has changed
  44285. ** and thus when they need to flush their cache.
  44286. **
  44287. ** The max embedded payload fraction is the amount of the total usable
  44288. ** space in a page that can be consumed by a single cell for standard
  44289. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  44290. ** is to limit the maximum cell size so that at least 4 cells will fit
  44291. ** on one page. Thus the default max embedded payload fraction is 64.
  44292. **
  44293. ** If the payload for a cell is larger than the max payload, then extra
  44294. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  44295. ** as many bytes as possible are moved into the overflow pages without letting
  44296. ** the cell size drop below the min embedded payload fraction.
  44297. **
  44298. ** The min leaf payload fraction is like the min embedded payload fraction
  44299. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  44300. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  44301. ** not specified in the header.
  44302. **
  44303. ** Each btree pages is divided into three sections: The header, the
  44304. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  44305. ** file header that occurs before the page header.
  44306. **
  44307. ** |----------------|
  44308. ** | file header | 100 bytes. Page 1 only.
  44309. ** |----------------|
  44310. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  44311. ** |----------------|
  44312. ** | cell pointer | | 2 bytes per cell. Sorted order.
  44313. ** | array | | Grows downward
  44314. ** | | v
  44315. ** |----------------|
  44316. ** | unallocated |
  44317. ** | space |
  44318. ** |----------------| ^ Grows upwards
  44319. ** | cell content | | Arbitrary order interspersed with freeblocks.
  44320. ** | area | | and free space fragments.
  44321. ** |----------------|
  44322. **
  44323. ** The page headers looks like this:
  44324. **
  44325. ** OFFSET SIZE DESCRIPTION
  44326. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  44327. ** 1 2 byte offset to the first freeblock
  44328. ** 3 2 number of cells on this page
  44329. ** 5 2 first byte of the cell content area
  44330. ** 7 1 number of fragmented free bytes
  44331. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  44332. **
  44333. ** The flags define the format of this btree page. The leaf flag means that
  44334. ** this page has no children. The zerodata flag means that this page carries
  44335. ** only keys and no data. The intkey flag means that the key is a integer
  44336. ** which is stored in the key size entry of the cell header rather than in
  44337. ** the payload area.
  44338. **
  44339. ** The cell pointer array begins on the first byte after the page header.
  44340. ** The cell pointer array contains zero or more 2-byte numbers which are
  44341. ** offsets from the beginning of the page to the cell content in the cell
  44342. ** content area. The cell pointers occur in sorted order. The system strives
  44343. ** to keep free space after the last cell pointer so that new cells can
  44344. ** be easily added without having to defragment the page.
  44345. **
  44346. ** Cell content is stored at the very end of the page and grows toward the
  44347. ** beginning of the page.
  44348. **
  44349. ** Unused space within the cell content area is collected into a linked list of
  44350. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  44351. ** to the first freeblock is given in the header. Freeblocks occur in
  44352. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  44353. ** any group of 3 or fewer unused bytes in the cell content area cannot
  44354. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  44355. ** a fragment. The total number of bytes in all fragments is recorded.
  44356. ** in the page header at offset 7.
  44357. **
  44358. ** SIZE DESCRIPTION
  44359. ** 2 Byte offset of the next freeblock
  44360. ** 2 Bytes in this freeblock
  44361. **
  44362. ** Cells are of variable length. Cells are stored in the cell content area at
  44363. ** the end of the page. Pointers to the cells are in the cell pointer array
  44364. ** that immediately follows the page header. Cells is not necessarily
  44365. ** contiguous or in order, but cell pointers are contiguous and in order.
  44366. **
  44367. ** Cell content makes use of variable length integers. A variable
  44368. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  44369. ** byte are used. The integer consists of all bytes that have bit 8 set and
  44370. ** the first byte with bit 8 clear. The most significant byte of the integer
  44371. ** appears first. A variable-length integer may not be more than 9 bytes long.
  44372. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  44373. ** allows a 64-bit integer to be encoded in 9 bytes.
  44374. **
  44375. ** 0x00 becomes 0x00000000
  44376. ** 0x7f becomes 0x0000007f
  44377. ** 0x81 0x00 becomes 0x00000080
  44378. ** 0x82 0x00 becomes 0x00000100
  44379. ** 0x80 0x7f becomes 0x0000007f
  44380. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  44381. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  44382. **
  44383. ** Variable length integers are used for rowids and to hold the number of
  44384. ** bytes of key and data in a btree cell.
  44385. **
  44386. ** The content of a cell looks like this:
  44387. **
  44388. ** SIZE DESCRIPTION
  44389. ** 4 Page number of the left child. Omitted if leaf flag is set.
  44390. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  44391. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  44392. ** * Payload
  44393. ** 4 First page of the overflow chain. Omitted if no overflow
  44394. **
  44395. ** Overflow pages form a linked list. Each page except the last is completely
  44396. ** filled with data (pagesize - 4 bytes). The last page can have as little
  44397. ** as 1 byte of data.
  44398. **
  44399. ** SIZE DESCRIPTION
  44400. ** 4 Page number of next overflow page
  44401. ** * Data
  44402. **
  44403. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  44404. ** file header points to the first in a linked list of trunk page. Each trunk
  44405. ** page points to multiple leaf pages. The content of a leaf page is
  44406. ** unspecified. A trunk page looks like this:
  44407. **
  44408. ** SIZE DESCRIPTION
  44409. ** 4 Page number of next trunk page
  44410. ** 4 Number of leaf pointers on this page
  44411. ** * zero or more pages numbers of leaves
  44412. */
  44413. /* The following value is the maximum cell size assuming a maximum page
  44414. ** size give above.
  44415. */
  44416. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  44417. /* The maximum number of cells on a single page of the database. This
  44418. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  44419. ** plus 2 bytes for the index to the cell in the page header). Such
  44420. ** small cells will be rare, but they are possible.
  44421. */
  44422. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  44423. /* Forward declarations */
  44424. typedef struct MemPage MemPage;
  44425. typedef struct BtLock BtLock;
  44426. /*
  44427. ** This is a magic string that appears at the beginning of every
  44428. ** SQLite database in order to identify the file as a real database.
  44429. **
  44430. ** You can change this value at compile-time by specifying a
  44431. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  44432. ** header must be exactly 16 bytes including the zero-terminator so
  44433. ** the string itself should be 15 characters long. If you change
  44434. ** the header, then your custom library will not be able to read
  44435. ** databases generated by the standard tools and the standard tools
  44436. ** will not be able to read databases created by your custom library.
  44437. */
  44438. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  44439. # define SQLITE_FILE_HEADER "SQLite format 3"
  44440. #endif
  44441. /*
  44442. ** Page type flags. An ORed combination of these flags appear as the
  44443. ** first byte of on-disk image of every BTree page.
  44444. */
  44445. #define PTF_INTKEY 0x01
  44446. #define PTF_ZERODATA 0x02
  44447. #define PTF_LEAFDATA 0x04
  44448. #define PTF_LEAF 0x08
  44449. /*
  44450. ** As each page of the file is loaded into memory, an instance of the following
  44451. ** structure is appended and initialized to zero. This structure stores
  44452. ** information about the page that is decoded from the raw file page.
  44453. **
  44454. ** The pParent field points back to the parent page. This allows us to
  44455. ** walk up the BTree from any leaf to the root. Care must be taken to
  44456. ** unref() the parent page pointer when this page is no longer referenced.
  44457. ** The pageDestructor() routine handles that chore.
  44458. **
  44459. ** Access to all fields of this structure is controlled by the mutex
  44460. ** stored in MemPage.pBt->mutex.
  44461. */
  44462. struct MemPage {
  44463. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  44464. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  44465. u8 intKey; /* True if intkey flag is set */
  44466. u8 leaf; /* True if leaf flag is set */
  44467. u8 hasData; /* True if this page stores data */
  44468. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  44469. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  44470. u8 max1bytePayload; /* min(maxLocal,127) */
  44471. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  44472. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  44473. u16 cellOffset; /* Index in aData of first cell pointer */
  44474. u16 nFree; /* Number of free bytes on the page */
  44475. u16 nCell; /* Number of cells on this page, local and ovfl */
  44476. u16 maskPage; /* Mask for page offset */
  44477. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  44478. ** non-overflow cell */
  44479. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  44480. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  44481. u8 *aData; /* Pointer to disk image of the page data */
  44482. u8 *aDataEnd; /* One byte past the end of usable data */
  44483. u8 *aCellIdx; /* The cell index area */
  44484. DbPage *pDbPage; /* Pager page handle */
  44485. Pgno pgno; /* Page number for this page */
  44486. };
  44487. /*
  44488. ** The in-memory image of a disk page has the auxiliary information appended
  44489. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  44490. ** that extra information.
  44491. */
  44492. #define EXTRA_SIZE sizeof(MemPage)
  44493. /*
  44494. ** A linked list of the following structures is stored at BtShared.pLock.
  44495. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  44496. ** is opened on the table with root page BtShared.iTable. Locks are removed
  44497. ** from this list when a transaction is committed or rolled back, or when
  44498. ** a btree handle is closed.
  44499. */
  44500. struct BtLock {
  44501. Btree *pBtree; /* Btree handle holding this lock */
  44502. Pgno iTable; /* Root page of table */
  44503. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  44504. BtLock *pNext; /* Next in BtShared.pLock list */
  44505. };
  44506. /* Candidate values for BtLock.eLock */
  44507. #define READ_LOCK 1
  44508. #define WRITE_LOCK 2
  44509. /* A Btree handle
  44510. **
  44511. ** A database connection contains a pointer to an instance of
  44512. ** this object for every database file that it has open. This structure
  44513. ** is opaque to the database connection. The database connection cannot
  44514. ** see the internals of this structure and only deals with pointers to
  44515. ** this structure.
  44516. **
  44517. ** For some database files, the same underlying database cache might be
  44518. ** shared between multiple connections. In that case, each connection
  44519. ** has it own instance of this object. But each instance of this object
  44520. ** points to the same BtShared object. The database cache and the
  44521. ** schema associated with the database file are all contained within
  44522. ** the BtShared object.
  44523. **
  44524. ** All fields in this structure are accessed under sqlite3.mutex.
  44525. ** The pBt pointer itself may not be changed while there exists cursors
  44526. ** in the referenced BtShared that point back to this Btree since those
  44527. ** cursors have to go through this Btree to find their BtShared and
  44528. ** they often do so without holding sqlite3.mutex.
  44529. */
  44530. struct Btree {
  44531. sqlite3 *db; /* The database connection holding this btree */
  44532. BtShared *pBt; /* Sharable content of this btree */
  44533. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  44534. u8 sharable; /* True if we can share pBt with another db */
  44535. u8 locked; /* True if db currently has pBt locked */
  44536. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  44537. int nBackup; /* Number of backup operations reading this btree */
  44538. Btree *pNext; /* List of other sharable Btrees from the same db */
  44539. Btree *pPrev; /* Back pointer of the same list */
  44540. #ifndef SQLITE_OMIT_SHARED_CACHE
  44541. BtLock lock; /* Object used to lock page 1 */
  44542. #endif
  44543. };
  44544. /*
  44545. ** Btree.inTrans may take one of the following values.
  44546. **
  44547. ** If the shared-data extension is enabled, there may be multiple users
  44548. ** of the Btree structure. At most one of these may open a write transaction,
  44549. ** but any number may have active read transactions.
  44550. */
  44551. #define TRANS_NONE 0
  44552. #define TRANS_READ 1
  44553. #define TRANS_WRITE 2
  44554. /*
  44555. ** An instance of this object represents a single database file.
  44556. **
  44557. ** A single database file can be in use at the same time by two
  44558. ** or more database connections. When two or more connections are
  44559. ** sharing the same database file, each connection has it own
  44560. ** private Btree object for the file and each of those Btrees points
  44561. ** to this one BtShared object. BtShared.nRef is the number of
  44562. ** connections currently sharing this database file.
  44563. **
  44564. ** Fields in this structure are accessed under the BtShared.mutex
  44565. ** mutex, except for nRef and pNext which are accessed under the
  44566. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  44567. ** may not be modified once it is initially set as long as nRef>0.
  44568. ** The pSchema field may be set once under BtShared.mutex and
  44569. ** thereafter is unchanged as long as nRef>0.
  44570. **
  44571. ** isPending:
  44572. **
  44573. ** If a BtShared client fails to obtain a write-lock on a database
  44574. ** table (because there exists one or more read-locks on the table),
  44575. ** the shared-cache enters 'pending-lock' state and isPending is
  44576. ** set to true.
  44577. **
  44578. ** The shared-cache leaves the 'pending lock' state when either of
  44579. ** the following occur:
  44580. **
  44581. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  44582. ** 2) The number of locks held by other connections drops to zero.
  44583. **
  44584. ** while in the 'pending-lock' state, no connection may start a new
  44585. ** transaction.
  44586. **
  44587. ** This feature is included to help prevent writer-starvation.
  44588. */
  44589. struct BtShared {
  44590. Pager *pPager; /* The page cache */
  44591. sqlite3 *db; /* Database connection currently using this Btree */
  44592. BtCursor *pCursor; /* A list of all open cursors */
  44593. MemPage *pPage1; /* First page of the database */
  44594. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  44595. #ifndef SQLITE_OMIT_AUTOVACUUM
  44596. u8 autoVacuum; /* True if auto-vacuum is enabled */
  44597. u8 incrVacuum; /* True if incr-vacuum is enabled */
  44598. #endif
  44599. u8 inTransaction; /* Transaction state */
  44600. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  44601. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  44602. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  44603. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  44604. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  44605. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  44606. u32 pageSize; /* Total number of bytes on a page */
  44607. u32 usableSize; /* Number of usable bytes on each page */
  44608. int nTransaction; /* Number of open transactions (read + write) */
  44609. u32 nPage; /* Number of pages in the database */
  44610. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  44611. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  44612. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  44613. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  44614. #ifndef SQLITE_OMIT_SHARED_CACHE
  44615. int nRef; /* Number of references to this structure */
  44616. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  44617. BtLock *pLock; /* List of locks held on this shared-btree struct */
  44618. Btree *pWriter; /* Btree with currently open write transaction */
  44619. #endif
  44620. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  44621. };
  44622. /*
  44623. ** Allowed values for BtShared.btsFlags
  44624. */
  44625. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  44626. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  44627. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  44628. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  44629. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  44630. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  44631. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  44632. /*
  44633. ** An instance of the following structure is used to hold information
  44634. ** about a cell. The parseCellPtr() function fills in this structure
  44635. ** based on information extract from the raw disk page.
  44636. */
  44637. typedef struct CellInfo CellInfo;
  44638. struct CellInfo {
  44639. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  44640. u8 *pCell; /* Pointer to the start of cell content */
  44641. u32 nData; /* Number of bytes of data */
  44642. u32 nPayload; /* Total amount of payload */
  44643. u16 nHeader; /* Size of the cell content header in bytes */
  44644. u16 nLocal; /* Amount of payload held locally */
  44645. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  44646. u16 nSize; /* Size of the cell content on the main b-tree page */
  44647. };
  44648. /*
  44649. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  44650. ** this will be declared corrupt. This value is calculated based on a
  44651. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  44652. ** root-node and 3 for all other internal nodes.
  44653. **
  44654. ** If a tree that appears to be taller than this is encountered, it is
  44655. ** assumed that the database is corrupt.
  44656. */
  44657. #define BTCURSOR_MAX_DEPTH 20
  44658. /*
  44659. ** A cursor is a pointer to a particular entry within a particular
  44660. ** b-tree within a database file.
  44661. **
  44662. ** The entry is identified by its MemPage and the index in
  44663. ** MemPage.aCell[] of the entry.
  44664. **
  44665. ** A single database file can be shared by two more database connections,
  44666. ** but cursors cannot be shared. Each cursor is associated with a
  44667. ** particular database connection identified BtCursor.pBtree.db.
  44668. **
  44669. ** Fields in this structure are accessed under the BtShared.mutex
  44670. ** found at self->pBt->mutex.
  44671. */
  44672. struct BtCursor {
  44673. Btree *pBtree; /* The Btree to which this cursor belongs */
  44674. BtShared *pBt; /* The BtShared this cursor points to */
  44675. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  44676. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  44677. #ifndef SQLITE_OMIT_INCRBLOB
  44678. Pgno *aOverflow; /* Cache of overflow page locations */
  44679. #endif
  44680. Pgno pgnoRoot; /* The root page of this tree */
  44681. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  44682. CellInfo info; /* A parse of the cell we are pointing at */
  44683. i64 nKey; /* Size of pKey, or last integer key */
  44684. void *pKey; /* Saved key that was cursor's last known position */
  44685. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  44686. u8 wrFlag; /* True if writable */
  44687. u8 atLast; /* Cursor pointing to the last entry */
  44688. u8 validNKey; /* True if info.nKey is valid */
  44689. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  44690. #ifndef SQLITE_OMIT_INCRBLOB
  44691. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  44692. #endif
  44693. u8 hints; /* As configured by CursorSetHints() */
  44694. i16 iPage; /* Index of current page in apPage */
  44695. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  44696. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  44697. };
  44698. /*
  44699. ** Potential values for BtCursor.eState.
  44700. **
  44701. ** CURSOR_VALID:
  44702. ** Cursor points to a valid entry. getPayload() etc. may be called.
  44703. **
  44704. ** CURSOR_INVALID:
  44705. ** Cursor does not point to a valid entry. This can happen (for example)
  44706. ** because the table is empty or because BtreeCursorFirst() has not been
  44707. ** called.
  44708. **
  44709. ** CURSOR_REQUIRESEEK:
  44710. ** The table that this cursor was opened on still exists, but has been
  44711. ** modified since the cursor was last used. The cursor position is saved
  44712. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  44713. ** this state, restoreCursorPosition() can be called to attempt to
  44714. ** seek the cursor to the saved position.
  44715. **
  44716. ** CURSOR_FAULT:
  44717. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  44718. ** on a different connection that shares the BtShared cache with this
  44719. ** cursor. The error has left the cache in an inconsistent state.
  44720. ** Do nothing else with this cursor. Any attempt to use the cursor
  44721. ** should return the error code stored in BtCursor.skip
  44722. */
  44723. #define CURSOR_INVALID 0
  44724. #define CURSOR_VALID 1
  44725. #define CURSOR_REQUIRESEEK 2
  44726. #define CURSOR_FAULT 3
  44727. /*
  44728. ** The database page the PENDING_BYTE occupies. This page is never used.
  44729. */
  44730. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  44731. /*
  44732. ** These macros define the location of the pointer-map entry for a
  44733. ** database page. The first argument to each is the number of usable
  44734. ** bytes on each page of the database (often 1024). The second is the
  44735. ** page number to look up in the pointer map.
  44736. **
  44737. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  44738. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  44739. ** the offset of the requested map entry.
  44740. **
  44741. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  44742. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  44743. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  44744. ** this test.
  44745. */
  44746. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  44747. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  44748. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  44749. /*
  44750. ** The pointer map is a lookup table that identifies the parent page for
  44751. ** each child page in the database file. The parent page is the page that
  44752. ** contains a pointer to the child. Every page in the database contains
  44753. ** 0 or 1 parent pages. (In this context 'database page' refers
  44754. ** to any page that is not part of the pointer map itself.) Each pointer map
  44755. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  44756. ** The PTRMAP_XXX identifiers below are the valid types.
  44757. **
  44758. ** The purpose of the pointer map is to facility moving pages from one
  44759. ** position in the file to another as part of autovacuum. When a page
  44760. ** is moved, the pointer in its parent must be updated to point to the
  44761. ** new location. The pointer map is used to locate the parent page quickly.
  44762. **
  44763. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  44764. ** used in this case.
  44765. **
  44766. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  44767. ** is not used in this case.
  44768. **
  44769. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  44770. ** overflow pages. The page number identifies the page that
  44771. ** contains the cell with a pointer to this overflow page.
  44772. **
  44773. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  44774. ** overflow pages. The page-number identifies the previous
  44775. ** page in the overflow page list.
  44776. **
  44777. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  44778. ** identifies the parent page in the btree.
  44779. */
  44780. #define PTRMAP_ROOTPAGE 1
  44781. #define PTRMAP_FREEPAGE 2
  44782. #define PTRMAP_OVERFLOW1 3
  44783. #define PTRMAP_OVERFLOW2 4
  44784. #define PTRMAP_BTREE 5
  44785. /* A bunch of assert() statements to check the transaction state variables
  44786. ** of handle p (type Btree*) are internally consistent.
  44787. */
  44788. #define btreeIntegrity(p) \
  44789. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  44790. assert( p->pBt->inTransaction>=p->inTrans );
  44791. /*
  44792. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  44793. ** if the database supports auto-vacuum or not. Because it is used
  44794. ** within an expression that is an argument to another macro
  44795. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  44796. ** So, this macro is defined instead.
  44797. */
  44798. #ifndef SQLITE_OMIT_AUTOVACUUM
  44799. #define ISAUTOVACUUM (pBt->autoVacuum)
  44800. #else
  44801. #define ISAUTOVACUUM 0
  44802. #endif
  44803. /*
  44804. ** This structure is passed around through all the sanity checking routines
  44805. ** in order to keep track of some global state information.
  44806. **
  44807. ** The aRef[] array is allocated so that there is 1 bit for each page in
  44808. ** the database. As the integrity-check proceeds, for each page used in
  44809. ** the database the corresponding bit is set. This allows integrity-check to
  44810. ** detect pages that are used twice and orphaned pages (both of which
  44811. ** indicate corruption).
  44812. */
  44813. typedef struct IntegrityCk IntegrityCk;
  44814. struct IntegrityCk {
  44815. BtShared *pBt; /* The tree being checked out */
  44816. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  44817. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  44818. Pgno nPage; /* Number of pages in the database */
  44819. int mxErr; /* Stop accumulating errors when this reaches zero */
  44820. int nErr; /* Number of messages written to zErrMsg so far */
  44821. int mallocFailed; /* A memory allocation error has occurred */
  44822. StrAccum errMsg; /* Accumulate the error message text here */
  44823. };
  44824. /*
  44825. ** Routines to read or write a two- and four-byte big-endian integer values.
  44826. */
  44827. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  44828. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  44829. #define get4byte sqlite3Get4byte
  44830. #define put4byte sqlite3Put4byte
  44831. /************** End of btreeInt.h ********************************************/
  44832. /************** Continuing where we left off in btmutex.c ********************/
  44833. #ifndef SQLITE_OMIT_SHARED_CACHE
  44834. #if SQLITE_THREADSAFE
  44835. /*
  44836. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  44837. ** set BtShared.db to the database handle associated with p and the
  44838. ** p->locked boolean to true.
  44839. */
  44840. static void lockBtreeMutex(Btree *p){
  44841. assert( p->locked==0 );
  44842. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  44843. assert( sqlite3_mutex_held(p->db->mutex) );
  44844. sqlite3_mutex_enter(p->pBt->mutex);
  44845. p->pBt->db = p->db;
  44846. p->locked = 1;
  44847. }
  44848. /*
  44849. ** Release the BtShared mutex associated with B-Tree handle p and
  44850. ** clear the p->locked boolean.
  44851. */
  44852. static void unlockBtreeMutex(Btree *p){
  44853. BtShared *pBt = p->pBt;
  44854. assert( p->locked==1 );
  44855. assert( sqlite3_mutex_held(pBt->mutex) );
  44856. assert( sqlite3_mutex_held(p->db->mutex) );
  44857. assert( p->db==pBt->db );
  44858. sqlite3_mutex_leave(pBt->mutex);
  44859. p->locked = 0;
  44860. }
  44861. /*
  44862. ** Enter a mutex on the given BTree object.
  44863. **
  44864. ** If the object is not sharable, then no mutex is ever required
  44865. ** and this routine is a no-op. The underlying mutex is non-recursive.
  44866. ** But we keep a reference count in Btree.wantToLock so the behavior
  44867. ** of this interface is recursive.
  44868. **
  44869. ** To avoid deadlocks, multiple Btrees are locked in the same order
  44870. ** by all database connections. The p->pNext is a list of other
  44871. ** Btrees belonging to the same database connection as the p Btree
  44872. ** which need to be locked after p. If we cannot get a lock on
  44873. ** p, then first unlock all of the others on p->pNext, then wait
  44874. ** for the lock to become available on p, then relock all of the
  44875. ** subsequent Btrees that desire a lock.
  44876. */
  44877. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  44878. Btree *pLater;
  44879. /* Some basic sanity checking on the Btree. The list of Btrees
  44880. ** connected by pNext and pPrev should be in sorted order by
  44881. ** Btree.pBt value. All elements of the list should belong to
  44882. ** the same connection. Only shared Btrees are on the list. */
  44883. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  44884. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  44885. assert( p->pNext==0 || p->pNext->db==p->db );
  44886. assert( p->pPrev==0 || p->pPrev->db==p->db );
  44887. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  44888. /* Check for locking consistency */
  44889. assert( !p->locked || p->wantToLock>0 );
  44890. assert( p->sharable || p->wantToLock==0 );
  44891. /* We should already hold a lock on the database connection */
  44892. assert( sqlite3_mutex_held(p->db->mutex) );
  44893. /* Unless the database is sharable and unlocked, then BtShared.db
  44894. ** should already be set correctly. */
  44895. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  44896. if( !p->sharable ) return;
  44897. p->wantToLock++;
  44898. if( p->locked ) return;
  44899. /* In most cases, we should be able to acquire the lock we
  44900. ** want without having to go throught the ascending lock
  44901. ** procedure that follows. Just be sure not to block.
  44902. */
  44903. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  44904. p->pBt->db = p->db;
  44905. p->locked = 1;
  44906. return;
  44907. }
  44908. /* To avoid deadlock, first release all locks with a larger
  44909. ** BtShared address. Then acquire our lock. Then reacquire
  44910. ** the other BtShared locks that we used to hold in ascending
  44911. ** order.
  44912. */
  44913. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  44914. assert( pLater->sharable );
  44915. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  44916. assert( !pLater->locked || pLater->wantToLock>0 );
  44917. if( pLater->locked ){
  44918. unlockBtreeMutex(pLater);
  44919. }
  44920. }
  44921. lockBtreeMutex(p);
  44922. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  44923. if( pLater->wantToLock ){
  44924. lockBtreeMutex(pLater);
  44925. }
  44926. }
  44927. }
  44928. /*
  44929. ** Exit the recursive mutex on a Btree.
  44930. */
  44931. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  44932. if( p->sharable ){
  44933. assert( p->wantToLock>0 );
  44934. p->wantToLock--;
  44935. if( p->wantToLock==0 ){
  44936. unlockBtreeMutex(p);
  44937. }
  44938. }
  44939. }
  44940. #ifndef NDEBUG
  44941. /*
  44942. ** Return true if the BtShared mutex is held on the btree, or if the
  44943. ** B-Tree is not marked as sharable.
  44944. **
  44945. ** This routine is used only from within assert() statements.
  44946. */
  44947. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  44948. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  44949. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  44950. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  44951. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  44952. return (p->sharable==0 || p->locked);
  44953. }
  44954. #endif
  44955. #ifndef SQLITE_OMIT_INCRBLOB
  44956. /*
  44957. ** Enter and leave a mutex on a Btree given a cursor owned by that
  44958. ** Btree. These entry points are used by incremental I/O and can be
  44959. ** omitted if that module is not used.
  44960. */
  44961. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  44962. sqlite3BtreeEnter(pCur->pBtree);
  44963. }
  44964. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  44965. sqlite3BtreeLeave(pCur->pBtree);
  44966. }
  44967. #endif /* SQLITE_OMIT_INCRBLOB */
  44968. /*
  44969. ** Enter the mutex on every Btree associated with a database
  44970. ** connection. This is needed (for example) prior to parsing
  44971. ** a statement since we will be comparing table and column names
  44972. ** against all schemas and we do not want those schemas being
  44973. ** reset out from under us.
  44974. **
  44975. ** There is a corresponding leave-all procedures.
  44976. **
  44977. ** Enter the mutexes in accending order by BtShared pointer address
  44978. ** to avoid the possibility of deadlock when two threads with
  44979. ** two or more btrees in common both try to lock all their btrees
  44980. ** at the same instant.
  44981. */
  44982. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  44983. int i;
  44984. Btree *p;
  44985. assert( sqlite3_mutex_held(db->mutex) );
  44986. for(i=0; i<db->nDb; i++){
  44987. p = db->aDb[i].pBt;
  44988. if( p ) sqlite3BtreeEnter(p);
  44989. }
  44990. }
  44991. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  44992. int i;
  44993. Btree *p;
  44994. assert( sqlite3_mutex_held(db->mutex) );
  44995. for(i=0; i<db->nDb; i++){
  44996. p = db->aDb[i].pBt;
  44997. if( p ) sqlite3BtreeLeave(p);
  44998. }
  44999. }
  45000. /*
  45001. ** Return true if a particular Btree requires a lock. Return FALSE if
  45002. ** no lock is ever required since it is not sharable.
  45003. */
  45004. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  45005. return p->sharable;
  45006. }
  45007. #ifndef NDEBUG
  45008. /*
  45009. ** Return true if the current thread holds the database connection
  45010. ** mutex and all required BtShared mutexes.
  45011. **
  45012. ** This routine is used inside assert() statements only.
  45013. */
  45014. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  45015. int i;
  45016. if( !sqlite3_mutex_held(db->mutex) ){
  45017. return 0;
  45018. }
  45019. for(i=0; i<db->nDb; i++){
  45020. Btree *p;
  45021. p = db->aDb[i].pBt;
  45022. if( p && p->sharable &&
  45023. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  45024. return 0;
  45025. }
  45026. }
  45027. return 1;
  45028. }
  45029. #endif /* NDEBUG */
  45030. #ifndef NDEBUG
  45031. /*
  45032. ** Return true if the correct mutexes are held for accessing the
  45033. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  45034. ** access are:
  45035. **
  45036. ** (1) The mutex on db
  45037. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  45038. **
  45039. ** If pSchema is not NULL, then iDb is computed from pSchema and
  45040. ** db using sqlite3SchemaToIndex().
  45041. */
  45042. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  45043. Btree *p;
  45044. assert( db!=0 );
  45045. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  45046. assert( iDb>=0 && iDb<db->nDb );
  45047. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  45048. if( iDb==1 ) return 1;
  45049. p = db->aDb[iDb].pBt;
  45050. assert( p!=0 );
  45051. return p->sharable==0 || p->locked==1;
  45052. }
  45053. #endif /* NDEBUG */
  45054. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  45055. /*
  45056. ** The following are special cases for mutex enter routines for use
  45057. ** in single threaded applications that use shared cache. Except for
  45058. ** these two routines, all mutex operations are no-ops in that case and
  45059. ** are null #defines in btree.h.
  45060. **
  45061. ** If shared cache is disabled, then all btree mutex routines, including
  45062. ** the ones below, are no-ops and are null #defines in btree.h.
  45063. */
  45064. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  45065. p->pBt->db = p->db;
  45066. }
  45067. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  45068. int i;
  45069. for(i=0; i<db->nDb; i++){
  45070. Btree *p = db->aDb[i].pBt;
  45071. if( p ){
  45072. p->pBt->db = p->db;
  45073. }
  45074. }
  45075. }
  45076. #endif /* if SQLITE_THREADSAFE */
  45077. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  45078. /************** End of btmutex.c *********************************************/
  45079. /************** Begin file btree.c *******************************************/
  45080. /*
  45081. ** 2004 April 6
  45082. **
  45083. ** The author disclaims copyright to this source code. In place of
  45084. ** a legal notice, here is a blessing:
  45085. **
  45086. ** May you do good and not evil.
  45087. ** May you find forgiveness for yourself and forgive others.
  45088. ** May you share freely, never taking more than you give.
  45089. **
  45090. *************************************************************************
  45091. ** This file implements a external (disk-based) database using BTrees.
  45092. ** See the header comment on "btreeInt.h" for additional information.
  45093. ** Including a description of file format and an overview of operation.
  45094. */
  45095. /*
  45096. ** The header string that appears at the beginning of every
  45097. ** SQLite database.
  45098. */
  45099. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  45100. /*
  45101. ** Set this global variable to 1 to enable tracing using the TRACE
  45102. ** macro.
  45103. */
  45104. #if 0
  45105. int sqlite3BtreeTrace=1; /* True to enable tracing */
  45106. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  45107. #else
  45108. # define TRACE(X)
  45109. #endif
  45110. /*
  45111. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  45112. ** But if the value is zero, make it 65536.
  45113. **
  45114. ** This routine is used to extract the "offset to cell content area" value
  45115. ** from the header of a btree page. If the page size is 65536 and the page
  45116. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  45117. ** This routine makes the necessary adjustment to 65536.
  45118. */
  45119. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  45120. #ifndef SQLITE_OMIT_SHARED_CACHE
  45121. /*
  45122. ** A list of BtShared objects that are eligible for participation
  45123. ** in shared cache. This variable has file scope during normal builds,
  45124. ** but the test harness needs to access it so we make it global for
  45125. ** test builds.
  45126. **
  45127. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  45128. */
  45129. #ifdef SQLITE_TEST
  45130. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  45131. #else
  45132. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  45133. #endif
  45134. #endif /* SQLITE_OMIT_SHARED_CACHE */
  45135. #ifndef SQLITE_OMIT_SHARED_CACHE
  45136. /*
  45137. ** Enable or disable the shared pager and schema features.
  45138. **
  45139. ** This routine has no effect on existing database connections.
  45140. ** The shared cache setting effects only future calls to
  45141. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  45142. */
  45143. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  45144. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  45145. return SQLITE_OK;
  45146. }
  45147. #endif
  45148. #ifdef SQLITE_OMIT_SHARED_CACHE
  45149. /*
  45150. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  45151. ** and clearAllSharedCacheTableLocks()
  45152. ** manipulate entries in the BtShared.pLock linked list used to store
  45153. ** shared-cache table level locks. If the library is compiled with the
  45154. ** shared-cache feature disabled, then there is only ever one user
  45155. ** of each BtShared structure and so this locking is not necessary.
  45156. ** So define the lock related functions as no-ops.
  45157. */
  45158. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  45159. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  45160. #define clearAllSharedCacheTableLocks(a)
  45161. #define downgradeAllSharedCacheTableLocks(a)
  45162. #define hasSharedCacheTableLock(a,b,c,d) 1
  45163. #define hasReadConflicts(a, b) 0
  45164. #endif
  45165. #ifndef SQLITE_OMIT_SHARED_CACHE
  45166. #ifdef SQLITE_DEBUG
  45167. /*
  45168. **** This function is only used as part of an assert() statement. ***
  45169. **
  45170. ** Check to see if pBtree holds the required locks to read or write to the
  45171. ** table with root page iRoot. Return 1 if it does and 0 if not.
  45172. **
  45173. ** For example, when writing to a table with root-page iRoot via
  45174. ** Btree connection pBtree:
  45175. **
  45176. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  45177. **
  45178. ** When writing to an index that resides in a sharable database, the
  45179. ** caller should have first obtained a lock specifying the root page of
  45180. ** the corresponding table. This makes things a bit more complicated,
  45181. ** as this module treats each table as a separate structure. To determine
  45182. ** the table corresponding to the index being written, this
  45183. ** function has to search through the database schema.
  45184. **
  45185. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  45186. ** hold a write-lock on the schema table (root page 1). This is also
  45187. ** acceptable.
  45188. */
  45189. static int hasSharedCacheTableLock(
  45190. Btree *pBtree, /* Handle that must hold lock */
  45191. Pgno iRoot, /* Root page of b-tree */
  45192. int isIndex, /* True if iRoot is the root of an index b-tree */
  45193. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  45194. ){
  45195. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  45196. Pgno iTab = 0;
  45197. BtLock *pLock;
  45198. /* If this database is not shareable, or if the client is reading
  45199. ** and has the read-uncommitted flag set, then no lock is required.
  45200. ** Return true immediately.
  45201. */
  45202. if( (pBtree->sharable==0)
  45203. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  45204. ){
  45205. return 1;
  45206. }
  45207. /* If the client is reading or writing an index and the schema is
  45208. ** not loaded, then it is too difficult to actually check to see if
  45209. ** the correct locks are held. So do not bother - just return true.
  45210. ** This case does not come up very often anyhow.
  45211. */
  45212. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  45213. return 1;
  45214. }
  45215. /* Figure out the root-page that the lock should be held on. For table
  45216. ** b-trees, this is just the root page of the b-tree being read or
  45217. ** written. For index b-trees, it is the root page of the associated
  45218. ** table. */
  45219. if( isIndex ){
  45220. HashElem *p;
  45221. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  45222. Index *pIdx = (Index *)sqliteHashData(p);
  45223. if( pIdx->tnum==(int)iRoot ){
  45224. iTab = pIdx->pTable->tnum;
  45225. }
  45226. }
  45227. }else{
  45228. iTab = iRoot;
  45229. }
  45230. /* Search for the required lock. Either a write-lock on root-page iTab, a
  45231. ** write-lock on the schema table, or (if the client is reading) a
  45232. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  45233. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  45234. if( pLock->pBtree==pBtree
  45235. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  45236. && pLock->eLock>=eLockType
  45237. ){
  45238. return 1;
  45239. }
  45240. }
  45241. /* Failed to find the required lock. */
  45242. return 0;
  45243. }
  45244. #endif /* SQLITE_DEBUG */
  45245. #ifdef SQLITE_DEBUG
  45246. /*
  45247. **** This function may be used as part of assert() statements only. ****
  45248. **
  45249. ** Return true if it would be illegal for pBtree to write into the
  45250. ** table or index rooted at iRoot because other shared connections are
  45251. ** simultaneously reading that same table or index.
  45252. **
  45253. ** It is illegal for pBtree to write if some other Btree object that
  45254. ** shares the same BtShared object is currently reading or writing
  45255. ** the iRoot table. Except, if the other Btree object has the
  45256. ** read-uncommitted flag set, then it is OK for the other object to
  45257. ** have a read cursor.
  45258. **
  45259. ** For example, before writing to any part of the table or index
  45260. ** rooted at page iRoot, one should call:
  45261. **
  45262. ** assert( !hasReadConflicts(pBtree, iRoot) );
  45263. */
  45264. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  45265. BtCursor *p;
  45266. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  45267. if( p->pgnoRoot==iRoot
  45268. && p->pBtree!=pBtree
  45269. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  45270. ){
  45271. return 1;
  45272. }
  45273. }
  45274. return 0;
  45275. }
  45276. #endif /* #ifdef SQLITE_DEBUG */
  45277. /*
  45278. ** Query to see if Btree handle p may obtain a lock of type eLock
  45279. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  45280. ** SQLITE_OK if the lock may be obtained (by calling
  45281. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  45282. */
  45283. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  45284. BtShared *pBt = p->pBt;
  45285. BtLock *pIter;
  45286. assert( sqlite3BtreeHoldsMutex(p) );
  45287. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  45288. assert( p->db!=0 );
  45289. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  45290. /* If requesting a write-lock, then the Btree must have an open write
  45291. ** transaction on this file. And, obviously, for this to be so there
  45292. ** must be an open write transaction on the file itself.
  45293. */
  45294. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  45295. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  45296. /* This routine is a no-op if the shared-cache is not enabled */
  45297. if( !p->sharable ){
  45298. return SQLITE_OK;
  45299. }
  45300. /* If some other connection is holding an exclusive lock, the
  45301. ** requested lock may not be obtained.
  45302. */
  45303. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  45304. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  45305. return SQLITE_LOCKED_SHAREDCACHE;
  45306. }
  45307. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  45308. /* The condition (pIter->eLock!=eLock) in the following if(...)
  45309. ** statement is a simplification of:
  45310. **
  45311. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  45312. **
  45313. ** since we know that if eLock==WRITE_LOCK, then no other connection
  45314. ** may hold a WRITE_LOCK on any table in this file (since there can
  45315. ** only be a single writer).
  45316. */
  45317. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  45318. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  45319. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  45320. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  45321. if( eLock==WRITE_LOCK ){
  45322. assert( p==pBt->pWriter );
  45323. pBt->btsFlags |= BTS_PENDING;
  45324. }
  45325. return SQLITE_LOCKED_SHAREDCACHE;
  45326. }
  45327. }
  45328. return SQLITE_OK;
  45329. }
  45330. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  45331. #ifndef SQLITE_OMIT_SHARED_CACHE
  45332. /*
  45333. ** Add a lock on the table with root-page iTable to the shared-btree used
  45334. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  45335. ** WRITE_LOCK.
  45336. **
  45337. ** This function assumes the following:
  45338. **
  45339. ** (a) The specified Btree object p is connected to a sharable
  45340. ** database (one with the BtShared.sharable flag set), and
  45341. **
  45342. ** (b) No other Btree objects hold a lock that conflicts
  45343. ** with the requested lock (i.e. querySharedCacheTableLock() has
  45344. ** already been called and returned SQLITE_OK).
  45345. **
  45346. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  45347. ** is returned if a malloc attempt fails.
  45348. */
  45349. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  45350. BtShared *pBt = p->pBt;
  45351. BtLock *pLock = 0;
  45352. BtLock *pIter;
  45353. assert( sqlite3BtreeHoldsMutex(p) );
  45354. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  45355. assert( p->db!=0 );
  45356. /* A connection with the read-uncommitted flag set will never try to
  45357. ** obtain a read-lock using this function. The only read-lock obtained
  45358. ** by a connection in read-uncommitted mode is on the sqlite_master
  45359. ** table, and that lock is obtained in BtreeBeginTrans(). */
  45360. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  45361. /* This function should only be called on a sharable b-tree after it
  45362. ** has been determined that no other b-tree holds a conflicting lock. */
  45363. assert( p->sharable );
  45364. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  45365. /* First search the list for an existing lock on this table. */
  45366. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  45367. if( pIter->iTable==iTable && pIter->pBtree==p ){
  45368. pLock = pIter;
  45369. break;
  45370. }
  45371. }
  45372. /* If the above search did not find a BtLock struct associating Btree p
  45373. ** with table iTable, allocate one and link it into the list.
  45374. */
  45375. if( !pLock ){
  45376. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  45377. if( !pLock ){
  45378. return SQLITE_NOMEM;
  45379. }
  45380. pLock->iTable = iTable;
  45381. pLock->pBtree = p;
  45382. pLock->pNext = pBt->pLock;
  45383. pBt->pLock = pLock;
  45384. }
  45385. /* Set the BtLock.eLock variable to the maximum of the current lock
  45386. ** and the requested lock. This means if a write-lock was already held
  45387. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  45388. */
  45389. assert( WRITE_LOCK>READ_LOCK );
  45390. if( eLock>pLock->eLock ){
  45391. pLock->eLock = eLock;
  45392. }
  45393. return SQLITE_OK;
  45394. }
  45395. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  45396. #ifndef SQLITE_OMIT_SHARED_CACHE
  45397. /*
  45398. ** Release all the table locks (locks obtained via calls to
  45399. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  45400. **
  45401. ** This function assumes that Btree p has an open read or write
  45402. ** transaction. If it does not, then the BTS_PENDING flag
  45403. ** may be incorrectly cleared.
  45404. */
  45405. static void clearAllSharedCacheTableLocks(Btree *p){
  45406. BtShared *pBt = p->pBt;
  45407. BtLock **ppIter = &pBt->pLock;
  45408. assert( sqlite3BtreeHoldsMutex(p) );
  45409. assert( p->sharable || 0==*ppIter );
  45410. assert( p->inTrans>0 );
  45411. while( *ppIter ){
  45412. BtLock *pLock = *ppIter;
  45413. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  45414. assert( pLock->pBtree->inTrans>=pLock->eLock );
  45415. if( pLock->pBtree==p ){
  45416. *ppIter = pLock->pNext;
  45417. assert( pLock->iTable!=1 || pLock==&p->lock );
  45418. if( pLock->iTable!=1 ){
  45419. sqlite3_free(pLock);
  45420. }
  45421. }else{
  45422. ppIter = &pLock->pNext;
  45423. }
  45424. }
  45425. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  45426. if( pBt->pWriter==p ){
  45427. pBt->pWriter = 0;
  45428. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  45429. }else if( pBt->nTransaction==2 ){
  45430. /* This function is called when Btree p is concluding its
  45431. ** transaction. If there currently exists a writer, and p is not
  45432. ** that writer, then the number of locks held by connections other
  45433. ** than the writer must be about to drop to zero. In this case
  45434. ** set the BTS_PENDING flag to 0.
  45435. **
  45436. ** If there is not currently a writer, then BTS_PENDING must
  45437. ** be zero already. So this next line is harmless in that case.
  45438. */
  45439. pBt->btsFlags &= ~BTS_PENDING;
  45440. }
  45441. }
  45442. /*
  45443. ** This function changes all write-locks held by Btree p into read-locks.
  45444. */
  45445. static void downgradeAllSharedCacheTableLocks(Btree *p){
  45446. BtShared *pBt = p->pBt;
  45447. if( pBt->pWriter==p ){
  45448. BtLock *pLock;
  45449. pBt->pWriter = 0;
  45450. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  45451. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  45452. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  45453. pLock->eLock = READ_LOCK;
  45454. }
  45455. }
  45456. }
  45457. #endif /* SQLITE_OMIT_SHARED_CACHE */
  45458. static void releasePage(MemPage *pPage); /* Forward reference */
  45459. /*
  45460. ***** This routine is used inside of assert() only ****
  45461. **
  45462. ** Verify that the cursor holds the mutex on its BtShared
  45463. */
  45464. #ifdef SQLITE_DEBUG
  45465. static int cursorHoldsMutex(BtCursor *p){
  45466. return sqlite3_mutex_held(p->pBt->mutex);
  45467. }
  45468. #endif
  45469. #ifndef SQLITE_OMIT_INCRBLOB
  45470. /*
  45471. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  45472. */
  45473. static void invalidateOverflowCache(BtCursor *pCur){
  45474. assert( cursorHoldsMutex(pCur) );
  45475. sqlite3_free(pCur->aOverflow);
  45476. pCur->aOverflow = 0;
  45477. }
  45478. /*
  45479. ** Invalidate the overflow page-list cache for all cursors opened
  45480. ** on the shared btree structure pBt.
  45481. */
  45482. static void invalidateAllOverflowCache(BtShared *pBt){
  45483. BtCursor *p;
  45484. assert( sqlite3_mutex_held(pBt->mutex) );
  45485. for(p=pBt->pCursor; p; p=p->pNext){
  45486. invalidateOverflowCache(p);
  45487. }
  45488. }
  45489. /*
  45490. ** This function is called before modifying the contents of a table
  45491. ** to invalidate any incrblob cursors that are open on the
  45492. ** row or one of the rows being modified.
  45493. **
  45494. ** If argument isClearTable is true, then the entire contents of the
  45495. ** table is about to be deleted. In this case invalidate all incrblob
  45496. ** cursors open on any row within the table with root-page pgnoRoot.
  45497. **
  45498. ** Otherwise, if argument isClearTable is false, then the row with
  45499. ** rowid iRow is being replaced or deleted. In this case invalidate
  45500. ** only those incrblob cursors open on that specific row.
  45501. */
  45502. static void invalidateIncrblobCursors(
  45503. Btree *pBtree, /* The database file to check */
  45504. i64 iRow, /* The rowid that might be changing */
  45505. int isClearTable /* True if all rows are being deleted */
  45506. ){
  45507. BtCursor *p;
  45508. BtShared *pBt = pBtree->pBt;
  45509. assert( sqlite3BtreeHoldsMutex(pBtree) );
  45510. for(p=pBt->pCursor; p; p=p->pNext){
  45511. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  45512. p->eState = CURSOR_INVALID;
  45513. }
  45514. }
  45515. }
  45516. #else
  45517. /* Stub functions when INCRBLOB is omitted */
  45518. #define invalidateOverflowCache(x)
  45519. #define invalidateAllOverflowCache(x)
  45520. #define invalidateIncrblobCursors(x,y,z)
  45521. #endif /* SQLITE_OMIT_INCRBLOB */
  45522. /*
  45523. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  45524. ** when a page that previously contained data becomes a free-list leaf
  45525. ** page.
  45526. **
  45527. ** The BtShared.pHasContent bitvec exists to work around an obscure
  45528. ** bug caused by the interaction of two useful IO optimizations surrounding
  45529. ** free-list leaf pages:
  45530. **
  45531. ** 1) When all data is deleted from a page and the page becomes
  45532. ** a free-list leaf page, the page is not written to the database
  45533. ** (as free-list leaf pages contain no meaningful data). Sometimes
  45534. ** such a page is not even journalled (as it will not be modified,
  45535. ** why bother journalling it?).
  45536. **
  45537. ** 2) When a free-list leaf page is reused, its content is not read
  45538. ** from the database or written to the journal file (why should it
  45539. ** be, if it is not at all meaningful?).
  45540. **
  45541. ** By themselves, these optimizations work fine and provide a handy
  45542. ** performance boost to bulk delete or insert operations. However, if
  45543. ** a page is moved to the free-list and then reused within the same
  45544. ** transaction, a problem comes up. If the page is not journalled when
  45545. ** it is moved to the free-list and it is also not journalled when it
  45546. ** is extracted from the free-list and reused, then the original data
  45547. ** may be lost. In the event of a rollback, it may not be possible
  45548. ** to restore the database to its original configuration.
  45549. **
  45550. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  45551. ** moved to become a free-list leaf page, the corresponding bit is
  45552. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  45553. ** optimization 2 above is omitted if the corresponding bit is already
  45554. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  45555. ** at the end of every transaction.
  45556. */
  45557. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  45558. int rc = SQLITE_OK;
  45559. if( !pBt->pHasContent ){
  45560. assert( pgno<=pBt->nPage );
  45561. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  45562. if( !pBt->pHasContent ){
  45563. rc = SQLITE_NOMEM;
  45564. }
  45565. }
  45566. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  45567. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  45568. }
  45569. return rc;
  45570. }
  45571. /*
  45572. ** Query the BtShared.pHasContent vector.
  45573. **
  45574. ** This function is called when a free-list leaf page is removed from the
  45575. ** free-list for reuse. It returns false if it is safe to retrieve the
  45576. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  45577. */
  45578. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  45579. Bitvec *p = pBt->pHasContent;
  45580. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  45581. }
  45582. /*
  45583. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  45584. ** invoked at the conclusion of each write-transaction.
  45585. */
  45586. static void btreeClearHasContent(BtShared *pBt){
  45587. sqlite3BitvecDestroy(pBt->pHasContent);
  45588. pBt->pHasContent = 0;
  45589. }
  45590. /*
  45591. ** Save the current cursor position in the variables BtCursor.nKey
  45592. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  45593. **
  45594. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  45595. ** prior to calling this routine.
  45596. */
  45597. static int saveCursorPosition(BtCursor *pCur){
  45598. int rc;
  45599. assert( CURSOR_VALID==pCur->eState );
  45600. assert( 0==pCur->pKey );
  45601. assert( cursorHoldsMutex(pCur) );
  45602. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  45603. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  45604. /* If this is an intKey table, then the above call to BtreeKeySize()
  45605. ** stores the integer key in pCur->nKey. In this case this value is
  45606. ** all that is required. Otherwise, if pCur is not open on an intKey
  45607. ** table, then malloc space for and store the pCur->nKey bytes of key
  45608. ** data.
  45609. */
  45610. if( 0==pCur->apPage[0]->intKey ){
  45611. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  45612. if( pKey ){
  45613. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  45614. if( rc==SQLITE_OK ){
  45615. pCur->pKey = pKey;
  45616. }else{
  45617. sqlite3_free(pKey);
  45618. }
  45619. }else{
  45620. rc = SQLITE_NOMEM;
  45621. }
  45622. }
  45623. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  45624. if( rc==SQLITE_OK ){
  45625. int i;
  45626. for(i=0; i<=pCur->iPage; i++){
  45627. releasePage(pCur->apPage[i]);
  45628. pCur->apPage[i] = 0;
  45629. }
  45630. pCur->iPage = -1;
  45631. pCur->eState = CURSOR_REQUIRESEEK;
  45632. }
  45633. invalidateOverflowCache(pCur);
  45634. return rc;
  45635. }
  45636. /*
  45637. ** Save the positions of all cursors (except pExcept) that are open on
  45638. ** the table with root-page iRoot. Usually, this is called just before cursor
  45639. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  45640. */
  45641. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  45642. BtCursor *p;
  45643. assert( sqlite3_mutex_held(pBt->mutex) );
  45644. assert( pExcept==0 || pExcept->pBt==pBt );
  45645. for(p=pBt->pCursor; p; p=p->pNext){
  45646. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
  45647. p->eState==CURSOR_VALID ){
  45648. int rc = saveCursorPosition(p);
  45649. if( SQLITE_OK!=rc ){
  45650. return rc;
  45651. }
  45652. }
  45653. }
  45654. return SQLITE_OK;
  45655. }
  45656. /*
  45657. ** Clear the current cursor position.
  45658. */
  45659. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  45660. assert( cursorHoldsMutex(pCur) );
  45661. sqlite3_free(pCur->pKey);
  45662. pCur->pKey = 0;
  45663. pCur->eState = CURSOR_INVALID;
  45664. }
  45665. /*
  45666. ** In this version of BtreeMoveto, pKey is a packed index record
  45667. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  45668. ** record and then call BtreeMovetoUnpacked() to do the work.
  45669. */
  45670. static int btreeMoveto(
  45671. BtCursor *pCur, /* Cursor open on the btree to be searched */
  45672. const void *pKey, /* Packed key if the btree is an index */
  45673. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  45674. int bias, /* Bias search to the high end */
  45675. int *pRes /* Write search results here */
  45676. ){
  45677. int rc; /* Status code */
  45678. UnpackedRecord *pIdxKey; /* Unpacked index key */
  45679. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  45680. char *pFree = 0;
  45681. if( pKey ){
  45682. assert( nKey==(i64)(int)nKey );
  45683. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  45684. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  45685. );
  45686. if( pIdxKey==0 ) return SQLITE_NOMEM;
  45687. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  45688. }else{
  45689. pIdxKey = 0;
  45690. }
  45691. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  45692. if( pFree ){
  45693. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  45694. }
  45695. return rc;
  45696. }
  45697. /*
  45698. ** Restore the cursor to the position it was in (or as close to as possible)
  45699. ** when saveCursorPosition() was called. Note that this call deletes the
  45700. ** saved position info stored by saveCursorPosition(), so there can be
  45701. ** at most one effective restoreCursorPosition() call after each
  45702. ** saveCursorPosition().
  45703. */
  45704. static int btreeRestoreCursorPosition(BtCursor *pCur){
  45705. int rc;
  45706. assert( cursorHoldsMutex(pCur) );
  45707. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  45708. if( pCur->eState==CURSOR_FAULT ){
  45709. return pCur->skipNext;
  45710. }
  45711. pCur->eState = CURSOR_INVALID;
  45712. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  45713. if( rc==SQLITE_OK ){
  45714. sqlite3_free(pCur->pKey);
  45715. pCur->pKey = 0;
  45716. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  45717. }
  45718. return rc;
  45719. }
  45720. #define restoreCursorPosition(p) \
  45721. (p->eState>=CURSOR_REQUIRESEEK ? \
  45722. btreeRestoreCursorPosition(p) : \
  45723. SQLITE_OK)
  45724. /*
  45725. ** Determine whether or not a cursor has moved from the position it
  45726. ** was last placed at. Cursors can move when the row they are pointing
  45727. ** at is deleted out from under them.
  45728. **
  45729. ** This routine returns an error code if something goes wrong. The
  45730. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  45731. */
  45732. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  45733. int rc;
  45734. rc = restoreCursorPosition(pCur);
  45735. if( rc ){
  45736. *pHasMoved = 1;
  45737. return rc;
  45738. }
  45739. if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
  45740. *pHasMoved = 1;
  45741. }else{
  45742. *pHasMoved = 0;
  45743. }
  45744. return SQLITE_OK;
  45745. }
  45746. #ifndef SQLITE_OMIT_AUTOVACUUM
  45747. /*
  45748. ** Given a page number of a regular database page, return the page
  45749. ** number for the pointer-map page that contains the entry for the
  45750. ** input page number.
  45751. **
  45752. ** Return 0 (not a valid page) for pgno==1 since there is
  45753. ** no pointer map associated with page 1. The integrity_check logic
  45754. ** requires that ptrmapPageno(*,1)!=1.
  45755. */
  45756. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  45757. int nPagesPerMapPage;
  45758. Pgno iPtrMap, ret;
  45759. assert( sqlite3_mutex_held(pBt->mutex) );
  45760. if( pgno<2 ) return 0;
  45761. nPagesPerMapPage = (pBt->usableSize/5)+1;
  45762. iPtrMap = (pgno-2)/nPagesPerMapPage;
  45763. ret = (iPtrMap*nPagesPerMapPage) + 2;
  45764. if( ret==PENDING_BYTE_PAGE(pBt) ){
  45765. ret++;
  45766. }
  45767. return ret;
  45768. }
  45769. /*
  45770. ** Write an entry into the pointer map.
  45771. **
  45772. ** This routine updates the pointer map entry for page number 'key'
  45773. ** so that it maps to type 'eType' and parent page number 'pgno'.
  45774. **
  45775. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  45776. ** a no-op. If an error occurs, the appropriate error code is written
  45777. ** into *pRC.
  45778. */
  45779. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  45780. DbPage *pDbPage; /* The pointer map page */
  45781. u8 *pPtrmap; /* The pointer map data */
  45782. Pgno iPtrmap; /* The pointer map page number */
  45783. int offset; /* Offset in pointer map page */
  45784. int rc; /* Return code from subfunctions */
  45785. if( *pRC ) return;
  45786. assert( sqlite3_mutex_held(pBt->mutex) );
  45787. /* The master-journal page number must never be used as a pointer map page */
  45788. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  45789. assert( pBt->autoVacuum );
  45790. if( key==0 ){
  45791. *pRC = SQLITE_CORRUPT_BKPT;
  45792. return;
  45793. }
  45794. iPtrmap = PTRMAP_PAGENO(pBt, key);
  45795. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  45796. if( rc!=SQLITE_OK ){
  45797. *pRC = rc;
  45798. return;
  45799. }
  45800. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  45801. if( offset<0 ){
  45802. *pRC = SQLITE_CORRUPT_BKPT;
  45803. goto ptrmap_exit;
  45804. }
  45805. assert( offset <= (int)pBt->usableSize-5 );
  45806. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  45807. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  45808. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  45809. *pRC= rc = sqlite3PagerWrite(pDbPage);
  45810. if( rc==SQLITE_OK ){
  45811. pPtrmap[offset] = eType;
  45812. put4byte(&pPtrmap[offset+1], parent);
  45813. }
  45814. }
  45815. ptrmap_exit:
  45816. sqlite3PagerUnref(pDbPage);
  45817. }
  45818. /*
  45819. ** Read an entry from the pointer map.
  45820. **
  45821. ** This routine retrieves the pointer map entry for page 'key', writing
  45822. ** the type and parent page number to *pEType and *pPgno respectively.
  45823. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  45824. */
  45825. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  45826. DbPage *pDbPage; /* The pointer map page */
  45827. int iPtrmap; /* Pointer map page index */
  45828. u8 *pPtrmap; /* Pointer map page data */
  45829. int offset; /* Offset of entry in pointer map */
  45830. int rc;
  45831. assert( sqlite3_mutex_held(pBt->mutex) );
  45832. iPtrmap = PTRMAP_PAGENO(pBt, key);
  45833. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  45834. if( rc!=0 ){
  45835. return rc;
  45836. }
  45837. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  45838. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  45839. if( offset<0 ){
  45840. sqlite3PagerUnref(pDbPage);
  45841. return SQLITE_CORRUPT_BKPT;
  45842. }
  45843. assert( offset <= (int)pBt->usableSize-5 );
  45844. assert( pEType!=0 );
  45845. *pEType = pPtrmap[offset];
  45846. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  45847. sqlite3PagerUnref(pDbPage);
  45848. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  45849. return SQLITE_OK;
  45850. }
  45851. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  45852. #define ptrmapPut(w,x,y,z,rc)
  45853. #define ptrmapGet(w,x,y,z) SQLITE_OK
  45854. #define ptrmapPutOvflPtr(x, y, rc)
  45855. #endif
  45856. /*
  45857. ** Given a btree page and a cell index (0 means the first cell on
  45858. ** the page, 1 means the second cell, and so forth) return a pointer
  45859. ** to the cell content.
  45860. **
  45861. ** This routine works only for pages that do not contain overflow cells.
  45862. */
  45863. #define findCell(P,I) \
  45864. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  45865. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  45866. /*
  45867. ** This a more complex version of findCell() that works for
  45868. ** pages that do contain overflow cells.
  45869. */
  45870. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  45871. int i;
  45872. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45873. for(i=pPage->nOverflow-1; i>=0; i--){
  45874. int k;
  45875. k = pPage->aiOvfl[i];
  45876. if( k<=iCell ){
  45877. if( k==iCell ){
  45878. return pPage->apOvfl[i];
  45879. }
  45880. iCell--;
  45881. }
  45882. }
  45883. return findCell(pPage, iCell);
  45884. }
  45885. /*
  45886. ** Parse a cell content block and fill in the CellInfo structure. There
  45887. ** are two versions of this function. btreeParseCell() takes a
  45888. ** cell index as the second argument and btreeParseCellPtr()
  45889. ** takes a pointer to the body of the cell as its second argument.
  45890. **
  45891. ** Within this file, the parseCell() macro can be called instead of
  45892. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  45893. */
  45894. static void btreeParseCellPtr(
  45895. MemPage *pPage, /* Page containing the cell */
  45896. u8 *pCell, /* Pointer to the cell text. */
  45897. CellInfo *pInfo /* Fill in this structure */
  45898. ){
  45899. u16 n; /* Number bytes in cell content header */
  45900. u32 nPayload; /* Number of bytes of cell payload */
  45901. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45902. pInfo->pCell = pCell;
  45903. assert( pPage->leaf==0 || pPage->leaf==1 );
  45904. n = pPage->childPtrSize;
  45905. assert( n==4-4*pPage->leaf );
  45906. if( pPage->intKey ){
  45907. if( pPage->hasData ){
  45908. n += getVarint32(&pCell[n], nPayload);
  45909. }else{
  45910. nPayload = 0;
  45911. }
  45912. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  45913. pInfo->nData = nPayload;
  45914. }else{
  45915. pInfo->nData = 0;
  45916. n += getVarint32(&pCell[n], nPayload);
  45917. pInfo->nKey = nPayload;
  45918. }
  45919. pInfo->nPayload = nPayload;
  45920. pInfo->nHeader = n;
  45921. testcase( nPayload==pPage->maxLocal );
  45922. testcase( nPayload==pPage->maxLocal+1 );
  45923. if( likely(nPayload<=pPage->maxLocal) ){
  45924. /* This is the (easy) common case where the entire payload fits
  45925. ** on the local page. No overflow is required.
  45926. */
  45927. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  45928. pInfo->nLocal = (u16)nPayload;
  45929. pInfo->iOverflow = 0;
  45930. }else{
  45931. /* If the payload will not fit completely on the local page, we have
  45932. ** to decide how much to store locally and how much to spill onto
  45933. ** overflow pages. The strategy is to minimize the amount of unused
  45934. ** space on overflow pages while keeping the amount of local storage
  45935. ** in between minLocal and maxLocal.
  45936. **
  45937. ** Warning: changing the way overflow payload is distributed in any
  45938. ** way will result in an incompatible file format.
  45939. */
  45940. int minLocal; /* Minimum amount of payload held locally */
  45941. int maxLocal; /* Maximum amount of payload held locally */
  45942. int surplus; /* Overflow payload available for local storage */
  45943. minLocal = pPage->minLocal;
  45944. maxLocal = pPage->maxLocal;
  45945. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  45946. testcase( surplus==maxLocal );
  45947. testcase( surplus==maxLocal+1 );
  45948. if( surplus <= maxLocal ){
  45949. pInfo->nLocal = (u16)surplus;
  45950. }else{
  45951. pInfo->nLocal = (u16)minLocal;
  45952. }
  45953. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  45954. pInfo->nSize = pInfo->iOverflow + 4;
  45955. }
  45956. }
  45957. #define parseCell(pPage, iCell, pInfo) \
  45958. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  45959. static void btreeParseCell(
  45960. MemPage *pPage, /* Page containing the cell */
  45961. int iCell, /* The cell index. First cell is 0 */
  45962. CellInfo *pInfo /* Fill in this structure */
  45963. ){
  45964. parseCell(pPage, iCell, pInfo);
  45965. }
  45966. /*
  45967. ** Compute the total number of bytes that a Cell needs in the cell
  45968. ** data area of the btree-page. The return number includes the cell
  45969. ** data header and the local payload, but not any overflow page or
  45970. ** the space used by the cell pointer.
  45971. */
  45972. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  45973. u8 *pIter = &pCell[pPage->childPtrSize];
  45974. u32 nSize;
  45975. #ifdef SQLITE_DEBUG
  45976. /* The value returned by this function should always be the same as
  45977. ** the (CellInfo.nSize) value found by doing a full parse of the
  45978. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  45979. ** this function verifies that this invariant is not violated. */
  45980. CellInfo debuginfo;
  45981. btreeParseCellPtr(pPage, pCell, &debuginfo);
  45982. #endif
  45983. if( pPage->intKey ){
  45984. u8 *pEnd;
  45985. if( pPage->hasData ){
  45986. pIter += getVarint32(pIter, nSize);
  45987. }else{
  45988. nSize = 0;
  45989. }
  45990. /* pIter now points at the 64-bit integer key value, a variable length
  45991. ** integer. The following block moves pIter to point at the first byte
  45992. ** past the end of the key value. */
  45993. pEnd = &pIter[9];
  45994. while( (*pIter++)&0x80 && pIter<pEnd );
  45995. }else{
  45996. pIter += getVarint32(pIter, nSize);
  45997. }
  45998. testcase( nSize==pPage->maxLocal );
  45999. testcase( nSize==pPage->maxLocal+1 );
  46000. if( nSize>pPage->maxLocal ){
  46001. int minLocal = pPage->minLocal;
  46002. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  46003. testcase( nSize==pPage->maxLocal );
  46004. testcase( nSize==pPage->maxLocal+1 );
  46005. if( nSize>pPage->maxLocal ){
  46006. nSize = minLocal;
  46007. }
  46008. nSize += 4;
  46009. }
  46010. nSize += (u32)(pIter - pCell);
  46011. /* The minimum size of any cell is 4 bytes. */
  46012. if( nSize<4 ){
  46013. nSize = 4;
  46014. }
  46015. assert( nSize==debuginfo.nSize );
  46016. return (u16)nSize;
  46017. }
  46018. #ifdef SQLITE_DEBUG
  46019. /* This variation on cellSizePtr() is used inside of assert() statements
  46020. ** only. */
  46021. static u16 cellSize(MemPage *pPage, int iCell){
  46022. return cellSizePtr(pPage, findCell(pPage, iCell));
  46023. }
  46024. #endif
  46025. #ifndef SQLITE_OMIT_AUTOVACUUM
  46026. /*
  46027. ** If the cell pCell, part of page pPage contains a pointer
  46028. ** to an overflow page, insert an entry into the pointer-map
  46029. ** for the overflow page.
  46030. */
  46031. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  46032. CellInfo info;
  46033. if( *pRC ) return;
  46034. assert( pCell!=0 );
  46035. btreeParseCellPtr(pPage, pCell, &info);
  46036. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  46037. if( info.iOverflow ){
  46038. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  46039. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  46040. }
  46041. }
  46042. #endif
  46043. /*
  46044. ** Defragment the page given. All Cells are moved to the
  46045. ** end of the page and all free space is collected into one
  46046. ** big FreeBlk that occurs in between the header and cell
  46047. ** pointer array and the cell content area.
  46048. */
  46049. static int defragmentPage(MemPage *pPage){
  46050. int i; /* Loop counter */
  46051. int pc; /* Address of a i-th cell */
  46052. int hdr; /* Offset to the page header */
  46053. int size; /* Size of a cell */
  46054. int usableSize; /* Number of usable bytes on a page */
  46055. int cellOffset; /* Offset to the cell pointer array */
  46056. int cbrk; /* Offset to the cell content area */
  46057. int nCell; /* Number of cells on the page */
  46058. unsigned char *data; /* The page data */
  46059. unsigned char *temp; /* Temp area for cell content */
  46060. int iCellFirst; /* First allowable cell index */
  46061. int iCellLast; /* Last possible cell index */
  46062. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46063. assert( pPage->pBt!=0 );
  46064. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  46065. assert( pPage->nOverflow==0 );
  46066. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46067. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  46068. data = pPage->aData;
  46069. hdr = pPage->hdrOffset;
  46070. cellOffset = pPage->cellOffset;
  46071. nCell = pPage->nCell;
  46072. assert( nCell==get2byte(&data[hdr+3]) );
  46073. usableSize = pPage->pBt->usableSize;
  46074. cbrk = get2byte(&data[hdr+5]);
  46075. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  46076. cbrk = usableSize;
  46077. iCellFirst = cellOffset + 2*nCell;
  46078. iCellLast = usableSize - 4;
  46079. for(i=0; i<nCell; i++){
  46080. u8 *pAddr; /* The i-th cell pointer */
  46081. pAddr = &data[cellOffset + i*2];
  46082. pc = get2byte(pAddr);
  46083. testcase( pc==iCellFirst );
  46084. testcase( pc==iCellLast );
  46085. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  46086. /* These conditions have already been verified in btreeInitPage()
  46087. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  46088. */
  46089. if( pc<iCellFirst || pc>iCellLast ){
  46090. return SQLITE_CORRUPT_BKPT;
  46091. }
  46092. #endif
  46093. assert( pc>=iCellFirst && pc<=iCellLast );
  46094. size = cellSizePtr(pPage, &temp[pc]);
  46095. cbrk -= size;
  46096. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  46097. if( cbrk<iCellFirst ){
  46098. return SQLITE_CORRUPT_BKPT;
  46099. }
  46100. #else
  46101. if( cbrk<iCellFirst || pc+size>usableSize ){
  46102. return SQLITE_CORRUPT_BKPT;
  46103. }
  46104. #endif
  46105. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  46106. testcase( cbrk+size==usableSize );
  46107. testcase( pc+size==usableSize );
  46108. memcpy(&data[cbrk], &temp[pc], size);
  46109. put2byte(pAddr, cbrk);
  46110. }
  46111. assert( cbrk>=iCellFirst );
  46112. put2byte(&data[hdr+5], cbrk);
  46113. data[hdr+1] = 0;
  46114. data[hdr+2] = 0;
  46115. data[hdr+7] = 0;
  46116. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  46117. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46118. if( cbrk-iCellFirst!=pPage->nFree ){
  46119. return SQLITE_CORRUPT_BKPT;
  46120. }
  46121. return SQLITE_OK;
  46122. }
  46123. /*
  46124. ** Allocate nByte bytes of space from within the B-Tree page passed
  46125. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  46126. ** of the first byte of allocated space. Return either SQLITE_OK or
  46127. ** an error code (usually SQLITE_CORRUPT).
  46128. **
  46129. ** The caller guarantees that there is sufficient space to make the
  46130. ** allocation. This routine might need to defragment in order to bring
  46131. ** all the space together, however. This routine will avoid using
  46132. ** the first two bytes past the cell pointer area since presumably this
  46133. ** allocation is being made in order to insert a new cell, so we will
  46134. ** also end up needing a new cell pointer.
  46135. */
  46136. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  46137. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  46138. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  46139. int nFrag; /* Number of fragmented bytes on pPage */
  46140. int top; /* First byte of cell content area */
  46141. int gap; /* First byte of gap between cell pointers and cell content */
  46142. int rc; /* Integer return code */
  46143. int usableSize; /* Usable size of the page */
  46144. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46145. assert( pPage->pBt );
  46146. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46147. assert( nByte>=0 ); /* Minimum cell size is 4 */
  46148. assert( pPage->nFree>=nByte );
  46149. assert( pPage->nOverflow==0 );
  46150. usableSize = pPage->pBt->usableSize;
  46151. assert( nByte < usableSize-8 );
  46152. nFrag = data[hdr+7];
  46153. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  46154. gap = pPage->cellOffset + 2*pPage->nCell;
  46155. top = get2byteNotZero(&data[hdr+5]);
  46156. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  46157. testcase( gap+2==top );
  46158. testcase( gap+1==top );
  46159. testcase( gap==top );
  46160. if( nFrag>=60 ){
  46161. /* Always defragment highly fragmented pages */
  46162. rc = defragmentPage(pPage);
  46163. if( rc ) return rc;
  46164. top = get2byteNotZero(&data[hdr+5]);
  46165. }else if( gap+2<=top ){
  46166. /* Search the freelist looking for a free slot big enough to satisfy
  46167. ** the request. The allocation is made from the first free slot in
  46168. ** the list that is large enough to accomadate it.
  46169. */
  46170. int pc, addr;
  46171. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  46172. int size; /* Size of the free slot */
  46173. if( pc>usableSize-4 || pc<addr+4 ){
  46174. return SQLITE_CORRUPT_BKPT;
  46175. }
  46176. size = get2byte(&data[pc+2]);
  46177. if( size>=nByte ){
  46178. int x = size - nByte;
  46179. testcase( x==4 );
  46180. testcase( x==3 );
  46181. if( x<4 ){
  46182. /* Remove the slot from the free-list. Update the number of
  46183. ** fragmented bytes within the page. */
  46184. memcpy(&data[addr], &data[pc], 2);
  46185. data[hdr+7] = (u8)(nFrag + x);
  46186. }else if( size+pc > usableSize ){
  46187. return SQLITE_CORRUPT_BKPT;
  46188. }else{
  46189. /* The slot remains on the free-list. Reduce its size to account
  46190. ** for the portion used by the new allocation. */
  46191. put2byte(&data[pc+2], x);
  46192. }
  46193. *pIdx = pc + x;
  46194. return SQLITE_OK;
  46195. }
  46196. }
  46197. }
  46198. /* Check to make sure there is enough space in the gap to satisfy
  46199. ** the allocation. If not, defragment.
  46200. */
  46201. testcase( gap+2+nByte==top );
  46202. if( gap+2+nByte>top ){
  46203. rc = defragmentPage(pPage);
  46204. if( rc ) return rc;
  46205. top = get2byteNotZero(&data[hdr+5]);
  46206. assert( gap+nByte<=top );
  46207. }
  46208. /* Allocate memory from the gap in between the cell pointer array
  46209. ** and the cell content area. The btreeInitPage() call has already
  46210. ** validated the freelist. Given that the freelist is valid, there
  46211. ** is no way that the allocation can extend off the end of the page.
  46212. ** The assert() below verifies the previous sentence.
  46213. */
  46214. top -= nByte;
  46215. put2byte(&data[hdr+5], top);
  46216. assert( top+nByte <= (int)pPage->pBt->usableSize );
  46217. *pIdx = top;
  46218. return SQLITE_OK;
  46219. }
  46220. /*
  46221. ** Return a section of the pPage->aData to the freelist.
  46222. ** The first byte of the new free block is pPage->aDisk[start]
  46223. ** and the size of the block is "size" bytes.
  46224. **
  46225. ** Most of the effort here is involved in coalesing adjacent
  46226. ** free blocks into a single big free block.
  46227. */
  46228. static int freeSpace(MemPage *pPage, int start, int size){
  46229. int addr, pbegin, hdr;
  46230. int iLast; /* Largest possible freeblock offset */
  46231. unsigned char *data = pPage->aData;
  46232. assert( pPage->pBt!=0 );
  46233. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46234. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  46235. assert( (start + size) <= (int)pPage->pBt->usableSize );
  46236. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46237. assert( size>=0 ); /* Minimum cell size is 4 */
  46238. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  46239. /* Overwrite deleted information with zeros when the secure_delete
  46240. ** option is enabled */
  46241. memset(&data[start], 0, size);
  46242. }
  46243. /* Add the space back into the linked list of freeblocks. Note that
  46244. ** even though the freeblock list was checked by btreeInitPage(),
  46245. ** btreeInitPage() did not detect overlapping cells or
  46246. ** freeblocks that overlapped cells. Nor does it detect when the
  46247. ** cell content area exceeds the value in the page header. If these
  46248. ** situations arise, then subsequent insert operations might corrupt
  46249. ** the freelist. So we do need to check for corruption while scanning
  46250. ** the freelist.
  46251. */
  46252. hdr = pPage->hdrOffset;
  46253. addr = hdr + 1;
  46254. iLast = pPage->pBt->usableSize - 4;
  46255. assert( start<=iLast );
  46256. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  46257. if( pbegin<addr+4 ){
  46258. return SQLITE_CORRUPT_BKPT;
  46259. }
  46260. addr = pbegin;
  46261. }
  46262. if( pbegin>iLast ){
  46263. return SQLITE_CORRUPT_BKPT;
  46264. }
  46265. assert( pbegin>addr || pbegin==0 );
  46266. put2byte(&data[addr], start);
  46267. put2byte(&data[start], pbegin);
  46268. put2byte(&data[start+2], size);
  46269. pPage->nFree = pPage->nFree + (u16)size;
  46270. /* Coalesce adjacent free blocks */
  46271. addr = hdr + 1;
  46272. while( (pbegin = get2byte(&data[addr]))>0 ){
  46273. int pnext, psize, x;
  46274. assert( pbegin>addr );
  46275. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  46276. pnext = get2byte(&data[pbegin]);
  46277. psize = get2byte(&data[pbegin+2]);
  46278. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  46279. int frag = pnext - (pbegin+psize);
  46280. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  46281. return SQLITE_CORRUPT_BKPT;
  46282. }
  46283. data[hdr+7] -= (u8)frag;
  46284. x = get2byte(&data[pnext]);
  46285. put2byte(&data[pbegin], x);
  46286. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  46287. put2byte(&data[pbegin+2], x);
  46288. }else{
  46289. addr = pbegin;
  46290. }
  46291. }
  46292. /* If the cell content area begins with a freeblock, remove it. */
  46293. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  46294. int top;
  46295. pbegin = get2byte(&data[hdr+1]);
  46296. memcpy(&data[hdr+1], &data[pbegin], 2);
  46297. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  46298. put2byte(&data[hdr+5], top);
  46299. }
  46300. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46301. return SQLITE_OK;
  46302. }
  46303. /*
  46304. ** Decode the flags byte (the first byte of the header) for a page
  46305. ** and initialize fields of the MemPage structure accordingly.
  46306. **
  46307. ** Only the following combinations are supported. Anything different
  46308. ** indicates a corrupt database files:
  46309. **
  46310. ** PTF_ZERODATA
  46311. ** PTF_ZERODATA | PTF_LEAF
  46312. ** PTF_LEAFDATA | PTF_INTKEY
  46313. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  46314. */
  46315. static int decodeFlags(MemPage *pPage, int flagByte){
  46316. BtShared *pBt; /* A copy of pPage->pBt */
  46317. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  46318. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46319. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  46320. flagByte &= ~PTF_LEAF;
  46321. pPage->childPtrSize = 4-4*pPage->leaf;
  46322. pBt = pPage->pBt;
  46323. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  46324. pPage->intKey = 1;
  46325. pPage->hasData = pPage->leaf;
  46326. pPage->maxLocal = pBt->maxLeaf;
  46327. pPage->minLocal = pBt->minLeaf;
  46328. }else if( flagByte==PTF_ZERODATA ){
  46329. pPage->intKey = 0;
  46330. pPage->hasData = 0;
  46331. pPage->maxLocal = pBt->maxLocal;
  46332. pPage->minLocal = pBt->minLocal;
  46333. }else{
  46334. return SQLITE_CORRUPT_BKPT;
  46335. }
  46336. pPage->max1bytePayload = pBt->max1bytePayload;
  46337. return SQLITE_OK;
  46338. }
  46339. /*
  46340. ** Initialize the auxiliary information for a disk block.
  46341. **
  46342. ** Return SQLITE_OK on success. If we see that the page does
  46343. ** not contain a well-formed database page, then return
  46344. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  46345. ** guarantee that the page is well-formed. It only shows that
  46346. ** we failed to detect any corruption.
  46347. */
  46348. static int btreeInitPage(MemPage *pPage){
  46349. assert( pPage->pBt!=0 );
  46350. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46351. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  46352. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  46353. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  46354. if( !pPage->isInit ){
  46355. u16 pc; /* Address of a freeblock within pPage->aData[] */
  46356. u8 hdr; /* Offset to beginning of page header */
  46357. u8 *data; /* Equal to pPage->aData */
  46358. BtShared *pBt; /* The main btree structure */
  46359. int usableSize; /* Amount of usable space on each page */
  46360. u16 cellOffset; /* Offset from start of page to first cell pointer */
  46361. int nFree; /* Number of unused bytes on the page */
  46362. int top; /* First byte of the cell content area */
  46363. int iCellFirst; /* First allowable cell or freeblock offset */
  46364. int iCellLast; /* Last possible cell or freeblock offset */
  46365. pBt = pPage->pBt;
  46366. hdr = pPage->hdrOffset;
  46367. data = pPage->aData;
  46368. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  46369. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  46370. pPage->maskPage = (u16)(pBt->pageSize - 1);
  46371. pPage->nOverflow = 0;
  46372. usableSize = pBt->usableSize;
  46373. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  46374. pPage->aDataEnd = &data[usableSize];
  46375. pPage->aCellIdx = &data[cellOffset];
  46376. top = get2byteNotZero(&data[hdr+5]);
  46377. pPage->nCell = get2byte(&data[hdr+3]);
  46378. if( pPage->nCell>MX_CELL(pBt) ){
  46379. /* To many cells for a single page. The page must be corrupt */
  46380. return SQLITE_CORRUPT_BKPT;
  46381. }
  46382. testcase( pPage->nCell==MX_CELL(pBt) );
  46383. /* A malformed database page might cause us to read past the end
  46384. ** of page when parsing a cell.
  46385. **
  46386. ** The following block of code checks early to see if a cell extends
  46387. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  46388. ** returned if it does.
  46389. */
  46390. iCellFirst = cellOffset + 2*pPage->nCell;
  46391. iCellLast = usableSize - 4;
  46392. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  46393. {
  46394. int i; /* Index into the cell pointer array */
  46395. int sz; /* Size of a cell */
  46396. if( !pPage->leaf ) iCellLast--;
  46397. for(i=0; i<pPage->nCell; i++){
  46398. pc = get2byte(&data[cellOffset+i*2]);
  46399. testcase( pc==iCellFirst );
  46400. testcase( pc==iCellLast );
  46401. if( pc<iCellFirst || pc>iCellLast ){
  46402. return SQLITE_CORRUPT_BKPT;
  46403. }
  46404. sz = cellSizePtr(pPage, &data[pc]);
  46405. testcase( pc+sz==usableSize );
  46406. if( pc+sz>usableSize ){
  46407. return SQLITE_CORRUPT_BKPT;
  46408. }
  46409. }
  46410. if( !pPage->leaf ) iCellLast++;
  46411. }
  46412. #endif
  46413. /* Compute the total free space on the page */
  46414. pc = get2byte(&data[hdr+1]);
  46415. nFree = data[hdr+7] + top;
  46416. while( pc>0 ){
  46417. u16 next, size;
  46418. if( pc<iCellFirst || pc>iCellLast ){
  46419. /* Start of free block is off the page */
  46420. return SQLITE_CORRUPT_BKPT;
  46421. }
  46422. next = get2byte(&data[pc]);
  46423. size = get2byte(&data[pc+2]);
  46424. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  46425. /* Free blocks must be in ascending order. And the last byte of
  46426. ** the free-block must lie on the database page. */
  46427. return SQLITE_CORRUPT_BKPT;
  46428. }
  46429. nFree = nFree + size;
  46430. pc = next;
  46431. }
  46432. /* At this point, nFree contains the sum of the offset to the start
  46433. ** of the cell-content area plus the number of free bytes within
  46434. ** the cell-content area. If this is greater than the usable-size
  46435. ** of the page, then the page must be corrupted. This check also
  46436. ** serves to verify that the offset to the start of the cell-content
  46437. ** area, according to the page header, lies within the page.
  46438. */
  46439. if( nFree>usableSize ){
  46440. return SQLITE_CORRUPT_BKPT;
  46441. }
  46442. pPage->nFree = (u16)(nFree - iCellFirst);
  46443. pPage->isInit = 1;
  46444. }
  46445. return SQLITE_OK;
  46446. }
  46447. /*
  46448. ** Set up a raw page so that it looks like a database page holding
  46449. ** no entries.
  46450. */
  46451. static void zeroPage(MemPage *pPage, int flags){
  46452. unsigned char *data = pPage->aData;
  46453. BtShared *pBt = pPage->pBt;
  46454. u8 hdr = pPage->hdrOffset;
  46455. u16 first;
  46456. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  46457. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  46458. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  46459. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46460. assert( sqlite3_mutex_held(pBt->mutex) );
  46461. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  46462. memset(&data[hdr], 0, pBt->usableSize - hdr);
  46463. }
  46464. data[hdr] = (char)flags;
  46465. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  46466. memset(&data[hdr+1], 0, 4);
  46467. data[hdr+7] = 0;
  46468. put2byte(&data[hdr+5], pBt->usableSize);
  46469. pPage->nFree = (u16)(pBt->usableSize - first);
  46470. decodeFlags(pPage, flags);
  46471. pPage->hdrOffset = hdr;
  46472. pPage->cellOffset = first;
  46473. pPage->aDataEnd = &data[pBt->usableSize];
  46474. pPage->aCellIdx = &data[first];
  46475. pPage->nOverflow = 0;
  46476. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  46477. pPage->maskPage = (u16)(pBt->pageSize - 1);
  46478. pPage->nCell = 0;
  46479. pPage->isInit = 1;
  46480. }
  46481. /*
  46482. ** Convert a DbPage obtained from the pager into a MemPage used by
  46483. ** the btree layer.
  46484. */
  46485. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  46486. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  46487. pPage->aData = sqlite3PagerGetData(pDbPage);
  46488. pPage->pDbPage = pDbPage;
  46489. pPage->pBt = pBt;
  46490. pPage->pgno = pgno;
  46491. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  46492. return pPage;
  46493. }
  46494. /*
  46495. ** Get a page from the pager. Initialize the MemPage.pBt and
  46496. ** MemPage.aData elements if needed.
  46497. **
  46498. ** If the noContent flag is set, it means that we do not care about
  46499. ** the content of the page at this time. So do not go to the disk
  46500. ** to fetch the content. Just fill in the content with zeros for now.
  46501. ** If in the future we call sqlite3PagerWrite() on this page, that
  46502. ** means we have started to be concerned about content and the disk
  46503. ** read should occur at that point.
  46504. */
  46505. static int btreeGetPage(
  46506. BtShared *pBt, /* The btree */
  46507. Pgno pgno, /* Number of the page to fetch */
  46508. MemPage **ppPage, /* Return the page in this parameter */
  46509. int noContent /* Do not load page content if true */
  46510. ){
  46511. int rc;
  46512. DbPage *pDbPage;
  46513. assert( sqlite3_mutex_held(pBt->mutex) );
  46514. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  46515. if( rc ) return rc;
  46516. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  46517. return SQLITE_OK;
  46518. }
  46519. /*
  46520. ** Retrieve a page from the pager cache. If the requested page is not
  46521. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  46522. ** MemPage.aData elements if needed.
  46523. */
  46524. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  46525. DbPage *pDbPage;
  46526. assert( sqlite3_mutex_held(pBt->mutex) );
  46527. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  46528. if( pDbPage ){
  46529. return btreePageFromDbPage(pDbPage, pgno, pBt);
  46530. }
  46531. return 0;
  46532. }
  46533. /*
  46534. ** Return the size of the database file in pages. If there is any kind of
  46535. ** error, return ((unsigned int)-1).
  46536. */
  46537. static Pgno btreePagecount(BtShared *pBt){
  46538. return pBt->nPage;
  46539. }
  46540. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  46541. assert( sqlite3BtreeHoldsMutex(p) );
  46542. assert( ((p->pBt->nPage)&0x8000000)==0 );
  46543. return (int)btreePagecount(p->pBt);
  46544. }
  46545. /*
  46546. ** Get a page from the pager and initialize it. This routine is just a
  46547. ** convenience wrapper around separate calls to btreeGetPage() and
  46548. ** btreeInitPage().
  46549. **
  46550. ** If an error occurs, then the value *ppPage is set to is undefined. It
  46551. ** may remain unchanged, or it may be set to an invalid value.
  46552. */
  46553. static int getAndInitPage(
  46554. BtShared *pBt, /* The database file */
  46555. Pgno pgno, /* Number of the page to get */
  46556. MemPage **ppPage /* Write the page pointer here */
  46557. ){
  46558. int rc;
  46559. assert( sqlite3_mutex_held(pBt->mutex) );
  46560. if( pgno>btreePagecount(pBt) ){
  46561. rc = SQLITE_CORRUPT_BKPT;
  46562. }else{
  46563. rc = btreeGetPage(pBt, pgno, ppPage, 0);
  46564. if( rc==SQLITE_OK ){
  46565. rc = btreeInitPage(*ppPage);
  46566. if( rc!=SQLITE_OK ){
  46567. releasePage(*ppPage);
  46568. }
  46569. }
  46570. }
  46571. testcase( pgno==0 );
  46572. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  46573. return rc;
  46574. }
  46575. /*
  46576. ** Release a MemPage. This should be called once for each prior
  46577. ** call to btreeGetPage.
  46578. */
  46579. static void releasePage(MemPage *pPage){
  46580. if( pPage ){
  46581. assert( pPage->aData );
  46582. assert( pPage->pBt );
  46583. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  46584. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  46585. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46586. sqlite3PagerUnref(pPage->pDbPage);
  46587. }
  46588. }
  46589. /*
  46590. ** During a rollback, when the pager reloads information into the cache
  46591. ** so that the cache is restored to its original state at the start of
  46592. ** the transaction, for each page restored this routine is called.
  46593. **
  46594. ** This routine needs to reset the extra data section at the end of the
  46595. ** page to agree with the restored data.
  46596. */
  46597. static void pageReinit(DbPage *pData){
  46598. MemPage *pPage;
  46599. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  46600. assert( sqlite3PagerPageRefcount(pData)>0 );
  46601. if( pPage->isInit ){
  46602. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46603. pPage->isInit = 0;
  46604. if( sqlite3PagerPageRefcount(pData)>1 ){
  46605. /* pPage might not be a btree page; it might be an overflow page
  46606. ** or ptrmap page or a free page. In those cases, the following
  46607. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  46608. ** But no harm is done by this. And it is very important that
  46609. ** btreeInitPage() be called on every btree page so we make
  46610. ** the call for every page that comes in for re-initing. */
  46611. btreeInitPage(pPage);
  46612. }
  46613. }
  46614. }
  46615. /*
  46616. ** Invoke the busy handler for a btree.
  46617. */
  46618. static int btreeInvokeBusyHandler(void *pArg){
  46619. BtShared *pBt = (BtShared*)pArg;
  46620. assert( pBt->db );
  46621. assert( sqlite3_mutex_held(pBt->db->mutex) );
  46622. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  46623. }
  46624. /*
  46625. ** Open a database file.
  46626. **
  46627. ** zFilename is the name of the database file. If zFilename is NULL
  46628. ** then an ephemeral database is created. The ephemeral database might
  46629. ** be exclusively in memory, or it might use a disk-based memory cache.
  46630. ** Either way, the ephemeral database will be automatically deleted
  46631. ** when sqlite3BtreeClose() is called.
  46632. **
  46633. ** If zFilename is ":memory:" then an in-memory database is created
  46634. ** that is automatically destroyed when it is closed.
  46635. **
  46636. ** The "flags" parameter is a bitmask that might contain bits like
  46637. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  46638. **
  46639. ** If the database is already opened in the same database connection
  46640. ** and we are in shared cache mode, then the open will fail with an
  46641. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  46642. ** objects in the same database connection since doing so will lead
  46643. ** to problems with locking.
  46644. */
  46645. SQLITE_PRIVATE int sqlite3BtreeOpen(
  46646. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  46647. const char *zFilename, /* Name of the file containing the BTree database */
  46648. sqlite3 *db, /* Associated database handle */
  46649. Btree **ppBtree, /* Pointer to new Btree object written here */
  46650. int flags, /* Options */
  46651. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  46652. ){
  46653. BtShared *pBt = 0; /* Shared part of btree structure */
  46654. Btree *p; /* Handle to return */
  46655. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  46656. int rc = SQLITE_OK; /* Result code from this function */
  46657. u8 nReserve; /* Byte of unused space on each page */
  46658. unsigned char zDbHeader[100]; /* Database header content */
  46659. /* True if opening an ephemeral, temporary database */
  46660. const int isTempDb = zFilename==0 || zFilename[0]==0;
  46661. /* Set the variable isMemdb to true for an in-memory database, or
  46662. ** false for a file-based database.
  46663. */
  46664. #ifdef SQLITE_OMIT_MEMORYDB
  46665. const int isMemdb = 0;
  46666. #else
  46667. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  46668. || (isTempDb && sqlite3TempInMemory(db))
  46669. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  46670. #endif
  46671. assert( db!=0 );
  46672. assert( pVfs!=0 );
  46673. assert( sqlite3_mutex_held(db->mutex) );
  46674. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  46675. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  46676. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  46677. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  46678. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  46679. if( isMemdb ){
  46680. flags |= BTREE_MEMORY;
  46681. }
  46682. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  46683. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  46684. }
  46685. p = sqlite3MallocZero(sizeof(Btree));
  46686. if( !p ){
  46687. return SQLITE_NOMEM;
  46688. }
  46689. p->inTrans = TRANS_NONE;
  46690. p->db = db;
  46691. #ifndef SQLITE_OMIT_SHARED_CACHE
  46692. p->lock.pBtree = p;
  46693. p->lock.iTable = 1;
  46694. #endif
  46695. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  46696. /*
  46697. ** If this Btree is a candidate for shared cache, try to find an
  46698. ** existing BtShared object that we can share with
  46699. */
  46700. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  46701. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  46702. int nFullPathname = pVfs->mxPathname+1;
  46703. char *zFullPathname = sqlite3Malloc(nFullPathname);
  46704. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  46705. p->sharable = 1;
  46706. if( !zFullPathname ){
  46707. sqlite3_free(p);
  46708. return SQLITE_NOMEM;
  46709. }
  46710. if( isMemdb ){
  46711. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  46712. }else{
  46713. rc = sqlite3OsFullPathname(pVfs, zFilename,
  46714. nFullPathname, zFullPathname);
  46715. if( rc ){
  46716. sqlite3_free(zFullPathname);
  46717. sqlite3_free(p);
  46718. return rc;
  46719. }
  46720. }
  46721. #if SQLITE_THREADSAFE
  46722. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  46723. sqlite3_mutex_enter(mutexOpen);
  46724. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  46725. sqlite3_mutex_enter(mutexShared);
  46726. #endif
  46727. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  46728. assert( pBt->nRef>0 );
  46729. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  46730. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  46731. int iDb;
  46732. for(iDb=db->nDb-1; iDb>=0; iDb--){
  46733. Btree *pExisting = db->aDb[iDb].pBt;
  46734. if( pExisting && pExisting->pBt==pBt ){
  46735. sqlite3_mutex_leave(mutexShared);
  46736. sqlite3_mutex_leave(mutexOpen);
  46737. sqlite3_free(zFullPathname);
  46738. sqlite3_free(p);
  46739. return SQLITE_CONSTRAINT;
  46740. }
  46741. }
  46742. p->pBt = pBt;
  46743. pBt->nRef++;
  46744. break;
  46745. }
  46746. }
  46747. sqlite3_mutex_leave(mutexShared);
  46748. sqlite3_free(zFullPathname);
  46749. }
  46750. #ifdef SQLITE_DEBUG
  46751. else{
  46752. /* In debug mode, we mark all persistent databases as sharable
  46753. ** even when they are not. This exercises the locking code and
  46754. ** gives more opportunity for asserts(sqlite3_mutex_held())
  46755. ** statements to find locking problems.
  46756. */
  46757. p->sharable = 1;
  46758. }
  46759. #endif
  46760. }
  46761. #endif
  46762. if( pBt==0 ){
  46763. /*
  46764. ** The following asserts make sure that structures used by the btree are
  46765. ** the right size. This is to guard against size changes that result
  46766. ** when compiling on a different architecture.
  46767. */
  46768. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  46769. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  46770. assert( sizeof(u32)==4 );
  46771. assert( sizeof(u16)==2 );
  46772. assert( sizeof(Pgno)==4 );
  46773. pBt = sqlite3MallocZero( sizeof(*pBt) );
  46774. if( pBt==0 ){
  46775. rc = SQLITE_NOMEM;
  46776. goto btree_open_out;
  46777. }
  46778. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  46779. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  46780. if( rc==SQLITE_OK ){
  46781. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  46782. }
  46783. if( rc!=SQLITE_OK ){
  46784. goto btree_open_out;
  46785. }
  46786. pBt->openFlags = (u8)flags;
  46787. pBt->db = db;
  46788. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  46789. p->pBt = pBt;
  46790. pBt->pCursor = 0;
  46791. pBt->pPage1 = 0;
  46792. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  46793. #ifdef SQLITE_SECURE_DELETE
  46794. pBt->btsFlags |= BTS_SECURE_DELETE;
  46795. #endif
  46796. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  46797. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  46798. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  46799. pBt->pageSize = 0;
  46800. #ifndef SQLITE_OMIT_AUTOVACUUM
  46801. /* If the magic name ":memory:" will create an in-memory database, then
  46802. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  46803. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  46804. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  46805. ** regular file-name. In this case the auto-vacuum applies as per normal.
  46806. */
  46807. if( zFilename && !isMemdb ){
  46808. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  46809. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  46810. }
  46811. #endif
  46812. nReserve = 0;
  46813. }else{
  46814. nReserve = zDbHeader[20];
  46815. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  46816. #ifndef SQLITE_OMIT_AUTOVACUUM
  46817. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  46818. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  46819. #endif
  46820. }
  46821. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  46822. if( rc ) goto btree_open_out;
  46823. pBt->usableSize = pBt->pageSize - nReserve;
  46824. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  46825. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  46826. /* Add the new BtShared object to the linked list sharable BtShareds.
  46827. */
  46828. if( p->sharable ){
  46829. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  46830. pBt->nRef = 1;
  46831. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  46832. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  46833. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  46834. if( pBt->mutex==0 ){
  46835. rc = SQLITE_NOMEM;
  46836. db->mallocFailed = 0;
  46837. goto btree_open_out;
  46838. }
  46839. }
  46840. sqlite3_mutex_enter(mutexShared);
  46841. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  46842. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  46843. sqlite3_mutex_leave(mutexShared);
  46844. }
  46845. #endif
  46846. }
  46847. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  46848. /* If the new Btree uses a sharable pBtShared, then link the new
  46849. ** Btree into the list of all sharable Btrees for the same connection.
  46850. ** The list is kept in ascending order by pBt address.
  46851. */
  46852. if( p->sharable ){
  46853. int i;
  46854. Btree *pSib;
  46855. for(i=0; i<db->nDb; i++){
  46856. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  46857. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  46858. if( p->pBt<pSib->pBt ){
  46859. p->pNext = pSib;
  46860. p->pPrev = 0;
  46861. pSib->pPrev = p;
  46862. }else{
  46863. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  46864. pSib = pSib->pNext;
  46865. }
  46866. p->pNext = pSib->pNext;
  46867. p->pPrev = pSib;
  46868. if( p->pNext ){
  46869. p->pNext->pPrev = p;
  46870. }
  46871. pSib->pNext = p;
  46872. }
  46873. break;
  46874. }
  46875. }
  46876. }
  46877. #endif
  46878. *ppBtree = p;
  46879. btree_open_out:
  46880. if( rc!=SQLITE_OK ){
  46881. if( pBt && pBt->pPager ){
  46882. sqlite3PagerClose(pBt->pPager);
  46883. }
  46884. sqlite3_free(pBt);
  46885. sqlite3_free(p);
  46886. *ppBtree = 0;
  46887. }else{
  46888. /* If the B-Tree was successfully opened, set the pager-cache size to the
  46889. ** default value. Except, when opening on an existing shared pager-cache,
  46890. ** do not change the pager-cache size.
  46891. */
  46892. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  46893. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  46894. }
  46895. }
  46896. if( mutexOpen ){
  46897. assert( sqlite3_mutex_held(mutexOpen) );
  46898. sqlite3_mutex_leave(mutexOpen);
  46899. }
  46900. return rc;
  46901. }
  46902. /*
  46903. ** Decrement the BtShared.nRef counter. When it reaches zero,
  46904. ** remove the BtShared structure from the sharing list. Return
  46905. ** true if the BtShared.nRef counter reaches zero and return
  46906. ** false if it is still positive.
  46907. */
  46908. static int removeFromSharingList(BtShared *pBt){
  46909. #ifndef SQLITE_OMIT_SHARED_CACHE
  46910. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  46911. BtShared *pList;
  46912. int removed = 0;
  46913. assert( sqlite3_mutex_notheld(pBt->mutex) );
  46914. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  46915. sqlite3_mutex_enter(pMaster);
  46916. pBt->nRef--;
  46917. if( pBt->nRef<=0 ){
  46918. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  46919. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  46920. }else{
  46921. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  46922. while( ALWAYS(pList) && pList->pNext!=pBt ){
  46923. pList=pList->pNext;
  46924. }
  46925. if( ALWAYS(pList) ){
  46926. pList->pNext = pBt->pNext;
  46927. }
  46928. }
  46929. if( SQLITE_THREADSAFE ){
  46930. sqlite3_mutex_free(pBt->mutex);
  46931. }
  46932. removed = 1;
  46933. }
  46934. sqlite3_mutex_leave(pMaster);
  46935. return removed;
  46936. #else
  46937. return 1;
  46938. #endif
  46939. }
  46940. /*
  46941. ** Make sure pBt->pTmpSpace points to an allocation of
  46942. ** MX_CELL_SIZE(pBt) bytes.
  46943. */
  46944. static void allocateTempSpace(BtShared *pBt){
  46945. if( !pBt->pTmpSpace ){
  46946. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  46947. }
  46948. }
  46949. /*
  46950. ** Free the pBt->pTmpSpace allocation
  46951. */
  46952. static void freeTempSpace(BtShared *pBt){
  46953. sqlite3PageFree( pBt->pTmpSpace);
  46954. pBt->pTmpSpace = 0;
  46955. }
  46956. /*
  46957. ** Close an open database and invalidate all cursors.
  46958. */
  46959. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  46960. BtShared *pBt = p->pBt;
  46961. BtCursor *pCur;
  46962. /* Close all cursors opened via this handle. */
  46963. assert( sqlite3_mutex_held(p->db->mutex) );
  46964. sqlite3BtreeEnter(p);
  46965. pCur = pBt->pCursor;
  46966. while( pCur ){
  46967. BtCursor *pTmp = pCur;
  46968. pCur = pCur->pNext;
  46969. if( pTmp->pBtree==p ){
  46970. sqlite3BtreeCloseCursor(pTmp);
  46971. }
  46972. }
  46973. /* Rollback any active transaction and free the handle structure.
  46974. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  46975. ** this handle.
  46976. */
  46977. sqlite3BtreeRollback(p, SQLITE_OK);
  46978. sqlite3BtreeLeave(p);
  46979. /* If there are still other outstanding references to the shared-btree
  46980. ** structure, return now. The remainder of this procedure cleans
  46981. ** up the shared-btree.
  46982. */
  46983. assert( p->wantToLock==0 && p->locked==0 );
  46984. if( !p->sharable || removeFromSharingList(pBt) ){
  46985. /* The pBt is no longer on the sharing list, so we can access
  46986. ** it without having to hold the mutex.
  46987. **
  46988. ** Clean out and delete the BtShared object.
  46989. */
  46990. assert( !pBt->pCursor );
  46991. sqlite3PagerClose(pBt->pPager);
  46992. if( pBt->xFreeSchema && pBt->pSchema ){
  46993. pBt->xFreeSchema(pBt->pSchema);
  46994. }
  46995. sqlite3DbFree(0, pBt->pSchema);
  46996. freeTempSpace(pBt);
  46997. sqlite3_free(pBt);
  46998. }
  46999. #ifndef SQLITE_OMIT_SHARED_CACHE
  47000. assert( p->wantToLock==0 );
  47001. assert( p->locked==0 );
  47002. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  47003. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  47004. #endif
  47005. sqlite3_free(p);
  47006. return SQLITE_OK;
  47007. }
  47008. /*
  47009. ** Change the limit on the number of pages allowed in the cache.
  47010. **
  47011. ** The maximum number of cache pages is set to the absolute
  47012. ** value of mxPage. If mxPage is negative, the pager will
  47013. ** operate asynchronously - it will not stop to do fsync()s
  47014. ** to insure data is written to the disk surface before
  47015. ** continuing. Transactions still work if synchronous is off,
  47016. ** and the database cannot be corrupted if this program
  47017. ** crashes. But if the operating system crashes or there is
  47018. ** an abrupt power failure when synchronous is off, the database
  47019. ** could be left in an inconsistent and unrecoverable state.
  47020. ** Synchronous is on by default so database corruption is not
  47021. ** normally a worry.
  47022. */
  47023. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  47024. BtShared *pBt = p->pBt;
  47025. assert( sqlite3_mutex_held(p->db->mutex) );
  47026. sqlite3BtreeEnter(p);
  47027. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  47028. sqlite3BtreeLeave(p);
  47029. return SQLITE_OK;
  47030. }
  47031. /*
  47032. ** Change the way data is synced to disk in order to increase or decrease
  47033. ** how well the database resists damage due to OS crashes and power
  47034. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  47035. ** there is a high probability of damage) Level 2 is the default. There
  47036. ** is a very low but non-zero probability of damage. Level 3 reduces the
  47037. ** probability of damage to near zero but with a write performance reduction.
  47038. */
  47039. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  47040. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
  47041. Btree *p, /* The btree to set the safety level on */
  47042. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  47043. int fullSync, /* PRAGMA fullfsync. */
  47044. int ckptFullSync /* PRAGMA checkpoint_fullfync */
  47045. ){
  47046. BtShared *pBt = p->pBt;
  47047. assert( sqlite3_mutex_held(p->db->mutex) );
  47048. assert( level>=1 && level<=3 );
  47049. sqlite3BtreeEnter(p);
  47050. sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
  47051. sqlite3BtreeLeave(p);
  47052. return SQLITE_OK;
  47053. }
  47054. #endif
  47055. /*
  47056. ** Return TRUE if the given btree is set to safety level 1. In other
  47057. ** words, return TRUE if no sync() occurs on the disk files.
  47058. */
  47059. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  47060. BtShared *pBt = p->pBt;
  47061. int rc;
  47062. assert( sqlite3_mutex_held(p->db->mutex) );
  47063. sqlite3BtreeEnter(p);
  47064. assert( pBt && pBt->pPager );
  47065. rc = sqlite3PagerNosync(pBt->pPager);
  47066. sqlite3BtreeLeave(p);
  47067. return rc;
  47068. }
  47069. /*
  47070. ** Change the default pages size and the number of reserved bytes per page.
  47071. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  47072. ** without changing anything.
  47073. **
  47074. ** The page size must be a power of 2 between 512 and 65536. If the page
  47075. ** size supplied does not meet this constraint then the page size is not
  47076. ** changed.
  47077. **
  47078. ** Page sizes are constrained to be a power of two so that the region
  47079. ** of the database file used for locking (beginning at PENDING_BYTE,
  47080. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  47081. ** at the beginning of a page.
  47082. **
  47083. ** If parameter nReserve is less than zero, then the number of reserved
  47084. ** bytes per page is left unchanged.
  47085. **
  47086. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  47087. ** and autovacuum mode can no longer be changed.
  47088. */
  47089. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  47090. int rc = SQLITE_OK;
  47091. BtShared *pBt = p->pBt;
  47092. assert( nReserve>=-1 && nReserve<=255 );
  47093. sqlite3BtreeEnter(p);
  47094. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  47095. sqlite3BtreeLeave(p);
  47096. return SQLITE_READONLY;
  47097. }
  47098. if( nReserve<0 ){
  47099. nReserve = pBt->pageSize - pBt->usableSize;
  47100. }
  47101. assert( nReserve>=0 && nReserve<=255 );
  47102. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  47103. ((pageSize-1)&pageSize)==0 ){
  47104. assert( (pageSize & 7)==0 );
  47105. assert( !pBt->pPage1 && !pBt->pCursor );
  47106. pBt->pageSize = (u32)pageSize;
  47107. freeTempSpace(pBt);
  47108. }
  47109. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  47110. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  47111. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  47112. sqlite3BtreeLeave(p);
  47113. return rc;
  47114. }
  47115. /*
  47116. ** Return the currently defined page size
  47117. */
  47118. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  47119. return p->pBt->pageSize;
  47120. }
  47121. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  47122. /*
  47123. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  47124. ** may only be called if it is guaranteed that the b-tree mutex is already
  47125. ** held.
  47126. **
  47127. ** This is useful in one special case in the backup API code where it is
  47128. ** known that the shared b-tree mutex is held, but the mutex on the
  47129. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  47130. ** were to be called, it might collide with some other operation on the
  47131. ** database handle that owns *p, causing undefined behaviour.
  47132. */
  47133. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  47134. assert( sqlite3_mutex_held(p->pBt->mutex) );
  47135. return p->pBt->pageSize - p->pBt->usableSize;
  47136. }
  47137. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  47138. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  47139. /*
  47140. ** Return the number of bytes of space at the end of every page that
  47141. ** are intentually left unused. This is the "reserved" space that is
  47142. ** sometimes used by extensions.
  47143. */
  47144. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  47145. int n;
  47146. sqlite3BtreeEnter(p);
  47147. n = p->pBt->pageSize - p->pBt->usableSize;
  47148. sqlite3BtreeLeave(p);
  47149. return n;
  47150. }
  47151. /*
  47152. ** Set the maximum page count for a database if mxPage is positive.
  47153. ** No changes are made if mxPage is 0 or negative.
  47154. ** Regardless of the value of mxPage, return the maximum page count.
  47155. */
  47156. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  47157. int n;
  47158. sqlite3BtreeEnter(p);
  47159. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  47160. sqlite3BtreeLeave(p);
  47161. return n;
  47162. }
  47163. /*
  47164. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  47165. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  47166. ** setting after the change.
  47167. */
  47168. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  47169. int b;
  47170. if( p==0 ) return 0;
  47171. sqlite3BtreeEnter(p);
  47172. if( newFlag>=0 ){
  47173. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  47174. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  47175. }
  47176. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  47177. sqlite3BtreeLeave(p);
  47178. return b;
  47179. }
  47180. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  47181. /*
  47182. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  47183. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  47184. ** is disabled. The default value for the auto-vacuum property is
  47185. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  47186. */
  47187. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  47188. #ifdef SQLITE_OMIT_AUTOVACUUM
  47189. return SQLITE_READONLY;
  47190. #else
  47191. BtShared *pBt = p->pBt;
  47192. int rc = SQLITE_OK;
  47193. u8 av = (u8)autoVacuum;
  47194. sqlite3BtreeEnter(p);
  47195. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  47196. rc = SQLITE_READONLY;
  47197. }else{
  47198. pBt->autoVacuum = av ?1:0;
  47199. pBt->incrVacuum = av==2 ?1:0;
  47200. }
  47201. sqlite3BtreeLeave(p);
  47202. return rc;
  47203. #endif
  47204. }
  47205. /*
  47206. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  47207. ** enabled 1 is returned. Otherwise 0.
  47208. */
  47209. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  47210. #ifdef SQLITE_OMIT_AUTOVACUUM
  47211. return BTREE_AUTOVACUUM_NONE;
  47212. #else
  47213. int rc;
  47214. sqlite3BtreeEnter(p);
  47215. rc = (
  47216. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  47217. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  47218. BTREE_AUTOVACUUM_INCR
  47219. );
  47220. sqlite3BtreeLeave(p);
  47221. return rc;
  47222. #endif
  47223. }
  47224. /*
  47225. ** Get a reference to pPage1 of the database file. This will
  47226. ** also acquire a readlock on that file.
  47227. **
  47228. ** SQLITE_OK is returned on success. If the file is not a
  47229. ** well-formed database file, then SQLITE_CORRUPT is returned.
  47230. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  47231. ** is returned if we run out of memory.
  47232. */
  47233. static int lockBtree(BtShared *pBt){
  47234. int rc; /* Result code from subfunctions */
  47235. MemPage *pPage1; /* Page 1 of the database file */
  47236. int nPage; /* Number of pages in the database */
  47237. int nPageFile = 0; /* Number of pages in the database file */
  47238. int nPageHeader; /* Number of pages in the database according to hdr */
  47239. assert( sqlite3_mutex_held(pBt->mutex) );
  47240. assert( pBt->pPage1==0 );
  47241. rc = sqlite3PagerSharedLock(pBt->pPager);
  47242. if( rc!=SQLITE_OK ) return rc;
  47243. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  47244. if( rc!=SQLITE_OK ) return rc;
  47245. /* Do some checking to help insure the file we opened really is
  47246. ** a valid database file.
  47247. */
  47248. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  47249. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  47250. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  47251. nPage = nPageFile;
  47252. }
  47253. if( nPage>0 ){
  47254. u32 pageSize;
  47255. u32 usableSize;
  47256. u8 *page1 = pPage1->aData;
  47257. rc = SQLITE_NOTADB;
  47258. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  47259. goto page1_init_failed;
  47260. }
  47261. #ifdef SQLITE_OMIT_WAL
  47262. if( page1[18]>1 ){
  47263. pBt->btsFlags |= BTS_READ_ONLY;
  47264. }
  47265. if( page1[19]>1 ){
  47266. goto page1_init_failed;
  47267. }
  47268. #else
  47269. if( page1[18]>2 ){
  47270. pBt->btsFlags |= BTS_READ_ONLY;
  47271. }
  47272. if( page1[19]>2 ){
  47273. goto page1_init_failed;
  47274. }
  47275. /* If the write version is set to 2, this database should be accessed
  47276. ** in WAL mode. If the log is not already open, open it now. Then
  47277. ** return SQLITE_OK and return without populating BtShared.pPage1.
  47278. ** The caller detects this and calls this function again. This is
  47279. ** required as the version of page 1 currently in the page1 buffer
  47280. ** may not be the latest version - there may be a newer one in the log
  47281. ** file.
  47282. */
  47283. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  47284. int isOpen = 0;
  47285. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  47286. if( rc!=SQLITE_OK ){
  47287. goto page1_init_failed;
  47288. }else if( isOpen==0 ){
  47289. releasePage(pPage1);
  47290. return SQLITE_OK;
  47291. }
  47292. rc = SQLITE_NOTADB;
  47293. }
  47294. #endif
  47295. /* The maximum embedded fraction must be exactly 25%. And the minimum
  47296. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  47297. ** The original design allowed these amounts to vary, but as of
  47298. ** version 3.6.0, we require them to be fixed.
  47299. */
  47300. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  47301. goto page1_init_failed;
  47302. }
  47303. pageSize = (page1[16]<<8) | (page1[17]<<16);
  47304. if( ((pageSize-1)&pageSize)!=0
  47305. || pageSize>SQLITE_MAX_PAGE_SIZE
  47306. || pageSize<=256
  47307. ){
  47308. goto page1_init_failed;
  47309. }
  47310. assert( (pageSize & 7)==0 );
  47311. usableSize = pageSize - page1[20];
  47312. if( (u32)pageSize!=pBt->pageSize ){
  47313. /* After reading the first page of the database assuming a page size
  47314. ** of BtShared.pageSize, we have discovered that the page-size is
  47315. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  47316. ** zero and return SQLITE_OK. The caller will call this function
  47317. ** again with the correct page-size.
  47318. */
  47319. releasePage(pPage1);
  47320. pBt->usableSize = usableSize;
  47321. pBt->pageSize = pageSize;
  47322. freeTempSpace(pBt);
  47323. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  47324. pageSize-usableSize);
  47325. return rc;
  47326. }
  47327. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  47328. rc = SQLITE_CORRUPT_BKPT;
  47329. goto page1_init_failed;
  47330. }
  47331. if( usableSize<480 ){
  47332. goto page1_init_failed;
  47333. }
  47334. pBt->pageSize = pageSize;
  47335. pBt->usableSize = usableSize;
  47336. #ifndef SQLITE_OMIT_AUTOVACUUM
  47337. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  47338. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  47339. #endif
  47340. }
  47341. /* maxLocal is the maximum amount of payload to store locally for
  47342. ** a cell. Make sure it is small enough so that at least minFanout
  47343. ** cells can will fit on one page. We assume a 10-byte page header.
  47344. ** Besides the payload, the cell must store:
  47345. ** 2-byte pointer to the cell
  47346. ** 4-byte child pointer
  47347. ** 9-byte nKey value
  47348. ** 4-byte nData value
  47349. ** 4-byte overflow page pointer
  47350. ** So a cell consists of a 2-byte pointer, a header which is as much as
  47351. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  47352. ** page pointer.
  47353. */
  47354. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  47355. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  47356. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  47357. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  47358. if( pBt->maxLocal>127 ){
  47359. pBt->max1bytePayload = 127;
  47360. }else{
  47361. pBt->max1bytePayload = (u8)pBt->maxLocal;
  47362. }
  47363. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  47364. pBt->pPage1 = pPage1;
  47365. pBt->nPage = nPage;
  47366. return SQLITE_OK;
  47367. page1_init_failed:
  47368. releasePage(pPage1);
  47369. pBt->pPage1 = 0;
  47370. return rc;
  47371. }
  47372. /*
  47373. ** If there are no outstanding cursors and we are not in the middle
  47374. ** of a transaction but there is a read lock on the database, then
  47375. ** this routine unrefs the first page of the database file which
  47376. ** has the effect of releasing the read lock.
  47377. **
  47378. ** If there is a transaction in progress, this routine is a no-op.
  47379. */
  47380. static void unlockBtreeIfUnused(BtShared *pBt){
  47381. assert( sqlite3_mutex_held(pBt->mutex) );
  47382. assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
  47383. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  47384. assert( pBt->pPage1->aData );
  47385. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  47386. assert( pBt->pPage1->aData );
  47387. releasePage(pBt->pPage1);
  47388. pBt->pPage1 = 0;
  47389. }
  47390. }
  47391. /*
  47392. ** If pBt points to an empty file then convert that empty file
  47393. ** into a new empty database by initializing the first page of
  47394. ** the database.
  47395. */
  47396. static int newDatabase(BtShared *pBt){
  47397. MemPage *pP1;
  47398. unsigned char *data;
  47399. int rc;
  47400. assert( sqlite3_mutex_held(pBt->mutex) );
  47401. if( pBt->nPage>0 ){
  47402. return SQLITE_OK;
  47403. }
  47404. pP1 = pBt->pPage1;
  47405. assert( pP1!=0 );
  47406. data = pP1->aData;
  47407. rc = sqlite3PagerWrite(pP1->pDbPage);
  47408. if( rc ) return rc;
  47409. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  47410. assert( sizeof(zMagicHeader)==16 );
  47411. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  47412. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  47413. data[18] = 1;
  47414. data[19] = 1;
  47415. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  47416. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  47417. data[21] = 64;
  47418. data[22] = 32;
  47419. data[23] = 32;
  47420. memset(&data[24], 0, 100-24);
  47421. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  47422. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  47423. #ifndef SQLITE_OMIT_AUTOVACUUM
  47424. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  47425. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  47426. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  47427. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  47428. #endif
  47429. pBt->nPage = 1;
  47430. data[31] = 1;
  47431. return SQLITE_OK;
  47432. }
  47433. /*
  47434. ** Initialize the first page of the database file (creating a database
  47435. ** consisting of a single page and no schema objects). Return SQLITE_OK
  47436. ** if successful, or an SQLite error code otherwise.
  47437. */
  47438. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  47439. int rc;
  47440. sqlite3BtreeEnter(p);
  47441. p->pBt->nPage = 0;
  47442. rc = newDatabase(p->pBt);
  47443. sqlite3BtreeLeave(p);
  47444. return rc;
  47445. }
  47446. /*
  47447. ** Attempt to start a new transaction. A write-transaction
  47448. ** is started if the second argument is nonzero, otherwise a read-
  47449. ** transaction. If the second argument is 2 or more and exclusive
  47450. ** transaction is started, meaning that no other process is allowed
  47451. ** to access the database. A preexisting transaction may not be
  47452. ** upgraded to exclusive by calling this routine a second time - the
  47453. ** exclusivity flag only works for a new transaction.
  47454. **
  47455. ** A write-transaction must be started before attempting any
  47456. ** changes to the database. None of the following routines
  47457. ** will work unless a transaction is started first:
  47458. **
  47459. ** sqlite3BtreeCreateTable()
  47460. ** sqlite3BtreeCreateIndex()
  47461. ** sqlite3BtreeClearTable()
  47462. ** sqlite3BtreeDropTable()
  47463. ** sqlite3BtreeInsert()
  47464. ** sqlite3BtreeDelete()
  47465. ** sqlite3BtreeUpdateMeta()
  47466. **
  47467. ** If an initial attempt to acquire the lock fails because of lock contention
  47468. ** and the database was previously unlocked, then invoke the busy handler
  47469. ** if there is one. But if there was previously a read-lock, do not
  47470. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  47471. ** returned when there is already a read-lock in order to avoid a deadlock.
  47472. **
  47473. ** Suppose there are two processes A and B. A has a read lock and B has
  47474. ** a reserved lock. B tries to promote to exclusive but is blocked because
  47475. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  47476. ** One or the other of the two processes must give way or there can be
  47477. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  47478. ** when A already has a read lock, we encourage A to give up and let B
  47479. ** proceed.
  47480. */
  47481. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  47482. sqlite3 *pBlock = 0;
  47483. BtShared *pBt = p->pBt;
  47484. int rc = SQLITE_OK;
  47485. sqlite3BtreeEnter(p);
  47486. btreeIntegrity(p);
  47487. /* If the btree is already in a write-transaction, or it
  47488. ** is already in a read-transaction and a read-transaction
  47489. ** is requested, this is a no-op.
  47490. */
  47491. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  47492. goto trans_begun;
  47493. }
  47494. /* Write transactions are not possible on a read-only database */
  47495. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  47496. rc = SQLITE_READONLY;
  47497. goto trans_begun;
  47498. }
  47499. #ifndef SQLITE_OMIT_SHARED_CACHE
  47500. /* If another database handle has already opened a write transaction
  47501. ** on this shared-btree structure and a second write transaction is
  47502. ** requested, return SQLITE_LOCKED.
  47503. */
  47504. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  47505. || (pBt->btsFlags & BTS_PENDING)!=0
  47506. ){
  47507. pBlock = pBt->pWriter->db;
  47508. }else if( wrflag>1 ){
  47509. BtLock *pIter;
  47510. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  47511. if( pIter->pBtree!=p ){
  47512. pBlock = pIter->pBtree->db;
  47513. break;
  47514. }
  47515. }
  47516. }
  47517. if( pBlock ){
  47518. sqlite3ConnectionBlocked(p->db, pBlock);
  47519. rc = SQLITE_LOCKED_SHAREDCACHE;
  47520. goto trans_begun;
  47521. }
  47522. #endif
  47523. /* Any read-only or read-write transaction implies a read-lock on
  47524. ** page 1. So if some other shared-cache client already has a write-lock
  47525. ** on page 1, the transaction cannot be opened. */
  47526. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  47527. if( SQLITE_OK!=rc ) goto trans_begun;
  47528. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  47529. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  47530. do {
  47531. /* Call lockBtree() until either pBt->pPage1 is populated or
  47532. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  47533. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  47534. ** reading page 1 it discovers that the page-size of the database
  47535. ** file is not pBt->pageSize. In this case lockBtree() will update
  47536. ** pBt->pageSize to the page-size of the file on disk.
  47537. */
  47538. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  47539. if( rc==SQLITE_OK && wrflag ){
  47540. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  47541. rc = SQLITE_READONLY;
  47542. }else{
  47543. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  47544. if( rc==SQLITE_OK ){
  47545. rc = newDatabase(pBt);
  47546. }
  47547. }
  47548. }
  47549. if( rc!=SQLITE_OK ){
  47550. unlockBtreeIfUnused(pBt);
  47551. }
  47552. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  47553. btreeInvokeBusyHandler(pBt) );
  47554. if( rc==SQLITE_OK ){
  47555. if( p->inTrans==TRANS_NONE ){
  47556. pBt->nTransaction++;
  47557. #ifndef SQLITE_OMIT_SHARED_CACHE
  47558. if( p->sharable ){
  47559. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  47560. p->lock.eLock = READ_LOCK;
  47561. p->lock.pNext = pBt->pLock;
  47562. pBt->pLock = &p->lock;
  47563. }
  47564. #endif
  47565. }
  47566. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  47567. if( p->inTrans>pBt->inTransaction ){
  47568. pBt->inTransaction = p->inTrans;
  47569. }
  47570. if( wrflag ){
  47571. MemPage *pPage1 = pBt->pPage1;
  47572. #ifndef SQLITE_OMIT_SHARED_CACHE
  47573. assert( !pBt->pWriter );
  47574. pBt->pWriter = p;
  47575. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  47576. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  47577. #endif
  47578. /* If the db-size header field is incorrect (as it may be if an old
  47579. ** client has been writing the database file), update it now. Doing
  47580. ** this sooner rather than later means the database size can safely
  47581. ** re-read the database size from page 1 if a savepoint or transaction
  47582. ** rollback occurs within the transaction.
  47583. */
  47584. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  47585. rc = sqlite3PagerWrite(pPage1->pDbPage);
  47586. if( rc==SQLITE_OK ){
  47587. put4byte(&pPage1->aData[28], pBt->nPage);
  47588. }
  47589. }
  47590. }
  47591. }
  47592. trans_begun:
  47593. if( rc==SQLITE_OK && wrflag ){
  47594. /* This call makes sure that the pager has the correct number of
  47595. ** open savepoints. If the second parameter is greater than 0 and
  47596. ** the sub-journal is not already open, then it will be opened here.
  47597. */
  47598. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  47599. }
  47600. btreeIntegrity(p);
  47601. sqlite3BtreeLeave(p);
  47602. return rc;
  47603. }
  47604. #ifndef SQLITE_OMIT_AUTOVACUUM
  47605. /*
  47606. ** Set the pointer-map entries for all children of page pPage. Also, if
  47607. ** pPage contains cells that point to overflow pages, set the pointer
  47608. ** map entries for the overflow pages as well.
  47609. */
  47610. static int setChildPtrmaps(MemPage *pPage){
  47611. int i; /* Counter variable */
  47612. int nCell; /* Number of cells in page pPage */
  47613. int rc; /* Return code */
  47614. BtShared *pBt = pPage->pBt;
  47615. u8 isInitOrig = pPage->isInit;
  47616. Pgno pgno = pPage->pgno;
  47617. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47618. rc = btreeInitPage(pPage);
  47619. if( rc!=SQLITE_OK ){
  47620. goto set_child_ptrmaps_out;
  47621. }
  47622. nCell = pPage->nCell;
  47623. for(i=0; i<nCell; i++){
  47624. u8 *pCell = findCell(pPage, i);
  47625. ptrmapPutOvflPtr(pPage, pCell, &rc);
  47626. if( !pPage->leaf ){
  47627. Pgno childPgno = get4byte(pCell);
  47628. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  47629. }
  47630. }
  47631. if( !pPage->leaf ){
  47632. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  47633. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  47634. }
  47635. set_child_ptrmaps_out:
  47636. pPage->isInit = isInitOrig;
  47637. return rc;
  47638. }
  47639. /*
  47640. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  47641. ** that it points to iTo. Parameter eType describes the type of pointer to
  47642. ** be modified, as follows:
  47643. **
  47644. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  47645. ** page of pPage.
  47646. **
  47647. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  47648. ** page pointed to by one of the cells on pPage.
  47649. **
  47650. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  47651. ** overflow page in the list.
  47652. */
  47653. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  47654. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  47655. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  47656. if( eType==PTRMAP_OVERFLOW2 ){
  47657. /* The pointer is always the first 4 bytes of the page in this case. */
  47658. if( get4byte(pPage->aData)!=iFrom ){
  47659. return SQLITE_CORRUPT_BKPT;
  47660. }
  47661. put4byte(pPage->aData, iTo);
  47662. }else{
  47663. u8 isInitOrig = pPage->isInit;
  47664. int i;
  47665. int nCell;
  47666. btreeInitPage(pPage);
  47667. nCell = pPage->nCell;
  47668. for(i=0; i<nCell; i++){
  47669. u8 *pCell = findCell(pPage, i);
  47670. if( eType==PTRMAP_OVERFLOW1 ){
  47671. CellInfo info;
  47672. btreeParseCellPtr(pPage, pCell, &info);
  47673. if( info.iOverflow
  47674. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  47675. && iFrom==get4byte(&pCell[info.iOverflow])
  47676. ){
  47677. put4byte(&pCell[info.iOverflow], iTo);
  47678. break;
  47679. }
  47680. }else{
  47681. if( get4byte(pCell)==iFrom ){
  47682. put4byte(pCell, iTo);
  47683. break;
  47684. }
  47685. }
  47686. }
  47687. if( i==nCell ){
  47688. if( eType!=PTRMAP_BTREE ||
  47689. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  47690. return SQLITE_CORRUPT_BKPT;
  47691. }
  47692. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  47693. }
  47694. pPage->isInit = isInitOrig;
  47695. }
  47696. return SQLITE_OK;
  47697. }
  47698. /*
  47699. ** Move the open database page pDbPage to location iFreePage in the
  47700. ** database. The pDbPage reference remains valid.
  47701. **
  47702. ** The isCommit flag indicates that there is no need to remember that
  47703. ** the journal needs to be sync()ed before database page pDbPage->pgno
  47704. ** can be written to. The caller has already promised not to write to that
  47705. ** page.
  47706. */
  47707. static int relocatePage(
  47708. BtShared *pBt, /* Btree */
  47709. MemPage *pDbPage, /* Open page to move */
  47710. u8 eType, /* Pointer map 'type' entry for pDbPage */
  47711. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  47712. Pgno iFreePage, /* The location to move pDbPage to */
  47713. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  47714. ){
  47715. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  47716. Pgno iDbPage = pDbPage->pgno;
  47717. Pager *pPager = pBt->pPager;
  47718. int rc;
  47719. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  47720. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  47721. assert( sqlite3_mutex_held(pBt->mutex) );
  47722. assert( pDbPage->pBt==pBt );
  47723. /* Move page iDbPage from its current location to page number iFreePage */
  47724. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  47725. iDbPage, iFreePage, iPtrPage, eType));
  47726. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  47727. if( rc!=SQLITE_OK ){
  47728. return rc;
  47729. }
  47730. pDbPage->pgno = iFreePage;
  47731. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  47732. ** that point to overflow pages. The pointer map entries for all these
  47733. ** pages need to be changed.
  47734. **
  47735. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  47736. ** pointer to a subsequent overflow page. If this is the case, then
  47737. ** the pointer map needs to be updated for the subsequent overflow page.
  47738. */
  47739. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  47740. rc = setChildPtrmaps(pDbPage);
  47741. if( rc!=SQLITE_OK ){
  47742. return rc;
  47743. }
  47744. }else{
  47745. Pgno nextOvfl = get4byte(pDbPage->aData);
  47746. if( nextOvfl!=0 ){
  47747. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  47748. if( rc!=SQLITE_OK ){
  47749. return rc;
  47750. }
  47751. }
  47752. }
  47753. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  47754. ** that it points at iFreePage. Also fix the pointer map entry for
  47755. ** iPtrPage.
  47756. */
  47757. if( eType!=PTRMAP_ROOTPAGE ){
  47758. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  47759. if( rc!=SQLITE_OK ){
  47760. return rc;
  47761. }
  47762. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  47763. if( rc!=SQLITE_OK ){
  47764. releasePage(pPtrPage);
  47765. return rc;
  47766. }
  47767. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  47768. releasePage(pPtrPage);
  47769. if( rc==SQLITE_OK ){
  47770. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  47771. }
  47772. }
  47773. return rc;
  47774. }
  47775. /* Forward declaration required by incrVacuumStep(). */
  47776. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  47777. /*
  47778. ** Perform a single step of an incremental-vacuum. If successful,
  47779. ** return SQLITE_OK. If there is no work to do (and therefore no
  47780. ** point in calling this function again), return SQLITE_DONE.
  47781. **
  47782. ** More specificly, this function attempts to re-organize the
  47783. ** database so that the last page of the file currently in use
  47784. ** is no longer in use.
  47785. **
  47786. ** If the nFin parameter is non-zero, this function assumes
  47787. ** that the caller will keep calling incrVacuumStep() until
  47788. ** it returns SQLITE_DONE or an error, and that nFin is the
  47789. ** number of pages the database file will contain after this
  47790. ** process is complete. If nFin is zero, it is assumed that
  47791. ** incrVacuumStep() will be called a finite amount of times
  47792. ** which may or may not empty the freelist. A full autovacuum
  47793. ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
  47794. */
  47795. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
  47796. Pgno nFreeList; /* Number of pages still on the free-list */
  47797. int rc;
  47798. assert( sqlite3_mutex_held(pBt->mutex) );
  47799. assert( iLastPg>nFin );
  47800. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  47801. u8 eType;
  47802. Pgno iPtrPage;
  47803. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  47804. if( nFreeList==0 ){
  47805. return SQLITE_DONE;
  47806. }
  47807. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  47808. if( rc!=SQLITE_OK ){
  47809. return rc;
  47810. }
  47811. if( eType==PTRMAP_ROOTPAGE ){
  47812. return SQLITE_CORRUPT_BKPT;
  47813. }
  47814. if( eType==PTRMAP_FREEPAGE ){
  47815. if( nFin==0 ){
  47816. /* Remove the page from the files free-list. This is not required
  47817. ** if nFin is non-zero. In that case, the free-list will be
  47818. ** truncated to zero after this function returns, so it doesn't
  47819. ** matter if it still contains some garbage entries.
  47820. */
  47821. Pgno iFreePg;
  47822. MemPage *pFreePg;
  47823. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
  47824. if( rc!=SQLITE_OK ){
  47825. return rc;
  47826. }
  47827. assert( iFreePg==iLastPg );
  47828. releasePage(pFreePg);
  47829. }
  47830. } else {
  47831. Pgno iFreePg; /* Index of free page to move pLastPg to */
  47832. MemPage *pLastPg;
  47833. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  47834. if( rc!=SQLITE_OK ){
  47835. return rc;
  47836. }
  47837. /* If nFin is zero, this loop runs exactly once and page pLastPg
  47838. ** is swapped with the first free page pulled off the free list.
  47839. **
  47840. ** On the other hand, if nFin is greater than zero, then keep
  47841. ** looping until a free-page located within the first nFin pages
  47842. ** of the file is found.
  47843. */
  47844. do {
  47845. MemPage *pFreePg;
  47846. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
  47847. if( rc!=SQLITE_OK ){
  47848. releasePage(pLastPg);
  47849. return rc;
  47850. }
  47851. releasePage(pFreePg);
  47852. }while( nFin!=0 && iFreePg>nFin );
  47853. assert( iFreePg<iLastPg );
  47854. rc = sqlite3PagerWrite(pLastPg->pDbPage);
  47855. if( rc==SQLITE_OK ){
  47856. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
  47857. }
  47858. releasePage(pLastPg);
  47859. if( rc!=SQLITE_OK ){
  47860. return rc;
  47861. }
  47862. }
  47863. }
  47864. if( nFin==0 ){
  47865. iLastPg--;
  47866. while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
  47867. if( PTRMAP_ISPAGE(pBt, iLastPg) ){
  47868. MemPage *pPg;
  47869. rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
  47870. if( rc!=SQLITE_OK ){
  47871. return rc;
  47872. }
  47873. rc = sqlite3PagerWrite(pPg->pDbPage);
  47874. releasePage(pPg);
  47875. if( rc!=SQLITE_OK ){
  47876. return rc;
  47877. }
  47878. }
  47879. iLastPg--;
  47880. }
  47881. sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
  47882. pBt->nPage = iLastPg;
  47883. }
  47884. return SQLITE_OK;
  47885. }
  47886. /*
  47887. ** A write-transaction must be opened before calling this function.
  47888. ** It performs a single unit of work towards an incremental vacuum.
  47889. **
  47890. ** If the incremental vacuum is finished after this function has run,
  47891. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  47892. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  47893. */
  47894. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  47895. int rc;
  47896. BtShared *pBt = p->pBt;
  47897. sqlite3BtreeEnter(p);
  47898. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  47899. if( !pBt->autoVacuum ){
  47900. rc = SQLITE_DONE;
  47901. }else{
  47902. invalidateAllOverflowCache(pBt);
  47903. rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
  47904. if( rc==SQLITE_OK ){
  47905. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  47906. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  47907. }
  47908. }
  47909. sqlite3BtreeLeave(p);
  47910. return rc;
  47911. }
  47912. /*
  47913. ** This routine is called prior to sqlite3PagerCommit when a transaction
  47914. ** is commited for an auto-vacuum database.
  47915. **
  47916. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  47917. ** the database file should be truncated to during the commit process.
  47918. ** i.e. the database has been reorganized so that only the first *pnTrunc
  47919. ** pages are in use.
  47920. */
  47921. static int autoVacuumCommit(BtShared *pBt){
  47922. int rc = SQLITE_OK;
  47923. Pager *pPager = pBt->pPager;
  47924. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  47925. assert( sqlite3_mutex_held(pBt->mutex) );
  47926. invalidateAllOverflowCache(pBt);
  47927. assert(pBt->autoVacuum);
  47928. if( !pBt->incrVacuum ){
  47929. Pgno nFin; /* Number of pages in database after autovacuuming */
  47930. Pgno nFree; /* Number of pages on the freelist initially */
  47931. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  47932. Pgno iFree; /* The next page to be freed */
  47933. int nEntry; /* Number of entries on one ptrmap page */
  47934. Pgno nOrig; /* Database size before freeing */
  47935. nOrig = btreePagecount(pBt);
  47936. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  47937. /* It is not possible to create a database for which the final page
  47938. ** is either a pointer-map page or the pending-byte page. If one
  47939. ** is encountered, this indicates corruption.
  47940. */
  47941. return SQLITE_CORRUPT_BKPT;
  47942. }
  47943. nFree = get4byte(&pBt->pPage1->aData[36]);
  47944. nEntry = pBt->usableSize/5;
  47945. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  47946. nFin = nOrig - nFree - nPtrmap;
  47947. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  47948. nFin--;
  47949. }
  47950. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  47951. nFin--;
  47952. }
  47953. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  47954. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  47955. rc = incrVacuumStep(pBt, nFin, iFree);
  47956. }
  47957. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  47958. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  47959. put4byte(&pBt->pPage1->aData[32], 0);
  47960. put4byte(&pBt->pPage1->aData[36], 0);
  47961. put4byte(&pBt->pPage1->aData[28], nFin);
  47962. sqlite3PagerTruncateImage(pBt->pPager, nFin);
  47963. pBt->nPage = nFin;
  47964. }
  47965. if( rc!=SQLITE_OK ){
  47966. sqlite3PagerRollback(pPager);
  47967. }
  47968. }
  47969. assert( nRef==sqlite3PagerRefcount(pPager) );
  47970. return rc;
  47971. }
  47972. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  47973. # define setChildPtrmaps(x) SQLITE_OK
  47974. #endif
  47975. /*
  47976. ** This routine does the first phase of a two-phase commit. This routine
  47977. ** causes a rollback journal to be created (if it does not already exist)
  47978. ** and populated with enough information so that if a power loss occurs
  47979. ** the database can be restored to its original state by playing back
  47980. ** the journal. Then the contents of the journal are flushed out to
  47981. ** the disk. After the journal is safely on oxide, the changes to the
  47982. ** database are written into the database file and flushed to oxide.
  47983. ** At the end of this call, the rollback journal still exists on the
  47984. ** disk and we are still holding all locks, so the transaction has not
  47985. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  47986. ** commit process.
  47987. **
  47988. ** This call is a no-op if no write-transaction is currently active on pBt.
  47989. **
  47990. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  47991. ** the name of a master journal file that should be written into the
  47992. ** individual journal file, or is NULL, indicating no master journal file
  47993. ** (single database transaction).
  47994. **
  47995. ** When this is called, the master journal should already have been
  47996. ** created, populated with this journal pointer and synced to disk.
  47997. **
  47998. ** Once this is routine has returned, the only thing required to commit
  47999. ** the write-transaction for this database file is to delete the journal.
  48000. */
  48001. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  48002. int rc = SQLITE_OK;
  48003. if( p->inTrans==TRANS_WRITE ){
  48004. BtShared *pBt = p->pBt;
  48005. sqlite3BtreeEnter(p);
  48006. #ifndef SQLITE_OMIT_AUTOVACUUM
  48007. if( pBt->autoVacuum ){
  48008. rc = autoVacuumCommit(pBt);
  48009. if( rc!=SQLITE_OK ){
  48010. sqlite3BtreeLeave(p);
  48011. return rc;
  48012. }
  48013. }
  48014. #endif
  48015. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  48016. sqlite3BtreeLeave(p);
  48017. }
  48018. return rc;
  48019. }
  48020. /*
  48021. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  48022. ** at the conclusion of a transaction.
  48023. */
  48024. static void btreeEndTransaction(Btree *p){
  48025. BtShared *pBt = p->pBt;
  48026. assert( sqlite3BtreeHoldsMutex(p) );
  48027. btreeClearHasContent(pBt);
  48028. if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
  48029. /* If there are other active statements that belong to this database
  48030. ** handle, downgrade to a read-only transaction. The other statements
  48031. ** may still be reading from the database. */
  48032. downgradeAllSharedCacheTableLocks(p);
  48033. p->inTrans = TRANS_READ;
  48034. }else{
  48035. /* If the handle had any kind of transaction open, decrement the
  48036. ** transaction count of the shared btree. If the transaction count
  48037. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  48038. ** call below will unlock the pager. */
  48039. if( p->inTrans!=TRANS_NONE ){
  48040. clearAllSharedCacheTableLocks(p);
  48041. pBt->nTransaction--;
  48042. if( 0==pBt->nTransaction ){
  48043. pBt->inTransaction = TRANS_NONE;
  48044. }
  48045. }
  48046. /* Set the current transaction state to TRANS_NONE and unlock the
  48047. ** pager if this call closed the only read or write transaction. */
  48048. p->inTrans = TRANS_NONE;
  48049. unlockBtreeIfUnused(pBt);
  48050. }
  48051. btreeIntegrity(p);
  48052. }
  48053. /*
  48054. ** Commit the transaction currently in progress.
  48055. **
  48056. ** This routine implements the second phase of a 2-phase commit. The
  48057. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  48058. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  48059. ** routine did all the work of writing information out to disk and flushing the
  48060. ** contents so that they are written onto the disk platter. All this
  48061. ** routine has to do is delete or truncate or zero the header in the
  48062. ** the rollback journal (which causes the transaction to commit) and
  48063. ** drop locks.
  48064. **
  48065. ** Normally, if an error occurs while the pager layer is attempting to
  48066. ** finalize the underlying journal file, this function returns an error and
  48067. ** the upper layer will attempt a rollback. However, if the second argument
  48068. ** is non-zero then this b-tree transaction is part of a multi-file
  48069. ** transaction. In this case, the transaction has already been committed
  48070. ** (by deleting a master journal file) and the caller will ignore this
  48071. ** functions return code. So, even if an error occurs in the pager layer,
  48072. ** reset the b-tree objects internal state to indicate that the write
  48073. ** transaction has been closed. This is quite safe, as the pager will have
  48074. ** transitioned to the error state.
  48075. **
  48076. ** This will release the write lock on the database file. If there
  48077. ** are no active cursors, it also releases the read lock.
  48078. */
  48079. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  48080. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  48081. sqlite3BtreeEnter(p);
  48082. btreeIntegrity(p);
  48083. /* If the handle has a write-transaction open, commit the shared-btrees
  48084. ** transaction and set the shared state to TRANS_READ.
  48085. */
  48086. if( p->inTrans==TRANS_WRITE ){
  48087. int rc;
  48088. BtShared *pBt = p->pBt;
  48089. assert( pBt->inTransaction==TRANS_WRITE );
  48090. assert( pBt->nTransaction>0 );
  48091. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  48092. if( rc!=SQLITE_OK && bCleanup==0 ){
  48093. sqlite3BtreeLeave(p);
  48094. return rc;
  48095. }
  48096. pBt->inTransaction = TRANS_READ;
  48097. }
  48098. btreeEndTransaction(p);
  48099. sqlite3BtreeLeave(p);
  48100. return SQLITE_OK;
  48101. }
  48102. /*
  48103. ** Do both phases of a commit.
  48104. */
  48105. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  48106. int rc;
  48107. sqlite3BtreeEnter(p);
  48108. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  48109. if( rc==SQLITE_OK ){
  48110. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  48111. }
  48112. sqlite3BtreeLeave(p);
  48113. return rc;
  48114. }
  48115. #ifndef NDEBUG
  48116. /*
  48117. ** Return the number of write-cursors open on this handle. This is for use
  48118. ** in assert() expressions, so it is only compiled if NDEBUG is not
  48119. ** defined.
  48120. **
  48121. ** For the purposes of this routine, a write-cursor is any cursor that
  48122. ** is capable of writing to the databse. That means the cursor was
  48123. ** originally opened for writing and the cursor has not be disabled
  48124. ** by having its state changed to CURSOR_FAULT.
  48125. */
  48126. static int countWriteCursors(BtShared *pBt){
  48127. BtCursor *pCur;
  48128. int r = 0;
  48129. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  48130. if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
  48131. }
  48132. return r;
  48133. }
  48134. #endif
  48135. /*
  48136. ** This routine sets the state to CURSOR_FAULT and the error
  48137. ** code to errCode for every cursor on BtShared that pBtree
  48138. ** references.
  48139. **
  48140. ** Every cursor is tripped, including cursors that belong
  48141. ** to other database connections that happen to be sharing
  48142. ** the cache with pBtree.
  48143. **
  48144. ** This routine gets called when a rollback occurs.
  48145. ** All cursors using the same cache must be tripped
  48146. ** to prevent them from trying to use the btree after
  48147. ** the rollback. The rollback may have deleted tables
  48148. ** or moved root pages, so it is not sufficient to
  48149. ** save the state of the cursor. The cursor must be
  48150. ** invalidated.
  48151. */
  48152. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  48153. BtCursor *p;
  48154. if( pBtree==0 ) return;
  48155. sqlite3BtreeEnter(pBtree);
  48156. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  48157. int i;
  48158. sqlite3BtreeClearCursor(p);
  48159. p->eState = CURSOR_FAULT;
  48160. p->skipNext = errCode;
  48161. for(i=0; i<=p->iPage; i++){
  48162. releasePage(p->apPage[i]);
  48163. p->apPage[i] = 0;
  48164. }
  48165. }
  48166. sqlite3BtreeLeave(pBtree);
  48167. }
  48168. /*
  48169. ** Rollback the transaction in progress. All cursors will be
  48170. ** invalided by this operation. Any attempt to use a cursor
  48171. ** that was open at the beginning of this operation will result
  48172. ** in an error.
  48173. **
  48174. ** This will release the write lock on the database file. If there
  48175. ** are no active cursors, it also releases the read lock.
  48176. */
  48177. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  48178. int rc;
  48179. BtShared *pBt = p->pBt;
  48180. MemPage *pPage1;
  48181. sqlite3BtreeEnter(p);
  48182. if( tripCode==SQLITE_OK ){
  48183. rc = tripCode = saveAllCursors(pBt, 0, 0);
  48184. }else{
  48185. rc = SQLITE_OK;
  48186. }
  48187. if( tripCode ){
  48188. sqlite3BtreeTripAllCursors(p, tripCode);
  48189. }
  48190. btreeIntegrity(p);
  48191. if( p->inTrans==TRANS_WRITE ){
  48192. int rc2;
  48193. assert( TRANS_WRITE==pBt->inTransaction );
  48194. rc2 = sqlite3PagerRollback(pBt->pPager);
  48195. if( rc2!=SQLITE_OK ){
  48196. rc = rc2;
  48197. }
  48198. /* The rollback may have destroyed the pPage1->aData value. So
  48199. ** call btreeGetPage() on page 1 again to make
  48200. ** sure pPage1->aData is set correctly. */
  48201. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  48202. int nPage = get4byte(28+(u8*)pPage1->aData);
  48203. testcase( nPage==0 );
  48204. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  48205. testcase( pBt->nPage!=nPage );
  48206. pBt->nPage = nPage;
  48207. releasePage(pPage1);
  48208. }
  48209. assert( countWriteCursors(pBt)==0 );
  48210. pBt->inTransaction = TRANS_READ;
  48211. }
  48212. btreeEndTransaction(p);
  48213. sqlite3BtreeLeave(p);
  48214. return rc;
  48215. }
  48216. /*
  48217. ** Start a statement subtransaction. The subtransaction can can be rolled
  48218. ** back independently of the main transaction. You must start a transaction
  48219. ** before starting a subtransaction. The subtransaction is ended automatically
  48220. ** if the main transaction commits or rolls back.
  48221. **
  48222. ** Statement subtransactions are used around individual SQL statements
  48223. ** that are contained within a BEGIN...COMMIT block. If a constraint
  48224. ** error occurs within the statement, the effect of that one statement
  48225. ** can be rolled back without having to rollback the entire transaction.
  48226. **
  48227. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  48228. ** value passed as the second parameter is the total number of savepoints,
  48229. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  48230. ** are no active savepoints and no other statement-transactions open,
  48231. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  48232. ** using the sqlite3BtreeSavepoint() function.
  48233. */
  48234. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  48235. int rc;
  48236. BtShared *pBt = p->pBt;
  48237. sqlite3BtreeEnter(p);
  48238. assert( p->inTrans==TRANS_WRITE );
  48239. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  48240. assert( iStatement>0 );
  48241. assert( iStatement>p->db->nSavepoint );
  48242. assert( pBt->inTransaction==TRANS_WRITE );
  48243. /* At the pager level, a statement transaction is a savepoint with
  48244. ** an index greater than all savepoints created explicitly using
  48245. ** SQL statements. It is illegal to open, release or rollback any
  48246. ** such savepoints while the statement transaction savepoint is active.
  48247. */
  48248. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  48249. sqlite3BtreeLeave(p);
  48250. return rc;
  48251. }
  48252. /*
  48253. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  48254. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  48255. ** savepoint identified by parameter iSavepoint, depending on the value
  48256. ** of op.
  48257. **
  48258. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  48259. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  48260. ** contents of the entire transaction are rolled back. This is different
  48261. ** from a normal transaction rollback, as no locks are released and the
  48262. ** transaction remains open.
  48263. */
  48264. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  48265. int rc = SQLITE_OK;
  48266. if( p && p->inTrans==TRANS_WRITE ){
  48267. BtShared *pBt = p->pBt;
  48268. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  48269. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  48270. sqlite3BtreeEnter(p);
  48271. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  48272. if( rc==SQLITE_OK ){
  48273. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  48274. pBt->nPage = 0;
  48275. }
  48276. rc = newDatabase(pBt);
  48277. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  48278. /* The database size was written into the offset 28 of the header
  48279. ** when the transaction started, so we know that the value at offset
  48280. ** 28 is nonzero. */
  48281. assert( pBt->nPage>0 );
  48282. }
  48283. sqlite3BtreeLeave(p);
  48284. }
  48285. return rc;
  48286. }
  48287. /*
  48288. ** Create a new cursor for the BTree whose root is on the page
  48289. ** iTable. If a read-only cursor is requested, it is assumed that
  48290. ** the caller already has at least a read-only transaction open
  48291. ** on the database already. If a write-cursor is requested, then
  48292. ** the caller is assumed to have an open write transaction.
  48293. **
  48294. ** If wrFlag==0, then the cursor can only be used for reading.
  48295. ** If wrFlag==1, then the cursor can be used for reading or for
  48296. ** writing if other conditions for writing are also met. These
  48297. ** are the conditions that must be met in order for writing to
  48298. ** be allowed:
  48299. **
  48300. ** 1: The cursor must have been opened with wrFlag==1
  48301. **
  48302. ** 2: Other database connections that share the same pager cache
  48303. ** but which are not in the READ_UNCOMMITTED state may not have
  48304. ** cursors open with wrFlag==0 on the same table. Otherwise
  48305. ** the changes made by this write cursor would be visible to
  48306. ** the read cursors in the other database connection.
  48307. **
  48308. ** 3: The database must be writable (not on read-only media)
  48309. **
  48310. ** 4: There must be an active transaction.
  48311. **
  48312. ** No checking is done to make sure that page iTable really is the
  48313. ** root page of a b-tree. If it is not, then the cursor acquired
  48314. ** will not work correctly.
  48315. **
  48316. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  48317. ** on pCur to initialize the memory space prior to invoking this routine.
  48318. */
  48319. static int btreeCursor(
  48320. Btree *p, /* The btree */
  48321. int iTable, /* Root page of table to open */
  48322. int wrFlag, /* 1 to write. 0 read-only */
  48323. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  48324. BtCursor *pCur /* Space for new cursor */
  48325. ){
  48326. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  48327. assert( sqlite3BtreeHoldsMutex(p) );
  48328. assert( wrFlag==0 || wrFlag==1 );
  48329. /* The following assert statements verify that if this is a sharable
  48330. ** b-tree database, the connection is holding the required table locks,
  48331. ** and that no other connection has any open cursor that conflicts with
  48332. ** this lock. */
  48333. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  48334. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  48335. /* Assert that the caller has opened the required transaction. */
  48336. assert( p->inTrans>TRANS_NONE );
  48337. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  48338. assert( pBt->pPage1 && pBt->pPage1->aData );
  48339. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  48340. return SQLITE_READONLY;
  48341. }
  48342. if( iTable==1 && btreePagecount(pBt)==0 ){
  48343. assert( wrFlag==0 );
  48344. iTable = 0;
  48345. }
  48346. /* Now that no other errors can occur, finish filling in the BtCursor
  48347. ** variables and link the cursor into the BtShared list. */
  48348. pCur->pgnoRoot = (Pgno)iTable;
  48349. pCur->iPage = -1;
  48350. pCur->pKeyInfo = pKeyInfo;
  48351. pCur->pBtree = p;
  48352. pCur->pBt = pBt;
  48353. pCur->wrFlag = (u8)wrFlag;
  48354. pCur->pNext = pBt->pCursor;
  48355. if( pCur->pNext ){
  48356. pCur->pNext->pPrev = pCur;
  48357. }
  48358. pBt->pCursor = pCur;
  48359. pCur->eState = CURSOR_INVALID;
  48360. pCur->cachedRowid = 0;
  48361. return SQLITE_OK;
  48362. }
  48363. SQLITE_PRIVATE int sqlite3BtreeCursor(
  48364. Btree *p, /* The btree */
  48365. int iTable, /* Root page of table to open */
  48366. int wrFlag, /* 1 to write. 0 read-only */
  48367. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  48368. BtCursor *pCur /* Write new cursor here */
  48369. ){
  48370. int rc;
  48371. sqlite3BtreeEnter(p);
  48372. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  48373. sqlite3BtreeLeave(p);
  48374. return rc;
  48375. }
  48376. /*
  48377. ** Return the size of a BtCursor object in bytes.
  48378. **
  48379. ** This interfaces is needed so that users of cursors can preallocate
  48380. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  48381. ** to users so they cannot do the sizeof() themselves - they must call
  48382. ** this routine.
  48383. */
  48384. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  48385. return ROUND8(sizeof(BtCursor));
  48386. }
  48387. /*
  48388. ** Initialize memory that will be converted into a BtCursor object.
  48389. **
  48390. ** The simple approach here would be to memset() the entire object
  48391. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  48392. ** do not need to be zeroed and they are large, so we can save a lot
  48393. ** of run-time by skipping the initialization of those elements.
  48394. */
  48395. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  48396. memset(p, 0, offsetof(BtCursor, iPage));
  48397. }
  48398. /*
  48399. ** Set the cached rowid value of every cursor in the same database file
  48400. ** as pCur and having the same root page number as pCur. The value is
  48401. ** set to iRowid.
  48402. **
  48403. ** Only positive rowid values are considered valid for this cache.
  48404. ** The cache is initialized to zero, indicating an invalid cache.
  48405. ** A btree will work fine with zero or negative rowids. We just cannot
  48406. ** cache zero or negative rowids, which means tables that use zero or
  48407. ** negative rowids might run a little slower. But in practice, zero
  48408. ** or negative rowids are very uncommon so this should not be a problem.
  48409. */
  48410. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  48411. BtCursor *p;
  48412. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  48413. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  48414. }
  48415. assert( pCur->cachedRowid==iRowid );
  48416. }
  48417. /*
  48418. ** Return the cached rowid for the given cursor. A negative or zero
  48419. ** return value indicates that the rowid cache is invalid and should be
  48420. ** ignored. If the rowid cache has never before been set, then a
  48421. ** zero is returned.
  48422. */
  48423. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  48424. return pCur->cachedRowid;
  48425. }
  48426. /*
  48427. ** Close a cursor. The read lock on the database file is released
  48428. ** when the last cursor is closed.
  48429. */
  48430. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  48431. Btree *pBtree = pCur->pBtree;
  48432. if( pBtree ){
  48433. int i;
  48434. BtShared *pBt = pCur->pBt;
  48435. sqlite3BtreeEnter(pBtree);
  48436. sqlite3BtreeClearCursor(pCur);
  48437. if( pCur->pPrev ){
  48438. pCur->pPrev->pNext = pCur->pNext;
  48439. }else{
  48440. pBt->pCursor = pCur->pNext;
  48441. }
  48442. if( pCur->pNext ){
  48443. pCur->pNext->pPrev = pCur->pPrev;
  48444. }
  48445. for(i=0; i<=pCur->iPage; i++){
  48446. releasePage(pCur->apPage[i]);
  48447. }
  48448. unlockBtreeIfUnused(pBt);
  48449. invalidateOverflowCache(pCur);
  48450. /* sqlite3_free(pCur); */
  48451. sqlite3BtreeLeave(pBtree);
  48452. }
  48453. return SQLITE_OK;
  48454. }
  48455. /*
  48456. ** Make sure the BtCursor* given in the argument has a valid
  48457. ** BtCursor.info structure. If it is not already valid, call
  48458. ** btreeParseCell() to fill it in.
  48459. **
  48460. ** BtCursor.info is a cache of the information in the current cell.
  48461. ** Using this cache reduces the number of calls to btreeParseCell().
  48462. **
  48463. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  48464. ** compiler to crash when getCellInfo() is implemented as a macro.
  48465. ** But there is a measureable speed advantage to using the macro on gcc
  48466. ** (when less compiler optimizations like -Os or -O0 are used and the
  48467. ** compiler is not doing agressive inlining.) So we use a real function
  48468. ** for MSVC and a macro for everything else. Ticket #2457.
  48469. */
  48470. #ifndef NDEBUG
  48471. static void assertCellInfo(BtCursor *pCur){
  48472. CellInfo info;
  48473. int iPage = pCur->iPage;
  48474. memset(&info, 0, sizeof(info));
  48475. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  48476. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  48477. }
  48478. #else
  48479. #define assertCellInfo(x)
  48480. #endif
  48481. #ifdef _MSC_VER
  48482. /* Use a real function in MSVC to work around bugs in that compiler. */
  48483. static void getCellInfo(BtCursor *pCur){
  48484. if( pCur->info.nSize==0 ){
  48485. int iPage = pCur->iPage;
  48486. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  48487. pCur->validNKey = 1;
  48488. }else{
  48489. assertCellInfo(pCur);
  48490. }
  48491. }
  48492. #else /* if not _MSC_VER */
  48493. /* Use a macro in all other compilers so that the function is inlined */
  48494. #define getCellInfo(pCur) \
  48495. if( pCur->info.nSize==0 ){ \
  48496. int iPage = pCur->iPage; \
  48497. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  48498. pCur->validNKey = 1; \
  48499. }else{ \
  48500. assertCellInfo(pCur); \
  48501. }
  48502. #endif /* _MSC_VER */
  48503. #ifndef NDEBUG /* The next routine used only within assert() statements */
  48504. /*
  48505. ** Return true if the given BtCursor is valid. A valid cursor is one
  48506. ** that is currently pointing to a row in a (non-empty) table.
  48507. ** This is a verification routine is used only within assert() statements.
  48508. */
  48509. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  48510. return pCur && pCur->eState==CURSOR_VALID;
  48511. }
  48512. #endif /* NDEBUG */
  48513. /*
  48514. ** Set *pSize to the size of the buffer needed to hold the value of
  48515. ** the key for the current entry. If the cursor is not pointing
  48516. ** to a valid entry, *pSize is set to 0.
  48517. **
  48518. ** For a table with the INTKEY flag set, this routine returns the key
  48519. ** itself, not the number of bytes in the key.
  48520. **
  48521. ** The caller must position the cursor prior to invoking this routine.
  48522. **
  48523. ** This routine cannot fail. It always returns SQLITE_OK.
  48524. */
  48525. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  48526. assert( cursorHoldsMutex(pCur) );
  48527. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  48528. if( pCur->eState!=CURSOR_VALID ){
  48529. *pSize = 0;
  48530. }else{
  48531. getCellInfo(pCur);
  48532. *pSize = pCur->info.nKey;
  48533. }
  48534. return SQLITE_OK;
  48535. }
  48536. /*
  48537. ** Set *pSize to the number of bytes of data in the entry the
  48538. ** cursor currently points to.
  48539. **
  48540. ** The caller must guarantee that the cursor is pointing to a non-NULL
  48541. ** valid entry. In other words, the calling procedure must guarantee
  48542. ** that the cursor has Cursor.eState==CURSOR_VALID.
  48543. **
  48544. ** Failure is not possible. This function always returns SQLITE_OK.
  48545. ** It might just as well be a procedure (returning void) but we continue
  48546. ** to return an integer result code for historical reasons.
  48547. */
  48548. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  48549. assert( cursorHoldsMutex(pCur) );
  48550. assert( pCur->eState==CURSOR_VALID );
  48551. getCellInfo(pCur);
  48552. *pSize = pCur->info.nData;
  48553. return SQLITE_OK;
  48554. }
  48555. /*
  48556. ** Given the page number of an overflow page in the database (parameter
  48557. ** ovfl), this function finds the page number of the next page in the
  48558. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  48559. ** pointer-map data instead of reading the content of page ovfl to do so.
  48560. **
  48561. ** If an error occurs an SQLite error code is returned. Otherwise:
  48562. **
  48563. ** The page number of the next overflow page in the linked list is
  48564. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  48565. ** list, *pPgnoNext is set to zero.
  48566. **
  48567. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  48568. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  48569. ** reference. It is the responsibility of the caller to call releasePage()
  48570. ** on *ppPage to free the reference. In no reference was obtained (because
  48571. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  48572. ** *ppPage is set to zero.
  48573. */
  48574. static int getOverflowPage(
  48575. BtShared *pBt, /* The database file */
  48576. Pgno ovfl, /* Current overflow page number */
  48577. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  48578. Pgno *pPgnoNext /* OUT: Next overflow page number */
  48579. ){
  48580. Pgno next = 0;
  48581. MemPage *pPage = 0;
  48582. int rc = SQLITE_OK;
  48583. assert( sqlite3_mutex_held(pBt->mutex) );
  48584. assert(pPgnoNext);
  48585. #ifndef SQLITE_OMIT_AUTOVACUUM
  48586. /* Try to find the next page in the overflow list using the
  48587. ** autovacuum pointer-map pages. Guess that the next page in
  48588. ** the overflow list is page number (ovfl+1). If that guess turns
  48589. ** out to be wrong, fall back to loading the data of page
  48590. ** number ovfl to determine the next page number.
  48591. */
  48592. if( pBt->autoVacuum ){
  48593. Pgno pgno;
  48594. Pgno iGuess = ovfl+1;
  48595. u8 eType;
  48596. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  48597. iGuess++;
  48598. }
  48599. if( iGuess<=btreePagecount(pBt) ){
  48600. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  48601. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  48602. next = iGuess;
  48603. rc = SQLITE_DONE;
  48604. }
  48605. }
  48606. }
  48607. #endif
  48608. assert( next==0 || rc==SQLITE_DONE );
  48609. if( rc==SQLITE_OK ){
  48610. rc = btreeGetPage(pBt, ovfl, &pPage, 0);
  48611. assert( rc==SQLITE_OK || pPage==0 );
  48612. if( rc==SQLITE_OK ){
  48613. next = get4byte(pPage->aData);
  48614. }
  48615. }
  48616. *pPgnoNext = next;
  48617. if( ppPage ){
  48618. *ppPage = pPage;
  48619. }else{
  48620. releasePage(pPage);
  48621. }
  48622. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  48623. }
  48624. /*
  48625. ** Copy data from a buffer to a page, or from a page to a buffer.
  48626. **
  48627. ** pPayload is a pointer to data stored on database page pDbPage.
  48628. ** If argument eOp is false, then nByte bytes of data are copied
  48629. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  48630. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  48631. ** of data are copied from the buffer pBuf to pPayload.
  48632. **
  48633. ** SQLITE_OK is returned on success, otherwise an error code.
  48634. */
  48635. static int copyPayload(
  48636. void *pPayload, /* Pointer to page data */
  48637. void *pBuf, /* Pointer to buffer */
  48638. int nByte, /* Number of bytes to copy */
  48639. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  48640. DbPage *pDbPage /* Page containing pPayload */
  48641. ){
  48642. if( eOp ){
  48643. /* Copy data from buffer to page (a write operation) */
  48644. int rc = sqlite3PagerWrite(pDbPage);
  48645. if( rc!=SQLITE_OK ){
  48646. return rc;
  48647. }
  48648. memcpy(pPayload, pBuf, nByte);
  48649. }else{
  48650. /* Copy data from page to buffer (a read operation) */
  48651. memcpy(pBuf, pPayload, nByte);
  48652. }
  48653. return SQLITE_OK;
  48654. }
  48655. /*
  48656. ** This function is used to read or overwrite payload information
  48657. ** for the entry that the pCur cursor is pointing to. If the eOp
  48658. ** parameter is 0, this is a read operation (data copied into
  48659. ** buffer pBuf). If it is non-zero, a write (data copied from
  48660. ** buffer pBuf).
  48661. **
  48662. ** A total of "amt" bytes are read or written beginning at "offset".
  48663. ** Data is read to or from the buffer pBuf.
  48664. **
  48665. ** The content being read or written might appear on the main page
  48666. ** or be scattered out on multiple overflow pages.
  48667. **
  48668. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  48669. ** cursor entry uses one or more overflow pages, this function
  48670. ** allocates space for and lazily popluates the overflow page-list
  48671. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  48672. ** cache to make seeking to the supplied offset more efficient.
  48673. **
  48674. ** Once an overflow page-list cache has been allocated, it may be
  48675. ** invalidated if some other cursor writes to the same table, or if
  48676. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  48677. ** mode, the following events may invalidate an overflow page-list cache.
  48678. **
  48679. ** * An incremental vacuum,
  48680. ** * A commit in auto_vacuum="full" mode,
  48681. ** * Creating a table (may require moving an overflow page).
  48682. */
  48683. static int accessPayload(
  48684. BtCursor *pCur, /* Cursor pointing to entry to read from */
  48685. u32 offset, /* Begin reading this far into payload */
  48686. u32 amt, /* Read this many bytes */
  48687. unsigned char *pBuf, /* Write the bytes into this buffer */
  48688. int eOp /* zero to read. non-zero to write. */
  48689. ){
  48690. unsigned char *aPayload;
  48691. int rc = SQLITE_OK;
  48692. u32 nKey;
  48693. int iIdx = 0;
  48694. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  48695. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  48696. assert( pPage );
  48697. assert( pCur->eState==CURSOR_VALID );
  48698. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  48699. assert( cursorHoldsMutex(pCur) );
  48700. getCellInfo(pCur);
  48701. aPayload = pCur->info.pCell + pCur->info.nHeader;
  48702. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  48703. if( NEVER(offset+amt > nKey+pCur->info.nData)
  48704. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  48705. ){
  48706. /* Trying to read or write past the end of the data is an error */
  48707. return SQLITE_CORRUPT_BKPT;
  48708. }
  48709. /* Check if data must be read/written to/from the btree page itself. */
  48710. if( offset<pCur->info.nLocal ){
  48711. int a = amt;
  48712. if( a+offset>pCur->info.nLocal ){
  48713. a = pCur->info.nLocal - offset;
  48714. }
  48715. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  48716. offset = 0;
  48717. pBuf += a;
  48718. amt -= a;
  48719. }else{
  48720. offset -= pCur->info.nLocal;
  48721. }
  48722. if( rc==SQLITE_OK && amt>0 ){
  48723. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  48724. Pgno nextPage;
  48725. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  48726. #ifndef SQLITE_OMIT_INCRBLOB
  48727. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  48728. ** has not been allocated, allocate it now. The array is sized at
  48729. ** one entry for each overflow page in the overflow chain. The
  48730. ** page number of the first overflow page is stored in aOverflow[0],
  48731. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  48732. ** (the cache is lazily populated).
  48733. */
  48734. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  48735. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  48736. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  48737. /* nOvfl is always positive. If it were zero, fetchPayload would have
  48738. ** been used instead of this routine. */
  48739. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  48740. rc = SQLITE_NOMEM;
  48741. }
  48742. }
  48743. /* If the overflow page-list cache has been allocated and the
  48744. ** entry for the first required overflow page is valid, skip
  48745. ** directly to it.
  48746. */
  48747. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  48748. iIdx = (offset/ovflSize);
  48749. nextPage = pCur->aOverflow[iIdx];
  48750. offset = (offset%ovflSize);
  48751. }
  48752. #endif
  48753. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  48754. #ifndef SQLITE_OMIT_INCRBLOB
  48755. /* If required, populate the overflow page-list cache. */
  48756. if( pCur->aOverflow ){
  48757. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  48758. pCur->aOverflow[iIdx] = nextPage;
  48759. }
  48760. #endif
  48761. if( offset>=ovflSize ){
  48762. /* The only reason to read this page is to obtain the page
  48763. ** number for the next page in the overflow chain. The page
  48764. ** data is not required. So first try to lookup the overflow
  48765. ** page-list cache, if any, then fall back to the getOverflowPage()
  48766. ** function.
  48767. */
  48768. #ifndef SQLITE_OMIT_INCRBLOB
  48769. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  48770. nextPage = pCur->aOverflow[iIdx+1];
  48771. } else
  48772. #endif
  48773. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  48774. offset -= ovflSize;
  48775. }else{
  48776. /* Need to read this page properly. It contains some of the
  48777. ** range of data that is being read (eOp==0) or written (eOp!=0).
  48778. */
  48779. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  48780. sqlite3_file *fd;
  48781. #endif
  48782. int a = amt;
  48783. if( a + offset > ovflSize ){
  48784. a = ovflSize - offset;
  48785. }
  48786. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  48787. /* If all the following are true:
  48788. **
  48789. ** 1) this is a read operation, and
  48790. ** 2) data is required from the start of this overflow page, and
  48791. ** 3) the database is file-backed, and
  48792. ** 4) there is no open write-transaction, and
  48793. ** 5) the database is not a WAL database,
  48794. **
  48795. ** then data can be read directly from the database file into the
  48796. ** output buffer, bypassing the page-cache altogether. This speeds
  48797. ** up loading large records that span many overflow pages.
  48798. */
  48799. if( eOp==0 /* (1) */
  48800. && offset==0 /* (2) */
  48801. && pBt->inTransaction==TRANS_READ /* (4) */
  48802. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  48803. && pBt->pPage1->aData[19]==0x01 /* (5) */
  48804. ){
  48805. u8 aSave[4];
  48806. u8 *aWrite = &pBuf[-4];
  48807. memcpy(aSave, aWrite, 4);
  48808. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  48809. nextPage = get4byte(aWrite);
  48810. memcpy(aWrite, aSave, 4);
  48811. }else
  48812. #endif
  48813. {
  48814. DbPage *pDbPage;
  48815. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
  48816. if( rc==SQLITE_OK ){
  48817. aPayload = sqlite3PagerGetData(pDbPage);
  48818. nextPage = get4byte(aPayload);
  48819. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  48820. sqlite3PagerUnref(pDbPage);
  48821. offset = 0;
  48822. }
  48823. }
  48824. amt -= a;
  48825. pBuf += a;
  48826. }
  48827. }
  48828. }
  48829. if( rc==SQLITE_OK && amt>0 ){
  48830. return SQLITE_CORRUPT_BKPT;
  48831. }
  48832. return rc;
  48833. }
  48834. /*
  48835. ** Read part of the key associated with cursor pCur. Exactly
  48836. ** "amt" bytes will be transfered into pBuf[]. The transfer
  48837. ** begins at "offset".
  48838. **
  48839. ** The caller must ensure that pCur is pointing to a valid row
  48840. ** in the table.
  48841. **
  48842. ** Return SQLITE_OK on success or an error code if anything goes
  48843. ** wrong. An error is returned if "offset+amt" is larger than
  48844. ** the available payload.
  48845. */
  48846. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  48847. assert( cursorHoldsMutex(pCur) );
  48848. assert( pCur->eState==CURSOR_VALID );
  48849. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  48850. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  48851. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  48852. }
  48853. /*
  48854. ** Read part of the data associated with cursor pCur. Exactly
  48855. ** "amt" bytes will be transfered into pBuf[]. The transfer
  48856. ** begins at "offset".
  48857. **
  48858. ** Return SQLITE_OK on success or an error code if anything goes
  48859. ** wrong. An error is returned if "offset+amt" is larger than
  48860. ** the available payload.
  48861. */
  48862. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  48863. int rc;
  48864. #ifndef SQLITE_OMIT_INCRBLOB
  48865. if ( pCur->eState==CURSOR_INVALID ){
  48866. return SQLITE_ABORT;
  48867. }
  48868. #endif
  48869. assert( cursorHoldsMutex(pCur) );
  48870. rc = restoreCursorPosition(pCur);
  48871. if( rc==SQLITE_OK ){
  48872. assert( pCur->eState==CURSOR_VALID );
  48873. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  48874. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  48875. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  48876. }
  48877. return rc;
  48878. }
  48879. /*
  48880. ** Return a pointer to payload information from the entry that the
  48881. ** pCur cursor is pointing to. The pointer is to the beginning of
  48882. ** the key if skipKey==0 and it points to the beginning of data if
  48883. ** skipKey==1. The number of bytes of available key/data is written
  48884. ** into *pAmt. If *pAmt==0, then the value returned will not be
  48885. ** a valid pointer.
  48886. **
  48887. ** This routine is an optimization. It is common for the entire key
  48888. ** and data to fit on the local page and for there to be no overflow
  48889. ** pages. When that is so, this routine can be used to access the
  48890. ** key and data without making a copy. If the key and/or data spills
  48891. ** onto overflow pages, then accessPayload() must be used to reassemble
  48892. ** the key/data and copy it into a preallocated buffer.
  48893. **
  48894. ** The pointer returned by this routine looks directly into the cached
  48895. ** page of the database. The data might change or move the next time
  48896. ** any btree routine is called.
  48897. */
  48898. static const unsigned char *fetchPayload(
  48899. BtCursor *pCur, /* Cursor pointing to entry to read from */
  48900. int *pAmt, /* Write the number of available bytes here */
  48901. int skipKey /* read beginning at data if this is true */
  48902. ){
  48903. unsigned char *aPayload;
  48904. MemPage *pPage;
  48905. u32 nKey;
  48906. u32 nLocal;
  48907. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  48908. assert( pCur->eState==CURSOR_VALID );
  48909. assert( cursorHoldsMutex(pCur) );
  48910. pPage = pCur->apPage[pCur->iPage];
  48911. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  48912. if( NEVER(pCur->info.nSize==0) ){
  48913. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  48914. &pCur->info);
  48915. }
  48916. aPayload = pCur->info.pCell;
  48917. aPayload += pCur->info.nHeader;
  48918. if( pPage->intKey ){
  48919. nKey = 0;
  48920. }else{
  48921. nKey = (int)pCur->info.nKey;
  48922. }
  48923. if( skipKey ){
  48924. aPayload += nKey;
  48925. nLocal = pCur->info.nLocal - nKey;
  48926. }else{
  48927. nLocal = pCur->info.nLocal;
  48928. assert( nLocal<=nKey );
  48929. }
  48930. *pAmt = nLocal;
  48931. return aPayload;
  48932. }
  48933. /*
  48934. ** For the entry that cursor pCur is point to, return as
  48935. ** many bytes of the key or data as are available on the local
  48936. ** b-tree page. Write the number of available bytes into *pAmt.
  48937. **
  48938. ** The pointer returned is ephemeral. The key/data may move
  48939. ** or be destroyed on the next call to any Btree routine,
  48940. ** including calls from other threads against the same cache.
  48941. ** Hence, a mutex on the BtShared should be held prior to calling
  48942. ** this routine.
  48943. **
  48944. ** These routines is used to get quick access to key and data
  48945. ** in the common case where no overflow pages are used.
  48946. */
  48947. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  48948. const void *p = 0;
  48949. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  48950. assert( cursorHoldsMutex(pCur) );
  48951. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  48952. p = (const void*)fetchPayload(pCur, pAmt, 0);
  48953. }
  48954. return p;
  48955. }
  48956. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  48957. const void *p = 0;
  48958. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  48959. assert( cursorHoldsMutex(pCur) );
  48960. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  48961. p = (const void*)fetchPayload(pCur, pAmt, 1);
  48962. }
  48963. return p;
  48964. }
  48965. /*
  48966. ** Move the cursor down to a new child page. The newPgno argument is the
  48967. ** page number of the child page to move to.
  48968. **
  48969. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  48970. ** the new child page does not match the flags field of the parent (i.e.
  48971. ** if an intkey page appears to be the parent of a non-intkey page, or
  48972. ** vice-versa).
  48973. */
  48974. static int moveToChild(BtCursor *pCur, u32 newPgno){
  48975. int rc;
  48976. int i = pCur->iPage;
  48977. MemPage *pNewPage;
  48978. BtShared *pBt = pCur->pBt;
  48979. assert( cursorHoldsMutex(pCur) );
  48980. assert( pCur->eState==CURSOR_VALID );
  48981. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  48982. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  48983. return SQLITE_CORRUPT_BKPT;
  48984. }
  48985. rc = getAndInitPage(pBt, newPgno, &pNewPage);
  48986. if( rc ) return rc;
  48987. pCur->apPage[i+1] = pNewPage;
  48988. pCur->aiIdx[i+1] = 0;
  48989. pCur->iPage++;
  48990. pCur->info.nSize = 0;
  48991. pCur->validNKey = 0;
  48992. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  48993. return SQLITE_CORRUPT_BKPT;
  48994. }
  48995. return SQLITE_OK;
  48996. }
  48997. #if 0
  48998. /*
  48999. ** Page pParent is an internal (non-leaf) tree page. This function
  49000. ** asserts that page number iChild is the left-child if the iIdx'th
  49001. ** cell in page pParent. Or, if iIdx is equal to the total number of
  49002. ** cells in pParent, that page number iChild is the right-child of
  49003. ** the page.
  49004. */
  49005. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  49006. assert( iIdx<=pParent->nCell );
  49007. if( iIdx==pParent->nCell ){
  49008. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  49009. }else{
  49010. assert( get4byte(findCell(pParent, iIdx))==iChild );
  49011. }
  49012. }
  49013. #else
  49014. # define assertParentIndex(x,y,z)
  49015. #endif
  49016. /*
  49017. ** Move the cursor up to the parent page.
  49018. **
  49019. ** pCur->idx is set to the cell index that contains the pointer
  49020. ** to the page we are coming from. If we are coming from the
  49021. ** right-most child page then pCur->idx is set to one more than
  49022. ** the largest cell index.
  49023. */
  49024. static void moveToParent(BtCursor *pCur){
  49025. assert( cursorHoldsMutex(pCur) );
  49026. assert( pCur->eState==CURSOR_VALID );
  49027. assert( pCur->iPage>0 );
  49028. assert( pCur->apPage[pCur->iPage] );
  49029. /* UPDATE: It is actually possible for the condition tested by the assert
  49030. ** below to be untrue if the database file is corrupt. This can occur if
  49031. ** one cursor has modified page pParent while a reference to it is held
  49032. ** by a second cursor. Which can only happen if a single page is linked
  49033. ** into more than one b-tree structure in a corrupt database. */
  49034. #if 0
  49035. assertParentIndex(
  49036. pCur->apPage[pCur->iPage-1],
  49037. pCur->aiIdx[pCur->iPage-1],
  49038. pCur->apPage[pCur->iPage]->pgno
  49039. );
  49040. #endif
  49041. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  49042. releasePage(pCur->apPage[pCur->iPage]);
  49043. pCur->iPage--;
  49044. pCur->info.nSize = 0;
  49045. pCur->validNKey = 0;
  49046. }
  49047. /*
  49048. ** Move the cursor to point to the root page of its b-tree structure.
  49049. **
  49050. ** If the table has a virtual root page, then the cursor is moved to point
  49051. ** to the virtual root page instead of the actual root page. A table has a
  49052. ** virtual root page when the actual root page contains no cells and a
  49053. ** single child page. This can only happen with the table rooted at page 1.
  49054. **
  49055. ** If the b-tree structure is empty, the cursor state is set to
  49056. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  49057. ** cell located on the root (or virtual root) page and the cursor state
  49058. ** is set to CURSOR_VALID.
  49059. **
  49060. ** If this function returns successfully, it may be assumed that the
  49061. ** page-header flags indicate that the [virtual] root-page is the expected
  49062. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  49063. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  49064. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  49065. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  49066. ** b-tree).
  49067. */
  49068. static int moveToRoot(BtCursor *pCur){
  49069. MemPage *pRoot;
  49070. int rc = SQLITE_OK;
  49071. Btree *p = pCur->pBtree;
  49072. BtShared *pBt = p->pBt;
  49073. assert( cursorHoldsMutex(pCur) );
  49074. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  49075. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  49076. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  49077. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  49078. if( pCur->eState==CURSOR_FAULT ){
  49079. assert( pCur->skipNext!=SQLITE_OK );
  49080. return pCur->skipNext;
  49081. }
  49082. sqlite3BtreeClearCursor(pCur);
  49083. }
  49084. if( pCur->iPage>=0 ){
  49085. int i;
  49086. for(i=1; i<=pCur->iPage; i++){
  49087. releasePage(pCur->apPage[i]);
  49088. }
  49089. pCur->iPage = 0;
  49090. }else if( pCur->pgnoRoot==0 ){
  49091. pCur->eState = CURSOR_INVALID;
  49092. return SQLITE_OK;
  49093. }else{
  49094. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
  49095. if( rc!=SQLITE_OK ){
  49096. pCur->eState = CURSOR_INVALID;
  49097. return rc;
  49098. }
  49099. pCur->iPage = 0;
  49100. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  49101. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  49102. ** NULL, the caller expects a table b-tree. If this is not the case,
  49103. ** return an SQLITE_CORRUPT error. */
  49104. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  49105. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  49106. return SQLITE_CORRUPT_BKPT;
  49107. }
  49108. }
  49109. /* Assert that the root page is of the correct type. This must be the
  49110. ** case as the call to this function that loaded the root-page (either
  49111. ** this call or a previous invocation) would have detected corruption
  49112. ** if the assumption were not true, and it is not possible for the flags
  49113. ** byte to have been modified while this cursor is holding a reference
  49114. ** to the page. */
  49115. pRoot = pCur->apPage[0];
  49116. assert( pRoot->pgno==pCur->pgnoRoot );
  49117. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  49118. pCur->aiIdx[0] = 0;
  49119. pCur->info.nSize = 0;
  49120. pCur->atLast = 0;
  49121. pCur->validNKey = 0;
  49122. if( pRoot->nCell==0 && !pRoot->leaf ){
  49123. Pgno subpage;
  49124. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  49125. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  49126. pCur->eState = CURSOR_VALID;
  49127. rc = moveToChild(pCur, subpage);
  49128. }else{
  49129. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  49130. }
  49131. return rc;
  49132. }
  49133. /*
  49134. ** Move the cursor down to the left-most leaf entry beneath the
  49135. ** entry to which it is currently pointing.
  49136. **
  49137. ** The left-most leaf is the one with the smallest key - the first
  49138. ** in ascending order.
  49139. */
  49140. static int moveToLeftmost(BtCursor *pCur){
  49141. Pgno pgno;
  49142. int rc = SQLITE_OK;
  49143. MemPage *pPage;
  49144. assert( cursorHoldsMutex(pCur) );
  49145. assert( pCur->eState==CURSOR_VALID );
  49146. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  49147. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  49148. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  49149. rc = moveToChild(pCur, pgno);
  49150. }
  49151. return rc;
  49152. }
  49153. /*
  49154. ** Move the cursor down to the right-most leaf entry beneath the
  49155. ** page to which it is currently pointing. Notice the difference
  49156. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  49157. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  49158. ** finds the right-most entry beneath the *page*.
  49159. **
  49160. ** The right-most entry is the one with the largest key - the last
  49161. ** key in ascending order.
  49162. */
  49163. static int moveToRightmost(BtCursor *pCur){
  49164. Pgno pgno;
  49165. int rc = SQLITE_OK;
  49166. MemPage *pPage = 0;
  49167. assert( cursorHoldsMutex(pCur) );
  49168. assert( pCur->eState==CURSOR_VALID );
  49169. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  49170. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  49171. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  49172. rc = moveToChild(pCur, pgno);
  49173. }
  49174. if( rc==SQLITE_OK ){
  49175. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  49176. pCur->info.nSize = 0;
  49177. pCur->validNKey = 0;
  49178. }
  49179. return rc;
  49180. }
  49181. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  49182. ** on success. Set *pRes to 0 if the cursor actually points to something
  49183. ** or set *pRes to 1 if the table is empty.
  49184. */
  49185. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  49186. int rc;
  49187. assert( cursorHoldsMutex(pCur) );
  49188. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  49189. rc = moveToRoot(pCur);
  49190. if( rc==SQLITE_OK ){
  49191. if( pCur->eState==CURSOR_INVALID ){
  49192. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  49193. *pRes = 1;
  49194. }else{
  49195. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  49196. *pRes = 0;
  49197. rc = moveToLeftmost(pCur);
  49198. }
  49199. }
  49200. return rc;
  49201. }
  49202. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  49203. ** on success. Set *pRes to 0 if the cursor actually points to something
  49204. ** or set *pRes to 1 if the table is empty.
  49205. */
  49206. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  49207. int rc;
  49208. assert( cursorHoldsMutex(pCur) );
  49209. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  49210. /* If the cursor already points to the last entry, this is a no-op. */
  49211. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  49212. #ifdef SQLITE_DEBUG
  49213. /* This block serves to assert() that the cursor really does point
  49214. ** to the last entry in the b-tree. */
  49215. int ii;
  49216. for(ii=0; ii<pCur->iPage; ii++){
  49217. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  49218. }
  49219. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  49220. assert( pCur->apPage[pCur->iPage]->leaf );
  49221. #endif
  49222. return SQLITE_OK;
  49223. }
  49224. rc = moveToRoot(pCur);
  49225. if( rc==SQLITE_OK ){
  49226. if( CURSOR_INVALID==pCur->eState ){
  49227. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  49228. *pRes = 1;
  49229. }else{
  49230. assert( pCur->eState==CURSOR_VALID );
  49231. *pRes = 0;
  49232. rc = moveToRightmost(pCur);
  49233. pCur->atLast = rc==SQLITE_OK ?1:0;
  49234. }
  49235. }
  49236. return rc;
  49237. }
  49238. /* Move the cursor so that it points to an entry near the key
  49239. ** specified by pIdxKey or intKey. Return a success code.
  49240. **
  49241. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  49242. ** must be NULL. For index tables, pIdxKey is used and intKey
  49243. ** is ignored.
  49244. **
  49245. ** If an exact match is not found, then the cursor is always
  49246. ** left pointing at a leaf page which would hold the entry if it
  49247. ** were present. The cursor might point to an entry that comes
  49248. ** before or after the key.
  49249. **
  49250. ** An integer is written into *pRes which is the result of
  49251. ** comparing the key with the entry to which the cursor is
  49252. ** pointing. The meaning of the integer written into
  49253. ** *pRes is as follows:
  49254. **
  49255. ** *pRes<0 The cursor is left pointing at an entry that
  49256. ** is smaller than intKey/pIdxKey or if the table is empty
  49257. ** and the cursor is therefore left point to nothing.
  49258. **
  49259. ** *pRes==0 The cursor is left pointing at an entry that
  49260. ** exactly matches intKey/pIdxKey.
  49261. **
  49262. ** *pRes>0 The cursor is left pointing at an entry that
  49263. ** is larger than intKey/pIdxKey.
  49264. **
  49265. */
  49266. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  49267. BtCursor *pCur, /* The cursor to be moved */
  49268. UnpackedRecord *pIdxKey, /* Unpacked index key */
  49269. i64 intKey, /* The table key */
  49270. int biasRight, /* If true, bias the search to the high end */
  49271. int *pRes /* Write search results here */
  49272. ){
  49273. int rc;
  49274. assert( cursorHoldsMutex(pCur) );
  49275. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  49276. assert( pRes );
  49277. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  49278. /* If the cursor is already positioned at the point we are trying
  49279. ** to move to, then just return without doing any work */
  49280. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  49281. && pCur->apPage[0]->intKey
  49282. ){
  49283. if( pCur->info.nKey==intKey ){
  49284. *pRes = 0;
  49285. return SQLITE_OK;
  49286. }
  49287. if( pCur->atLast && pCur->info.nKey<intKey ){
  49288. *pRes = -1;
  49289. return SQLITE_OK;
  49290. }
  49291. }
  49292. rc = moveToRoot(pCur);
  49293. if( rc ){
  49294. return rc;
  49295. }
  49296. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  49297. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  49298. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  49299. if( pCur->eState==CURSOR_INVALID ){
  49300. *pRes = -1;
  49301. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  49302. return SQLITE_OK;
  49303. }
  49304. assert( pCur->apPage[0]->intKey || pIdxKey );
  49305. for(;;){
  49306. int lwr, upr, idx;
  49307. Pgno chldPg;
  49308. MemPage *pPage = pCur->apPage[pCur->iPage];
  49309. int c;
  49310. /* pPage->nCell must be greater than zero. If this is the root-page
  49311. ** the cursor would have been INVALID above and this for(;;) loop
  49312. ** not run. If this is not the root-page, then the moveToChild() routine
  49313. ** would have already detected db corruption. Similarly, pPage must
  49314. ** be the right kind (index or table) of b-tree page. Otherwise
  49315. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  49316. assert( pPage->nCell>0 );
  49317. assert( pPage->intKey==(pIdxKey==0) );
  49318. lwr = 0;
  49319. upr = pPage->nCell-1;
  49320. if( biasRight ){
  49321. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  49322. }else{
  49323. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  49324. }
  49325. for(;;){
  49326. u8 *pCell; /* Pointer to current cell in pPage */
  49327. assert( idx==pCur->aiIdx[pCur->iPage] );
  49328. pCur->info.nSize = 0;
  49329. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  49330. if( pPage->intKey ){
  49331. i64 nCellKey;
  49332. if( pPage->hasData ){
  49333. u32 dummy;
  49334. pCell += getVarint32(pCell, dummy);
  49335. }
  49336. getVarint(pCell, (u64*)&nCellKey);
  49337. if( nCellKey==intKey ){
  49338. c = 0;
  49339. }else if( nCellKey<intKey ){
  49340. c = -1;
  49341. }else{
  49342. assert( nCellKey>intKey );
  49343. c = +1;
  49344. }
  49345. pCur->validNKey = 1;
  49346. pCur->info.nKey = nCellKey;
  49347. }else{
  49348. /* The maximum supported page-size is 65536 bytes. This means that
  49349. ** the maximum number of record bytes stored on an index B-Tree
  49350. ** page is less than 16384 bytes and may be stored as a 2-byte
  49351. ** varint. This information is used to attempt to avoid parsing
  49352. ** the entire cell by checking for the cases where the record is
  49353. ** stored entirely within the b-tree page by inspecting the first
  49354. ** 2 bytes of the cell.
  49355. */
  49356. int nCell = pCell[0];
  49357. if( nCell<=pPage->max1bytePayload
  49358. /* && (pCell+nCell)<pPage->aDataEnd */
  49359. ){
  49360. /* This branch runs if the record-size field of the cell is a
  49361. ** single byte varint and the record fits entirely on the main
  49362. ** b-tree page. */
  49363. testcase( pCell+nCell+1==pPage->aDataEnd );
  49364. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  49365. }else if( !(pCell[1] & 0x80)
  49366. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  49367. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  49368. ){
  49369. /* The record-size field is a 2 byte varint and the record
  49370. ** fits entirely on the main b-tree page. */
  49371. testcase( pCell+nCell+2==pPage->aDataEnd );
  49372. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  49373. }else{
  49374. /* The record flows over onto one or more overflow pages. In
  49375. ** this case the whole cell needs to be parsed, a buffer allocated
  49376. ** and accessPayload() used to retrieve the record into the
  49377. ** buffer before VdbeRecordCompare() can be called. */
  49378. void *pCellKey;
  49379. u8 * const pCellBody = pCell - pPage->childPtrSize;
  49380. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  49381. nCell = (int)pCur->info.nKey;
  49382. pCellKey = sqlite3Malloc( nCell );
  49383. if( pCellKey==0 ){
  49384. rc = SQLITE_NOMEM;
  49385. goto moveto_finish;
  49386. }
  49387. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  49388. if( rc ){
  49389. sqlite3_free(pCellKey);
  49390. goto moveto_finish;
  49391. }
  49392. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  49393. sqlite3_free(pCellKey);
  49394. }
  49395. }
  49396. if( c==0 ){
  49397. if( pPage->intKey && !pPage->leaf ){
  49398. lwr = idx;
  49399. break;
  49400. }else{
  49401. *pRes = 0;
  49402. rc = SQLITE_OK;
  49403. goto moveto_finish;
  49404. }
  49405. }
  49406. if( c<0 ){
  49407. lwr = idx+1;
  49408. }else{
  49409. upr = idx-1;
  49410. }
  49411. if( lwr>upr ){
  49412. break;
  49413. }
  49414. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  49415. }
  49416. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  49417. assert( pPage->isInit );
  49418. if( pPage->leaf ){
  49419. chldPg = 0;
  49420. }else if( lwr>=pPage->nCell ){
  49421. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  49422. }else{
  49423. chldPg = get4byte(findCell(pPage, lwr));
  49424. }
  49425. if( chldPg==0 ){
  49426. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  49427. *pRes = c;
  49428. rc = SQLITE_OK;
  49429. goto moveto_finish;
  49430. }
  49431. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  49432. pCur->info.nSize = 0;
  49433. pCur->validNKey = 0;
  49434. rc = moveToChild(pCur, chldPg);
  49435. if( rc ) goto moveto_finish;
  49436. }
  49437. moveto_finish:
  49438. return rc;
  49439. }
  49440. /*
  49441. ** Return TRUE if the cursor is not pointing at an entry of the table.
  49442. **
  49443. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  49444. ** past the last entry in the table or sqlite3BtreePrev() moves past
  49445. ** the first entry. TRUE is also returned if the table is empty.
  49446. */
  49447. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  49448. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  49449. ** have been deleted? This API will need to change to return an error code
  49450. ** as well as the boolean result value.
  49451. */
  49452. return (CURSOR_VALID!=pCur->eState);
  49453. }
  49454. /*
  49455. ** Advance the cursor to the next entry in the database. If
  49456. ** successful then set *pRes=0. If the cursor
  49457. ** was already pointing to the last entry in the database before
  49458. ** this routine was called, then set *pRes=1.
  49459. */
  49460. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  49461. int rc;
  49462. int idx;
  49463. MemPage *pPage;
  49464. assert( cursorHoldsMutex(pCur) );
  49465. rc = restoreCursorPosition(pCur);
  49466. if( rc!=SQLITE_OK ){
  49467. return rc;
  49468. }
  49469. assert( pRes!=0 );
  49470. if( CURSOR_INVALID==pCur->eState ){
  49471. *pRes = 1;
  49472. return SQLITE_OK;
  49473. }
  49474. if( pCur->skipNext>0 ){
  49475. pCur->skipNext = 0;
  49476. *pRes = 0;
  49477. return SQLITE_OK;
  49478. }
  49479. pCur->skipNext = 0;
  49480. pPage = pCur->apPage[pCur->iPage];
  49481. idx = ++pCur->aiIdx[pCur->iPage];
  49482. assert( pPage->isInit );
  49483. /* If the database file is corrupt, it is possible for the value of idx
  49484. ** to be invalid here. This can only occur if a second cursor modifies
  49485. ** the page while cursor pCur is holding a reference to it. Which can
  49486. ** only happen if the database is corrupt in such a way as to link the
  49487. ** page into more than one b-tree structure. */
  49488. testcase( idx>pPage->nCell );
  49489. pCur->info.nSize = 0;
  49490. pCur->validNKey = 0;
  49491. if( idx>=pPage->nCell ){
  49492. if( !pPage->leaf ){
  49493. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  49494. if( rc ) return rc;
  49495. rc = moveToLeftmost(pCur);
  49496. *pRes = 0;
  49497. return rc;
  49498. }
  49499. do{
  49500. if( pCur->iPage==0 ){
  49501. *pRes = 1;
  49502. pCur->eState = CURSOR_INVALID;
  49503. return SQLITE_OK;
  49504. }
  49505. moveToParent(pCur);
  49506. pPage = pCur->apPage[pCur->iPage];
  49507. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  49508. *pRes = 0;
  49509. if( pPage->intKey ){
  49510. rc = sqlite3BtreeNext(pCur, pRes);
  49511. }else{
  49512. rc = SQLITE_OK;
  49513. }
  49514. return rc;
  49515. }
  49516. *pRes = 0;
  49517. if( pPage->leaf ){
  49518. return SQLITE_OK;
  49519. }
  49520. rc = moveToLeftmost(pCur);
  49521. return rc;
  49522. }
  49523. /*
  49524. ** Step the cursor to the back to the previous entry in the database. If
  49525. ** successful then set *pRes=0. If the cursor
  49526. ** was already pointing to the first entry in the database before
  49527. ** this routine was called, then set *pRes=1.
  49528. */
  49529. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  49530. int rc;
  49531. MemPage *pPage;
  49532. assert( cursorHoldsMutex(pCur) );
  49533. rc = restoreCursorPosition(pCur);
  49534. if( rc!=SQLITE_OK ){
  49535. return rc;
  49536. }
  49537. pCur->atLast = 0;
  49538. if( CURSOR_INVALID==pCur->eState ){
  49539. *pRes = 1;
  49540. return SQLITE_OK;
  49541. }
  49542. if( pCur->skipNext<0 ){
  49543. pCur->skipNext = 0;
  49544. *pRes = 0;
  49545. return SQLITE_OK;
  49546. }
  49547. pCur->skipNext = 0;
  49548. pPage = pCur->apPage[pCur->iPage];
  49549. assert( pPage->isInit );
  49550. if( !pPage->leaf ){
  49551. int idx = pCur->aiIdx[pCur->iPage];
  49552. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  49553. if( rc ){
  49554. return rc;
  49555. }
  49556. rc = moveToRightmost(pCur);
  49557. }else{
  49558. while( pCur->aiIdx[pCur->iPage]==0 ){
  49559. if( pCur->iPage==0 ){
  49560. pCur->eState = CURSOR_INVALID;
  49561. *pRes = 1;
  49562. return SQLITE_OK;
  49563. }
  49564. moveToParent(pCur);
  49565. }
  49566. pCur->info.nSize = 0;
  49567. pCur->validNKey = 0;
  49568. pCur->aiIdx[pCur->iPage]--;
  49569. pPage = pCur->apPage[pCur->iPage];
  49570. if( pPage->intKey && !pPage->leaf ){
  49571. rc = sqlite3BtreePrevious(pCur, pRes);
  49572. }else{
  49573. rc = SQLITE_OK;
  49574. }
  49575. }
  49576. *pRes = 0;
  49577. return rc;
  49578. }
  49579. /*
  49580. ** Allocate a new page from the database file.
  49581. **
  49582. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  49583. ** has already been called on the new page.) The new page has also
  49584. ** been referenced and the calling routine is responsible for calling
  49585. ** sqlite3PagerUnref() on the new page when it is done.
  49586. **
  49587. ** SQLITE_OK is returned on success. Any other return value indicates
  49588. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  49589. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  49590. **
  49591. ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
  49592. ** locate a page close to the page number "nearby". This can be used in an
  49593. ** attempt to keep related pages close to each other in the database file,
  49594. ** which in turn can make database access faster.
  49595. **
  49596. ** If the "exact" parameter is not 0, and the page-number nearby exists
  49597. ** anywhere on the free-list, then it is guarenteed to be returned. This
  49598. ** is only used by auto-vacuum databases when allocating a new table.
  49599. */
  49600. static int allocateBtreePage(
  49601. BtShared *pBt,
  49602. MemPage **ppPage,
  49603. Pgno *pPgno,
  49604. Pgno nearby,
  49605. u8 exact
  49606. ){
  49607. MemPage *pPage1;
  49608. int rc;
  49609. u32 n; /* Number of pages on the freelist */
  49610. u32 k; /* Number of leaves on the trunk of the freelist */
  49611. MemPage *pTrunk = 0;
  49612. MemPage *pPrevTrunk = 0;
  49613. Pgno mxPage; /* Total size of the database file */
  49614. assert( sqlite3_mutex_held(pBt->mutex) );
  49615. pPage1 = pBt->pPage1;
  49616. mxPage = btreePagecount(pBt);
  49617. n = get4byte(&pPage1->aData[36]);
  49618. testcase( n==mxPage-1 );
  49619. if( n>=mxPage ){
  49620. return SQLITE_CORRUPT_BKPT;
  49621. }
  49622. if( n>0 ){
  49623. /* There are pages on the freelist. Reuse one of those pages. */
  49624. Pgno iTrunk;
  49625. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  49626. /* If the 'exact' parameter was true and a query of the pointer-map
  49627. ** shows that the page 'nearby' is somewhere on the free-list, then
  49628. ** the entire-list will be searched for that page.
  49629. */
  49630. #ifndef SQLITE_OMIT_AUTOVACUUM
  49631. if( exact && nearby<=mxPage ){
  49632. u8 eType;
  49633. assert( nearby>0 );
  49634. assert( pBt->autoVacuum );
  49635. rc = ptrmapGet(pBt, nearby, &eType, 0);
  49636. if( rc ) return rc;
  49637. if( eType==PTRMAP_FREEPAGE ){
  49638. searchList = 1;
  49639. }
  49640. *pPgno = nearby;
  49641. }
  49642. #endif
  49643. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  49644. ** first free-list trunk page. iPrevTrunk is initially 1.
  49645. */
  49646. rc = sqlite3PagerWrite(pPage1->pDbPage);
  49647. if( rc ) return rc;
  49648. put4byte(&pPage1->aData[36], n-1);
  49649. /* The code within this loop is run only once if the 'searchList' variable
  49650. ** is not true. Otherwise, it runs once for each trunk-page on the
  49651. ** free-list until the page 'nearby' is located.
  49652. */
  49653. do {
  49654. pPrevTrunk = pTrunk;
  49655. if( pPrevTrunk ){
  49656. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  49657. }else{
  49658. iTrunk = get4byte(&pPage1->aData[32]);
  49659. }
  49660. testcase( iTrunk==mxPage );
  49661. if( iTrunk>mxPage ){
  49662. rc = SQLITE_CORRUPT_BKPT;
  49663. }else{
  49664. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  49665. }
  49666. if( rc ){
  49667. pTrunk = 0;
  49668. goto end_allocate_page;
  49669. }
  49670. assert( pTrunk!=0 );
  49671. assert( pTrunk->aData!=0 );
  49672. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  49673. if( k==0 && !searchList ){
  49674. /* The trunk has no leaves and the list is not being searched.
  49675. ** So extract the trunk page itself and use it as the newly
  49676. ** allocated page */
  49677. assert( pPrevTrunk==0 );
  49678. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  49679. if( rc ){
  49680. goto end_allocate_page;
  49681. }
  49682. *pPgno = iTrunk;
  49683. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  49684. *ppPage = pTrunk;
  49685. pTrunk = 0;
  49686. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  49687. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  49688. /* Value of k is out of range. Database corruption */
  49689. rc = SQLITE_CORRUPT_BKPT;
  49690. goto end_allocate_page;
  49691. #ifndef SQLITE_OMIT_AUTOVACUUM
  49692. }else if( searchList && nearby==iTrunk ){
  49693. /* The list is being searched and this trunk page is the page
  49694. ** to allocate, regardless of whether it has leaves.
  49695. */
  49696. assert( *pPgno==iTrunk );
  49697. *ppPage = pTrunk;
  49698. searchList = 0;
  49699. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  49700. if( rc ){
  49701. goto end_allocate_page;
  49702. }
  49703. if( k==0 ){
  49704. if( !pPrevTrunk ){
  49705. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  49706. }else{
  49707. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  49708. if( rc!=SQLITE_OK ){
  49709. goto end_allocate_page;
  49710. }
  49711. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  49712. }
  49713. }else{
  49714. /* The trunk page is required by the caller but it contains
  49715. ** pointers to free-list leaves. The first leaf becomes a trunk
  49716. ** page in this case.
  49717. */
  49718. MemPage *pNewTrunk;
  49719. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  49720. if( iNewTrunk>mxPage ){
  49721. rc = SQLITE_CORRUPT_BKPT;
  49722. goto end_allocate_page;
  49723. }
  49724. testcase( iNewTrunk==mxPage );
  49725. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  49726. if( rc!=SQLITE_OK ){
  49727. goto end_allocate_page;
  49728. }
  49729. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  49730. if( rc!=SQLITE_OK ){
  49731. releasePage(pNewTrunk);
  49732. goto end_allocate_page;
  49733. }
  49734. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  49735. put4byte(&pNewTrunk->aData[4], k-1);
  49736. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  49737. releasePage(pNewTrunk);
  49738. if( !pPrevTrunk ){
  49739. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  49740. put4byte(&pPage1->aData[32], iNewTrunk);
  49741. }else{
  49742. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  49743. if( rc ){
  49744. goto end_allocate_page;
  49745. }
  49746. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  49747. }
  49748. }
  49749. pTrunk = 0;
  49750. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  49751. #endif
  49752. }else if( k>0 ){
  49753. /* Extract a leaf from the trunk */
  49754. u32 closest;
  49755. Pgno iPage;
  49756. unsigned char *aData = pTrunk->aData;
  49757. if( nearby>0 ){
  49758. u32 i;
  49759. int dist;
  49760. closest = 0;
  49761. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  49762. for(i=1; i<k; i++){
  49763. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  49764. if( d2<dist ){
  49765. closest = i;
  49766. dist = d2;
  49767. }
  49768. }
  49769. }else{
  49770. closest = 0;
  49771. }
  49772. iPage = get4byte(&aData[8+closest*4]);
  49773. testcase( iPage==mxPage );
  49774. if( iPage>mxPage ){
  49775. rc = SQLITE_CORRUPT_BKPT;
  49776. goto end_allocate_page;
  49777. }
  49778. testcase( iPage==mxPage );
  49779. if( !searchList || iPage==nearby ){
  49780. int noContent;
  49781. *pPgno = iPage;
  49782. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  49783. ": %d more free pages\n",
  49784. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  49785. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  49786. if( rc ) goto end_allocate_page;
  49787. if( closest<k-1 ){
  49788. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  49789. }
  49790. put4byte(&aData[4], k-1);
  49791. noContent = !btreeGetHasContent(pBt, *pPgno);
  49792. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  49793. if( rc==SQLITE_OK ){
  49794. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  49795. if( rc!=SQLITE_OK ){
  49796. releasePage(*ppPage);
  49797. }
  49798. }
  49799. searchList = 0;
  49800. }
  49801. }
  49802. releasePage(pPrevTrunk);
  49803. pPrevTrunk = 0;
  49804. }while( searchList );
  49805. }else{
  49806. /* There are no pages on the freelist, so create a new page at the
  49807. ** end of the file */
  49808. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  49809. if( rc ) return rc;
  49810. pBt->nPage++;
  49811. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  49812. #ifndef SQLITE_OMIT_AUTOVACUUM
  49813. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  49814. /* If *pPgno refers to a pointer-map page, allocate two new pages
  49815. ** at the end of the file instead of one. The first allocated page
  49816. ** becomes a new pointer-map page, the second is used by the caller.
  49817. */
  49818. MemPage *pPg = 0;
  49819. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  49820. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  49821. rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
  49822. if( rc==SQLITE_OK ){
  49823. rc = sqlite3PagerWrite(pPg->pDbPage);
  49824. releasePage(pPg);
  49825. }
  49826. if( rc ) return rc;
  49827. pBt->nPage++;
  49828. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  49829. }
  49830. #endif
  49831. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  49832. *pPgno = pBt->nPage;
  49833. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  49834. rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
  49835. if( rc ) return rc;
  49836. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  49837. if( rc!=SQLITE_OK ){
  49838. releasePage(*ppPage);
  49839. }
  49840. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  49841. }
  49842. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  49843. end_allocate_page:
  49844. releasePage(pTrunk);
  49845. releasePage(pPrevTrunk);
  49846. if( rc==SQLITE_OK ){
  49847. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  49848. releasePage(*ppPage);
  49849. return SQLITE_CORRUPT_BKPT;
  49850. }
  49851. (*ppPage)->isInit = 0;
  49852. }else{
  49853. *ppPage = 0;
  49854. }
  49855. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  49856. return rc;
  49857. }
  49858. /*
  49859. ** This function is used to add page iPage to the database file free-list.
  49860. ** It is assumed that the page is not already a part of the free-list.
  49861. **
  49862. ** The value passed as the second argument to this function is optional.
  49863. ** If the caller happens to have a pointer to the MemPage object
  49864. ** corresponding to page iPage handy, it may pass it as the second value.
  49865. ** Otherwise, it may pass NULL.
  49866. **
  49867. ** If a pointer to a MemPage object is passed as the second argument,
  49868. ** its reference count is not altered by this function.
  49869. */
  49870. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  49871. MemPage *pTrunk = 0; /* Free-list trunk page */
  49872. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  49873. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  49874. MemPage *pPage; /* Page being freed. May be NULL. */
  49875. int rc; /* Return Code */
  49876. int nFree; /* Initial number of pages on free-list */
  49877. assert( sqlite3_mutex_held(pBt->mutex) );
  49878. assert( iPage>1 );
  49879. assert( !pMemPage || pMemPage->pgno==iPage );
  49880. if( pMemPage ){
  49881. pPage = pMemPage;
  49882. sqlite3PagerRef(pPage->pDbPage);
  49883. }else{
  49884. pPage = btreePageLookup(pBt, iPage);
  49885. }
  49886. /* Increment the free page count on pPage1 */
  49887. rc = sqlite3PagerWrite(pPage1->pDbPage);
  49888. if( rc ) goto freepage_out;
  49889. nFree = get4byte(&pPage1->aData[36]);
  49890. put4byte(&pPage1->aData[36], nFree+1);
  49891. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  49892. /* If the secure_delete option is enabled, then
  49893. ** always fully overwrite deleted information with zeros.
  49894. */
  49895. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  49896. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  49897. ){
  49898. goto freepage_out;
  49899. }
  49900. memset(pPage->aData, 0, pPage->pBt->pageSize);
  49901. }
  49902. /* If the database supports auto-vacuum, write an entry in the pointer-map
  49903. ** to indicate that the page is free.
  49904. */
  49905. if( ISAUTOVACUUM ){
  49906. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  49907. if( rc ) goto freepage_out;
  49908. }
  49909. /* Now manipulate the actual database free-list structure. There are two
  49910. ** possibilities. If the free-list is currently empty, or if the first
  49911. ** trunk page in the free-list is full, then this page will become a
  49912. ** new free-list trunk page. Otherwise, it will become a leaf of the
  49913. ** first trunk page in the current free-list. This block tests if it
  49914. ** is possible to add the page as a new free-list leaf.
  49915. */
  49916. if( nFree!=0 ){
  49917. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  49918. iTrunk = get4byte(&pPage1->aData[32]);
  49919. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  49920. if( rc!=SQLITE_OK ){
  49921. goto freepage_out;
  49922. }
  49923. nLeaf = get4byte(&pTrunk->aData[4]);
  49924. assert( pBt->usableSize>32 );
  49925. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  49926. rc = SQLITE_CORRUPT_BKPT;
  49927. goto freepage_out;
  49928. }
  49929. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  49930. /* In this case there is room on the trunk page to insert the page
  49931. ** being freed as a new leaf.
  49932. **
  49933. ** Note that the trunk page is not really full until it contains
  49934. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  49935. ** coded. But due to a coding error in versions of SQLite prior to
  49936. ** 3.6.0, databases with freelist trunk pages holding more than
  49937. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  49938. ** to maintain backwards compatibility with older versions of SQLite,
  49939. ** we will continue to restrict the number of entries to usableSize/4 - 8
  49940. ** for now. At some point in the future (once everyone has upgraded
  49941. ** to 3.6.0 or later) we should consider fixing the conditional above
  49942. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  49943. */
  49944. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  49945. if( rc==SQLITE_OK ){
  49946. put4byte(&pTrunk->aData[4], nLeaf+1);
  49947. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  49948. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  49949. sqlite3PagerDontWrite(pPage->pDbPage);
  49950. }
  49951. rc = btreeSetHasContent(pBt, iPage);
  49952. }
  49953. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  49954. goto freepage_out;
  49955. }
  49956. }
  49957. /* If control flows to this point, then it was not possible to add the
  49958. ** the page being freed as a leaf page of the first trunk in the free-list.
  49959. ** Possibly because the free-list is empty, or possibly because the
  49960. ** first trunk in the free-list is full. Either way, the page being freed
  49961. ** will become the new first trunk page in the free-list.
  49962. */
  49963. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  49964. goto freepage_out;
  49965. }
  49966. rc = sqlite3PagerWrite(pPage->pDbPage);
  49967. if( rc!=SQLITE_OK ){
  49968. goto freepage_out;
  49969. }
  49970. put4byte(pPage->aData, iTrunk);
  49971. put4byte(&pPage->aData[4], 0);
  49972. put4byte(&pPage1->aData[32], iPage);
  49973. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  49974. freepage_out:
  49975. if( pPage ){
  49976. pPage->isInit = 0;
  49977. }
  49978. releasePage(pPage);
  49979. releasePage(pTrunk);
  49980. return rc;
  49981. }
  49982. static void freePage(MemPage *pPage, int *pRC){
  49983. if( (*pRC)==SQLITE_OK ){
  49984. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  49985. }
  49986. }
  49987. /*
  49988. ** Free any overflow pages associated with the given Cell.
  49989. */
  49990. static int clearCell(MemPage *pPage, unsigned char *pCell){
  49991. BtShared *pBt = pPage->pBt;
  49992. CellInfo info;
  49993. Pgno ovflPgno;
  49994. int rc;
  49995. int nOvfl;
  49996. u32 ovflPageSize;
  49997. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49998. btreeParseCellPtr(pPage, pCell, &info);
  49999. if( info.iOverflow==0 ){
  50000. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  50001. }
  50002. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  50003. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  50004. }
  50005. ovflPgno = get4byte(&pCell[info.iOverflow]);
  50006. assert( pBt->usableSize > 4 );
  50007. ovflPageSize = pBt->usableSize - 4;
  50008. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  50009. assert( ovflPgno==0 || nOvfl>0 );
  50010. while( nOvfl-- ){
  50011. Pgno iNext = 0;
  50012. MemPage *pOvfl = 0;
  50013. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  50014. /* 0 is not a legal page number and page 1 cannot be an
  50015. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  50016. ** file the database must be corrupt. */
  50017. return SQLITE_CORRUPT_BKPT;
  50018. }
  50019. if( nOvfl ){
  50020. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  50021. if( rc ) return rc;
  50022. }
  50023. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  50024. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  50025. ){
  50026. /* There is no reason any cursor should have an outstanding reference
  50027. ** to an overflow page belonging to a cell that is being deleted/updated.
  50028. ** So if there exists more than one reference to this page, then it
  50029. ** must not really be an overflow page and the database must be corrupt.
  50030. ** It is helpful to detect this before calling freePage2(), as
  50031. ** freePage2() may zero the page contents if secure-delete mode is
  50032. ** enabled. If this 'overflow' page happens to be a page that the
  50033. ** caller is iterating through or using in some other way, this
  50034. ** can be problematic.
  50035. */
  50036. rc = SQLITE_CORRUPT_BKPT;
  50037. }else{
  50038. rc = freePage2(pBt, pOvfl, ovflPgno);
  50039. }
  50040. if( pOvfl ){
  50041. sqlite3PagerUnref(pOvfl->pDbPage);
  50042. }
  50043. if( rc ) return rc;
  50044. ovflPgno = iNext;
  50045. }
  50046. return SQLITE_OK;
  50047. }
  50048. /*
  50049. ** Create the byte sequence used to represent a cell on page pPage
  50050. ** and write that byte sequence into pCell[]. Overflow pages are
  50051. ** allocated and filled in as necessary. The calling procedure
  50052. ** is responsible for making sure sufficient space has been allocated
  50053. ** for pCell[].
  50054. **
  50055. ** Note that pCell does not necessary need to point to the pPage->aData
  50056. ** area. pCell might point to some temporary storage. The cell will
  50057. ** be constructed in this temporary area then copied into pPage->aData
  50058. ** later.
  50059. */
  50060. static int fillInCell(
  50061. MemPage *pPage, /* The page that contains the cell */
  50062. unsigned char *pCell, /* Complete text of the cell */
  50063. const void *pKey, i64 nKey, /* The key */
  50064. const void *pData,int nData, /* The data */
  50065. int nZero, /* Extra zero bytes to append to pData */
  50066. int *pnSize /* Write cell size here */
  50067. ){
  50068. int nPayload;
  50069. const u8 *pSrc;
  50070. int nSrc, n, rc;
  50071. int spaceLeft;
  50072. MemPage *pOvfl = 0;
  50073. MemPage *pToRelease = 0;
  50074. unsigned char *pPrior;
  50075. unsigned char *pPayload;
  50076. BtShared *pBt = pPage->pBt;
  50077. Pgno pgnoOvfl = 0;
  50078. int nHeader;
  50079. CellInfo info;
  50080. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50081. /* pPage is not necessarily writeable since pCell might be auxiliary
  50082. ** buffer space that is separate from the pPage buffer area */
  50083. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  50084. || sqlite3PagerIswriteable(pPage->pDbPage) );
  50085. /* Fill in the header. */
  50086. nHeader = 0;
  50087. if( !pPage->leaf ){
  50088. nHeader += 4;
  50089. }
  50090. if( pPage->hasData ){
  50091. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  50092. }else{
  50093. nData = nZero = 0;
  50094. }
  50095. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  50096. btreeParseCellPtr(pPage, pCell, &info);
  50097. assert( info.nHeader==nHeader );
  50098. assert( info.nKey==nKey );
  50099. assert( info.nData==(u32)(nData+nZero) );
  50100. /* Fill in the payload */
  50101. nPayload = nData + nZero;
  50102. if( pPage->intKey ){
  50103. pSrc = pData;
  50104. nSrc = nData;
  50105. nData = 0;
  50106. }else{
  50107. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  50108. return SQLITE_CORRUPT_BKPT;
  50109. }
  50110. nPayload += (int)nKey;
  50111. pSrc = pKey;
  50112. nSrc = (int)nKey;
  50113. }
  50114. *pnSize = info.nSize;
  50115. spaceLeft = info.nLocal;
  50116. pPayload = &pCell[nHeader];
  50117. pPrior = &pCell[info.iOverflow];
  50118. while( nPayload>0 ){
  50119. if( spaceLeft==0 ){
  50120. #ifndef SQLITE_OMIT_AUTOVACUUM
  50121. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  50122. if( pBt->autoVacuum ){
  50123. do{
  50124. pgnoOvfl++;
  50125. } while(
  50126. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  50127. );
  50128. }
  50129. #endif
  50130. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  50131. #ifndef SQLITE_OMIT_AUTOVACUUM
  50132. /* If the database supports auto-vacuum, and the second or subsequent
  50133. ** overflow page is being allocated, add an entry to the pointer-map
  50134. ** for that page now.
  50135. **
  50136. ** If this is the first overflow page, then write a partial entry
  50137. ** to the pointer-map. If we write nothing to this pointer-map slot,
  50138. ** then the optimistic overflow chain processing in clearCell()
  50139. ** may misinterpret the uninitialised values and delete the
  50140. ** wrong pages from the database.
  50141. */
  50142. if( pBt->autoVacuum && rc==SQLITE_OK ){
  50143. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  50144. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  50145. if( rc ){
  50146. releasePage(pOvfl);
  50147. }
  50148. }
  50149. #endif
  50150. if( rc ){
  50151. releasePage(pToRelease);
  50152. return rc;
  50153. }
  50154. /* If pToRelease is not zero than pPrior points into the data area
  50155. ** of pToRelease. Make sure pToRelease is still writeable. */
  50156. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  50157. /* If pPrior is part of the data area of pPage, then make sure pPage
  50158. ** is still writeable */
  50159. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  50160. || sqlite3PagerIswriteable(pPage->pDbPage) );
  50161. put4byte(pPrior, pgnoOvfl);
  50162. releasePage(pToRelease);
  50163. pToRelease = pOvfl;
  50164. pPrior = pOvfl->aData;
  50165. put4byte(pPrior, 0);
  50166. pPayload = &pOvfl->aData[4];
  50167. spaceLeft = pBt->usableSize - 4;
  50168. }
  50169. n = nPayload;
  50170. if( n>spaceLeft ) n = spaceLeft;
  50171. /* If pToRelease is not zero than pPayload points into the data area
  50172. ** of pToRelease. Make sure pToRelease is still writeable. */
  50173. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  50174. /* If pPayload is part of the data area of pPage, then make sure pPage
  50175. ** is still writeable */
  50176. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  50177. || sqlite3PagerIswriteable(pPage->pDbPage) );
  50178. if( nSrc>0 ){
  50179. if( n>nSrc ) n = nSrc;
  50180. assert( pSrc );
  50181. memcpy(pPayload, pSrc, n);
  50182. }else{
  50183. memset(pPayload, 0, n);
  50184. }
  50185. nPayload -= n;
  50186. pPayload += n;
  50187. pSrc += n;
  50188. nSrc -= n;
  50189. spaceLeft -= n;
  50190. if( nSrc==0 ){
  50191. nSrc = nData;
  50192. pSrc = pData;
  50193. }
  50194. }
  50195. releasePage(pToRelease);
  50196. return SQLITE_OK;
  50197. }
  50198. /*
  50199. ** Remove the i-th cell from pPage. This routine effects pPage only.
  50200. ** The cell content is not freed or deallocated. It is assumed that
  50201. ** the cell content has been copied someplace else. This routine just
  50202. ** removes the reference to the cell from pPage.
  50203. **
  50204. ** "sz" must be the number of bytes in the cell.
  50205. */
  50206. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  50207. u32 pc; /* Offset to cell content of cell being deleted */
  50208. u8 *data; /* pPage->aData */
  50209. u8 *ptr; /* Used to move bytes around within data[] */
  50210. u8 *endPtr; /* End of loop */
  50211. int rc; /* The return code */
  50212. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  50213. if( *pRC ) return;
  50214. assert( idx>=0 && idx<pPage->nCell );
  50215. assert( sz==cellSize(pPage, idx) );
  50216. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50217. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50218. data = pPage->aData;
  50219. ptr = &pPage->aCellIdx[2*idx];
  50220. pc = get2byte(ptr);
  50221. hdr = pPage->hdrOffset;
  50222. testcase( pc==get2byte(&data[hdr+5]) );
  50223. testcase( pc+sz==pPage->pBt->usableSize );
  50224. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  50225. *pRC = SQLITE_CORRUPT_BKPT;
  50226. return;
  50227. }
  50228. rc = freeSpace(pPage, pc, sz);
  50229. if( rc ){
  50230. *pRC = rc;
  50231. return;
  50232. }
  50233. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  50234. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  50235. while( ptr<endPtr ){
  50236. *(u16*)ptr = *(u16*)&ptr[2];
  50237. ptr += 2;
  50238. }
  50239. pPage->nCell--;
  50240. put2byte(&data[hdr+3], pPage->nCell);
  50241. pPage->nFree += 2;
  50242. }
  50243. /*
  50244. ** Insert a new cell on pPage at cell index "i". pCell points to the
  50245. ** content of the cell.
  50246. **
  50247. ** If the cell content will fit on the page, then put it there. If it
  50248. ** will not fit, then make a copy of the cell content into pTemp if
  50249. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  50250. ** in pPage->apOvfl[] and make it point to the cell content (either
  50251. ** in pTemp or the original pCell) and also record its index.
  50252. ** Allocating a new entry in pPage->aCell[] implies that
  50253. ** pPage->nOverflow is incremented.
  50254. **
  50255. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  50256. ** cell. The caller will overwrite them after this function returns. If
  50257. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  50258. ** (but pCell+nSkip is always valid).
  50259. */
  50260. static void insertCell(
  50261. MemPage *pPage, /* Page into which we are copying */
  50262. int i, /* New cell becomes the i-th cell of the page */
  50263. u8 *pCell, /* Content of the new cell */
  50264. int sz, /* Bytes of content in pCell */
  50265. u8 *pTemp, /* Temp storage space for pCell, if needed */
  50266. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  50267. int *pRC /* Read and write return code from here */
  50268. ){
  50269. int idx = 0; /* Where to write new cell content in data[] */
  50270. int j; /* Loop counter */
  50271. int end; /* First byte past the last cell pointer in data[] */
  50272. int ins; /* Index in data[] where new cell pointer is inserted */
  50273. int cellOffset; /* Address of first cell pointer in data[] */
  50274. u8 *data; /* The content of the whole page */
  50275. u8 *ptr; /* Used for moving information around in data[] */
  50276. u8 *endPtr; /* End of the loop */
  50277. int nSkip = (iChild ? 4 : 0);
  50278. if( *pRC ) return;
  50279. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  50280. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  50281. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  50282. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  50283. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50284. /* The cell should normally be sized correctly. However, when moving a
  50285. ** malformed cell from a leaf page to an interior page, if the cell size
  50286. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  50287. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  50288. ** the term after the || in the following assert(). */
  50289. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  50290. if( pPage->nOverflow || sz+2>pPage->nFree ){
  50291. if( pTemp ){
  50292. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  50293. pCell = pTemp;
  50294. }
  50295. if( iChild ){
  50296. put4byte(pCell, iChild);
  50297. }
  50298. j = pPage->nOverflow++;
  50299. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  50300. pPage->apOvfl[j] = pCell;
  50301. pPage->aiOvfl[j] = (u16)i;
  50302. }else{
  50303. int rc = sqlite3PagerWrite(pPage->pDbPage);
  50304. if( rc!=SQLITE_OK ){
  50305. *pRC = rc;
  50306. return;
  50307. }
  50308. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50309. data = pPage->aData;
  50310. cellOffset = pPage->cellOffset;
  50311. end = cellOffset + 2*pPage->nCell;
  50312. ins = cellOffset + 2*i;
  50313. rc = allocateSpace(pPage, sz, &idx);
  50314. if( rc ){ *pRC = rc; return; }
  50315. /* The allocateSpace() routine guarantees the following two properties
  50316. ** if it returns success */
  50317. assert( idx >= end+2 );
  50318. assert( idx+sz <= (int)pPage->pBt->usableSize );
  50319. pPage->nCell++;
  50320. pPage->nFree -= (u16)(2 + sz);
  50321. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  50322. if( iChild ){
  50323. put4byte(&data[idx], iChild);
  50324. }
  50325. ptr = &data[end];
  50326. endPtr = &data[ins];
  50327. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  50328. while( ptr>endPtr ){
  50329. *(u16*)ptr = *(u16*)&ptr[-2];
  50330. ptr -= 2;
  50331. }
  50332. put2byte(&data[ins], idx);
  50333. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  50334. #ifndef SQLITE_OMIT_AUTOVACUUM
  50335. if( pPage->pBt->autoVacuum ){
  50336. /* The cell may contain a pointer to an overflow page. If so, write
  50337. ** the entry for the overflow page into the pointer map.
  50338. */
  50339. ptrmapPutOvflPtr(pPage, pCell, pRC);
  50340. }
  50341. #endif
  50342. }
  50343. }
  50344. /*
  50345. ** Add a list of cells to a page. The page should be initially empty.
  50346. ** The cells are guaranteed to fit on the page.
  50347. */
  50348. static void assemblePage(
  50349. MemPage *pPage, /* The page to be assemblied */
  50350. int nCell, /* The number of cells to add to this page */
  50351. u8 **apCell, /* Pointers to cell bodies */
  50352. u16 *aSize /* Sizes of the cells */
  50353. ){
  50354. int i; /* Loop counter */
  50355. u8 *pCellptr; /* Address of next cell pointer */
  50356. int cellbody; /* Address of next cell body */
  50357. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  50358. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  50359. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  50360. assert( pPage->nOverflow==0 );
  50361. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50362. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  50363. && (int)MX_CELL(pPage->pBt)<=10921);
  50364. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50365. /* Check that the page has just been zeroed by zeroPage() */
  50366. assert( pPage->nCell==0 );
  50367. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  50368. pCellptr = &pPage->aCellIdx[nCell*2];
  50369. cellbody = nUsable;
  50370. for(i=nCell-1; i>=0; i--){
  50371. u16 sz = aSize[i];
  50372. pCellptr -= 2;
  50373. cellbody -= sz;
  50374. put2byte(pCellptr, cellbody);
  50375. memcpy(&data[cellbody], apCell[i], sz);
  50376. }
  50377. put2byte(&data[hdr+3], nCell);
  50378. put2byte(&data[hdr+5], cellbody);
  50379. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  50380. pPage->nCell = (u16)nCell;
  50381. }
  50382. /*
  50383. ** The following parameters determine how many adjacent pages get involved
  50384. ** in a balancing operation. NN is the number of neighbors on either side
  50385. ** of the page that participate in the balancing operation. NB is the
  50386. ** total number of pages that participate, including the target page and
  50387. ** NN neighbors on either side.
  50388. **
  50389. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  50390. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  50391. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  50392. ** The value of NN appears to give the best results overall.
  50393. */
  50394. #define NN 1 /* Number of neighbors on either side of pPage */
  50395. #define NB (NN*2+1) /* Total pages involved in the balance */
  50396. #ifndef SQLITE_OMIT_QUICKBALANCE
  50397. /*
  50398. ** This version of balance() handles the common special case where
  50399. ** a new entry is being inserted on the extreme right-end of the
  50400. ** tree, in other words, when the new entry will become the largest
  50401. ** entry in the tree.
  50402. **
  50403. ** Instead of trying to balance the 3 right-most leaf pages, just add
  50404. ** a new page to the right-hand side and put the one new entry in
  50405. ** that page. This leaves the right side of the tree somewhat
  50406. ** unbalanced. But odds are that we will be inserting new entries
  50407. ** at the end soon afterwards so the nearly empty page will quickly
  50408. ** fill up. On average.
  50409. **
  50410. ** pPage is the leaf page which is the right-most page in the tree.
  50411. ** pParent is its parent. pPage must have a single overflow entry
  50412. ** which is also the right-most entry on the page.
  50413. **
  50414. ** The pSpace buffer is used to store a temporary copy of the divider
  50415. ** cell that will be inserted into pParent. Such a cell consists of a 4
  50416. ** byte page number followed by a variable length integer. In other
  50417. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  50418. ** least 13 bytes in size.
  50419. */
  50420. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  50421. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  50422. MemPage *pNew; /* Newly allocated page */
  50423. int rc; /* Return Code */
  50424. Pgno pgnoNew; /* Page number of pNew */
  50425. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50426. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  50427. assert( pPage->nOverflow==1 );
  50428. /* This error condition is now caught prior to reaching this function */
  50429. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  50430. /* Allocate a new page. This page will become the right-sibling of
  50431. ** pPage. Make the parent page writable, so that the new divider cell
  50432. ** may be inserted. If both these operations are successful, proceed.
  50433. */
  50434. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  50435. if( rc==SQLITE_OK ){
  50436. u8 *pOut = &pSpace[4];
  50437. u8 *pCell = pPage->apOvfl[0];
  50438. u16 szCell = cellSizePtr(pPage, pCell);
  50439. u8 *pStop;
  50440. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  50441. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  50442. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  50443. assemblePage(pNew, 1, &pCell, &szCell);
  50444. /* If this is an auto-vacuum database, update the pointer map
  50445. ** with entries for the new page, and any pointer from the
  50446. ** cell on the page to an overflow page. If either of these
  50447. ** operations fails, the return code is set, but the contents
  50448. ** of the parent page are still manipulated by thh code below.
  50449. ** That is Ok, at this point the parent page is guaranteed to
  50450. ** be marked as dirty. Returning an error code will cause a
  50451. ** rollback, undoing any changes made to the parent page.
  50452. */
  50453. if( ISAUTOVACUUM ){
  50454. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  50455. if( szCell>pNew->minLocal ){
  50456. ptrmapPutOvflPtr(pNew, pCell, &rc);
  50457. }
  50458. }
  50459. /* Create a divider cell to insert into pParent. The divider cell
  50460. ** consists of a 4-byte page number (the page number of pPage) and
  50461. ** a variable length key value (which must be the same value as the
  50462. ** largest key on pPage).
  50463. **
  50464. ** To find the largest key value on pPage, first find the right-most
  50465. ** cell on pPage. The first two fields of this cell are the
  50466. ** record-length (a variable length integer at most 32-bits in size)
  50467. ** and the key value (a variable length integer, may have any value).
  50468. ** The first of the while(...) loops below skips over the record-length
  50469. ** field. The second while(...) loop copies the key value from the
  50470. ** cell on pPage into the pSpace buffer.
  50471. */
  50472. pCell = findCell(pPage, pPage->nCell-1);
  50473. pStop = &pCell[9];
  50474. while( (*(pCell++)&0x80) && pCell<pStop );
  50475. pStop = &pCell[9];
  50476. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  50477. /* Insert the new divider cell into pParent. */
  50478. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  50479. 0, pPage->pgno, &rc);
  50480. /* Set the right-child pointer of pParent to point to the new page. */
  50481. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  50482. /* Release the reference to the new page. */
  50483. releasePage(pNew);
  50484. }
  50485. return rc;
  50486. }
  50487. #endif /* SQLITE_OMIT_QUICKBALANCE */
  50488. #if 0
  50489. /*
  50490. ** This function does not contribute anything to the operation of SQLite.
  50491. ** it is sometimes activated temporarily while debugging code responsible
  50492. ** for setting pointer-map entries.
  50493. */
  50494. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  50495. int i, j;
  50496. for(i=0; i<nPage; i++){
  50497. Pgno n;
  50498. u8 e;
  50499. MemPage *pPage = apPage[i];
  50500. BtShared *pBt = pPage->pBt;
  50501. assert( pPage->isInit );
  50502. for(j=0; j<pPage->nCell; j++){
  50503. CellInfo info;
  50504. u8 *z;
  50505. z = findCell(pPage, j);
  50506. btreeParseCellPtr(pPage, z, &info);
  50507. if( info.iOverflow ){
  50508. Pgno ovfl = get4byte(&z[info.iOverflow]);
  50509. ptrmapGet(pBt, ovfl, &e, &n);
  50510. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  50511. }
  50512. if( !pPage->leaf ){
  50513. Pgno child = get4byte(z);
  50514. ptrmapGet(pBt, child, &e, &n);
  50515. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  50516. }
  50517. }
  50518. if( !pPage->leaf ){
  50519. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  50520. ptrmapGet(pBt, child, &e, &n);
  50521. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  50522. }
  50523. }
  50524. return 1;
  50525. }
  50526. #endif
  50527. /*
  50528. ** This function is used to copy the contents of the b-tree node stored
  50529. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  50530. ** the pointer-map entries for each child page are updated so that the
  50531. ** parent page stored in the pointer map is page pTo. If pFrom contained
  50532. ** any cells with overflow page pointers, then the corresponding pointer
  50533. ** map entries are also updated so that the parent page is page pTo.
  50534. **
  50535. ** If pFrom is currently carrying any overflow cells (entries in the
  50536. ** MemPage.apOvfl[] array), they are not copied to pTo.
  50537. **
  50538. ** Before returning, page pTo is reinitialized using btreeInitPage().
  50539. **
  50540. ** The performance of this function is not critical. It is only used by
  50541. ** the balance_shallower() and balance_deeper() procedures, neither of
  50542. ** which are called often under normal circumstances.
  50543. */
  50544. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  50545. if( (*pRC)==SQLITE_OK ){
  50546. BtShared * const pBt = pFrom->pBt;
  50547. u8 * const aFrom = pFrom->aData;
  50548. u8 * const aTo = pTo->aData;
  50549. int const iFromHdr = pFrom->hdrOffset;
  50550. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  50551. int rc;
  50552. int iData;
  50553. assert( pFrom->isInit );
  50554. assert( pFrom->nFree>=iToHdr );
  50555. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  50556. /* Copy the b-tree node content from page pFrom to page pTo. */
  50557. iData = get2byte(&aFrom[iFromHdr+5]);
  50558. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  50559. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  50560. /* Reinitialize page pTo so that the contents of the MemPage structure
  50561. ** match the new data. The initialization of pTo can actually fail under
  50562. ** fairly obscure circumstances, even though it is a copy of initialized
  50563. ** page pFrom.
  50564. */
  50565. pTo->isInit = 0;
  50566. rc = btreeInitPage(pTo);
  50567. if( rc!=SQLITE_OK ){
  50568. *pRC = rc;
  50569. return;
  50570. }
  50571. /* If this is an auto-vacuum database, update the pointer-map entries
  50572. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  50573. */
  50574. if( ISAUTOVACUUM ){
  50575. *pRC = setChildPtrmaps(pTo);
  50576. }
  50577. }
  50578. }
  50579. /*
  50580. ** This routine redistributes cells on the iParentIdx'th child of pParent
  50581. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  50582. ** same amount of free space. Usually a single sibling on either side of the
  50583. ** page are used in the balancing, though both siblings might come from one
  50584. ** side if the page is the first or last child of its parent. If the page
  50585. ** has fewer than 2 siblings (something which can only happen if the page
  50586. ** is a root page or a child of a root page) then all available siblings
  50587. ** participate in the balancing.
  50588. **
  50589. ** The number of siblings of the page might be increased or decreased by
  50590. ** one or two in an effort to keep pages nearly full but not over full.
  50591. **
  50592. ** Note that when this routine is called, some of the cells on the page
  50593. ** might not actually be stored in MemPage.aData[]. This can happen
  50594. ** if the page is overfull. This routine ensures that all cells allocated
  50595. ** to the page and its siblings fit into MemPage.aData[] before returning.
  50596. **
  50597. ** In the course of balancing the page and its siblings, cells may be
  50598. ** inserted into or removed from the parent page (pParent). Doing so
  50599. ** may cause the parent page to become overfull or underfull. If this
  50600. ** happens, it is the responsibility of the caller to invoke the correct
  50601. ** balancing routine to fix this problem (see the balance() routine).
  50602. **
  50603. ** If this routine fails for any reason, it might leave the database
  50604. ** in a corrupted state. So if this routine fails, the database should
  50605. ** be rolled back.
  50606. **
  50607. ** The third argument to this function, aOvflSpace, is a pointer to a
  50608. ** buffer big enough to hold one page. If while inserting cells into the parent
  50609. ** page (pParent) the parent page becomes overfull, this buffer is
  50610. ** used to store the parent's overflow cells. Because this function inserts
  50611. ** a maximum of four divider cells into the parent page, and the maximum
  50612. ** size of a cell stored within an internal node is always less than 1/4
  50613. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  50614. ** enough for all overflow cells.
  50615. **
  50616. ** If aOvflSpace is set to a null pointer, this function returns
  50617. ** SQLITE_NOMEM.
  50618. */
  50619. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  50620. #pragma optimize("", off)
  50621. #endif
  50622. static int balance_nonroot(
  50623. MemPage *pParent, /* Parent page of siblings being balanced */
  50624. int iParentIdx, /* Index of "the page" in pParent */
  50625. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  50626. int isRoot, /* True if pParent is a root-page */
  50627. int bBulk /* True if this call is part of a bulk load */
  50628. ){
  50629. BtShared *pBt; /* The whole database */
  50630. int nCell = 0; /* Number of cells in apCell[] */
  50631. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  50632. int nNew = 0; /* Number of pages in apNew[] */
  50633. int nOld; /* Number of pages in apOld[] */
  50634. int i, j, k; /* Loop counters */
  50635. int nxDiv; /* Next divider slot in pParent->aCell[] */
  50636. int rc = SQLITE_OK; /* The return code */
  50637. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  50638. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  50639. int usableSpace; /* Bytes in pPage beyond the header */
  50640. int pageFlags; /* Value of pPage->aData[0] */
  50641. int subtotal; /* Subtotal of bytes in cells on one page */
  50642. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  50643. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  50644. int szScratch; /* Size of scratch memory requested */
  50645. MemPage *apOld[NB]; /* pPage and up to two siblings */
  50646. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  50647. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  50648. u8 *pRight; /* Location in parent of right-sibling pointer */
  50649. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  50650. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  50651. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  50652. u8 **apCell = 0; /* All cells begin balanced */
  50653. u16 *szCell; /* Local size of all cells in apCell[] */
  50654. u8 *aSpace1; /* Space for copies of dividers cells */
  50655. Pgno pgno; /* Temp var to store a page number in */
  50656. pBt = pParent->pBt;
  50657. assert( sqlite3_mutex_held(pBt->mutex) );
  50658. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  50659. #if 0
  50660. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  50661. #endif
  50662. /* At this point pParent may have at most one overflow cell. And if
  50663. ** this overflow cell is present, it must be the cell with
  50664. ** index iParentIdx. This scenario comes about when this function
  50665. ** is called (indirectly) from sqlite3BtreeDelete().
  50666. */
  50667. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  50668. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  50669. if( !aOvflSpace ){
  50670. return SQLITE_NOMEM;
  50671. }
  50672. /* Find the sibling pages to balance. Also locate the cells in pParent
  50673. ** that divide the siblings. An attempt is made to find NN siblings on
  50674. ** either side of pPage. More siblings are taken from one side, however,
  50675. ** if there are fewer than NN siblings on the other side. If pParent
  50676. ** has NB or fewer children then all children of pParent are taken.
  50677. **
  50678. ** This loop also drops the divider cells from the parent page. This
  50679. ** way, the remainder of the function does not have to deal with any
  50680. ** overflow cells in the parent page, since if any existed they will
  50681. ** have already been removed.
  50682. */
  50683. i = pParent->nOverflow + pParent->nCell;
  50684. if( i<2 ){
  50685. nxDiv = 0;
  50686. }else{
  50687. assert( bBulk==0 || bBulk==1 );
  50688. if( iParentIdx==0 ){
  50689. nxDiv = 0;
  50690. }else if( iParentIdx==i ){
  50691. nxDiv = i-2+bBulk;
  50692. }else{
  50693. assert( bBulk==0 );
  50694. nxDiv = iParentIdx-1;
  50695. }
  50696. i = 2-bBulk;
  50697. }
  50698. nOld = i+1;
  50699. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  50700. pRight = &pParent->aData[pParent->hdrOffset+8];
  50701. }else{
  50702. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  50703. }
  50704. pgno = get4byte(pRight);
  50705. while( 1 ){
  50706. rc = getAndInitPage(pBt, pgno, &apOld[i]);
  50707. if( rc ){
  50708. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  50709. goto balance_cleanup;
  50710. }
  50711. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  50712. if( (i--)==0 ) break;
  50713. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  50714. apDiv[i] = pParent->apOvfl[0];
  50715. pgno = get4byte(apDiv[i]);
  50716. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  50717. pParent->nOverflow = 0;
  50718. }else{
  50719. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  50720. pgno = get4byte(apDiv[i]);
  50721. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  50722. /* Drop the cell from the parent page. apDiv[i] still points to
  50723. ** the cell within the parent, even though it has been dropped.
  50724. ** This is safe because dropping a cell only overwrites the first
  50725. ** four bytes of it, and this function does not need the first
  50726. ** four bytes of the divider cell. So the pointer is safe to use
  50727. ** later on.
  50728. **
  50729. ** But not if we are in secure-delete mode. In secure-delete mode,
  50730. ** the dropCell() routine will overwrite the entire cell with zeroes.
  50731. ** In this case, temporarily copy the cell into the aOvflSpace[]
  50732. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  50733. ** is allocated. */
  50734. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  50735. int iOff;
  50736. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  50737. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  50738. rc = SQLITE_CORRUPT_BKPT;
  50739. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  50740. goto balance_cleanup;
  50741. }else{
  50742. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  50743. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  50744. }
  50745. }
  50746. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  50747. }
  50748. }
  50749. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  50750. ** alignment */
  50751. nMaxCells = (nMaxCells + 3)&~3;
  50752. /*
  50753. ** Allocate space for memory structures
  50754. */
  50755. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  50756. szScratch =
  50757. nMaxCells*sizeof(u8*) /* apCell */
  50758. + nMaxCells*sizeof(u16) /* szCell */
  50759. + pBt->pageSize /* aSpace1 */
  50760. + k*nOld; /* Page copies (apCopy) */
  50761. apCell = sqlite3ScratchMalloc( szScratch );
  50762. if( apCell==0 ){
  50763. rc = SQLITE_NOMEM;
  50764. goto balance_cleanup;
  50765. }
  50766. szCell = (u16*)&apCell[nMaxCells];
  50767. aSpace1 = (u8*)&szCell[nMaxCells];
  50768. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  50769. /*
  50770. ** Load pointers to all cells on sibling pages and the divider cells
  50771. ** into the local apCell[] array. Make copies of the divider cells
  50772. ** into space obtained from aSpace1[] and remove the divider cells
  50773. ** from pParent.
  50774. **
  50775. ** If the siblings are on leaf pages, then the child pointers of the
  50776. ** divider cells are stripped from the cells before they are copied
  50777. ** into aSpace1[]. In this way, all cells in apCell[] are without
  50778. ** child pointers. If siblings are not leaves, then all cell in
  50779. ** apCell[] include child pointers. Either way, all cells in apCell[]
  50780. ** are alike.
  50781. **
  50782. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  50783. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  50784. */
  50785. leafCorrection = apOld[0]->leaf*4;
  50786. leafData = apOld[0]->hasData;
  50787. for(i=0; i<nOld; i++){
  50788. int limit;
  50789. /* Before doing anything else, take a copy of the i'th original sibling
  50790. ** The rest of this function will use data from the copies rather
  50791. ** that the original pages since the original pages will be in the
  50792. ** process of being overwritten. */
  50793. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  50794. memcpy(pOld, apOld[i], sizeof(MemPage));
  50795. pOld->aData = (void*)&pOld[1];
  50796. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  50797. limit = pOld->nCell+pOld->nOverflow;
  50798. if( pOld->nOverflow>0 ){
  50799. for(j=0; j<limit; j++){
  50800. assert( nCell<nMaxCells );
  50801. apCell[nCell] = findOverflowCell(pOld, j);
  50802. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  50803. nCell++;
  50804. }
  50805. }else{
  50806. u8 *aData = pOld->aData;
  50807. u16 maskPage = pOld->maskPage;
  50808. u16 cellOffset = pOld->cellOffset;
  50809. for(j=0; j<limit; j++){
  50810. assert( nCell<nMaxCells );
  50811. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  50812. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  50813. nCell++;
  50814. }
  50815. }
  50816. if( i<nOld-1 && !leafData){
  50817. u16 sz = (u16)szNew[i];
  50818. u8 *pTemp;
  50819. assert( nCell<nMaxCells );
  50820. szCell[nCell] = sz;
  50821. pTemp = &aSpace1[iSpace1];
  50822. iSpace1 += sz;
  50823. assert( sz<=pBt->maxLocal+23 );
  50824. assert( iSpace1 <= (int)pBt->pageSize );
  50825. memcpy(pTemp, apDiv[i], sz);
  50826. apCell[nCell] = pTemp+leafCorrection;
  50827. assert( leafCorrection==0 || leafCorrection==4 );
  50828. szCell[nCell] = szCell[nCell] - leafCorrection;
  50829. if( !pOld->leaf ){
  50830. assert( leafCorrection==0 );
  50831. assert( pOld->hdrOffset==0 );
  50832. /* The right pointer of the child page pOld becomes the left
  50833. ** pointer of the divider cell */
  50834. memcpy(apCell[nCell], &pOld->aData[8], 4);
  50835. }else{
  50836. assert( leafCorrection==4 );
  50837. if( szCell[nCell]<4 ){
  50838. /* Do not allow any cells smaller than 4 bytes. */
  50839. szCell[nCell] = 4;
  50840. }
  50841. }
  50842. nCell++;
  50843. }
  50844. }
  50845. /*
  50846. ** Figure out the number of pages needed to hold all nCell cells.
  50847. ** Store this number in "k". Also compute szNew[] which is the total
  50848. ** size of all cells on the i-th page and cntNew[] which is the index
  50849. ** in apCell[] of the cell that divides page i from page i+1.
  50850. ** cntNew[k] should equal nCell.
  50851. **
  50852. ** Values computed by this block:
  50853. **
  50854. ** k: The total number of sibling pages
  50855. ** szNew[i]: Spaced used on the i-th sibling page.
  50856. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  50857. ** the right of the i-th sibling page.
  50858. ** usableSpace: Number of bytes of space available on each sibling.
  50859. **
  50860. */
  50861. usableSpace = pBt->usableSize - 12 + leafCorrection;
  50862. for(subtotal=k=i=0; i<nCell; i++){
  50863. assert( i<nMaxCells );
  50864. subtotal += szCell[i] + 2;
  50865. if( subtotal > usableSpace ){
  50866. szNew[k] = subtotal - szCell[i];
  50867. cntNew[k] = i;
  50868. if( leafData ){ i--; }
  50869. subtotal = 0;
  50870. k++;
  50871. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  50872. }
  50873. }
  50874. szNew[k] = subtotal;
  50875. cntNew[k] = nCell;
  50876. k++;
  50877. /*
  50878. ** The packing computed by the previous block is biased toward the siblings
  50879. ** on the left side. The left siblings are always nearly full, while the
  50880. ** right-most sibling might be nearly empty. This block of code attempts
  50881. ** to adjust the packing of siblings to get a better balance.
  50882. **
  50883. ** This adjustment is more than an optimization. The packing above might
  50884. ** be so out of balance as to be illegal. For example, the right-most
  50885. ** sibling might be completely empty. This adjustment is not optional.
  50886. */
  50887. for(i=k-1; i>0; i--){
  50888. int szRight = szNew[i]; /* Size of sibling on the right */
  50889. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  50890. int r; /* Index of right-most cell in left sibling */
  50891. int d; /* Index of first cell to the left of right sibling */
  50892. r = cntNew[i-1] - 1;
  50893. d = r + 1 - leafData;
  50894. assert( d<nMaxCells );
  50895. assert( r<nMaxCells );
  50896. while( szRight==0
  50897. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  50898. ){
  50899. szRight += szCell[d] + 2;
  50900. szLeft -= szCell[r] + 2;
  50901. cntNew[i-1]--;
  50902. r = cntNew[i-1] - 1;
  50903. d = r + 1 - leafData;
  50904. }
  50905. szNew[i] = szRight;
  50906. szNew[i-1] = szLeft;
  50907. }
  50908. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  50909. ** a virtual root page. A virtual root page is when the real root
  50910. ** page is page 1 and we are the only child of that page.
  50911. **
  50912. ** UPDATE: The assert() below is not necessarily true if the database
  50913. ** file is corrupt. The corruption will be detected and reported later
  50914. ** in this procedure so there is no need to act upon it now.
  50915. */
  50916. #if 0
  50917. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  50918. #endif
  50919. TRACE(("BALANCE: old: %d %d %d ",
  50920. apOld[0]->pgno,
  50921. nOld>=2 ? apOld[1]->pgno : 0,
  50922. nOld>=3 ? apOld[2]->pgno : 0
  50923. ));
  50924. /*
  50925. ** Allocate k new pages. Reuse old pages where possible.
  50926. */
  50927. if( apOld[0]->pgno<=1 ){
  50928. rc = SQLITE_CORRUPT_BKPT;
  50929. goto balance_cleanup;
  50930. }
  50931. pageFlags = apOld[0]->aData[0];
  50932. for(i=0; i<k; i++){
  50933. MemPage *pNew;
  50934. if( i<nOld ){
  50935. pNew = apNew[i] = apOld[i];
  50936. apOld[i] = 0;
  50937. rc = sqlite3PagerWrite(pNew->pDbPage);
  50938. nNew++;
  50939. if( rc ) goto balance_cleanup;
  50940. }else{
  50941. assert( i>0 );
  50942. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  50943. if( rc ) goto balance_cleanup;
  50944. apNew[i] = pNew;
  50945. nNew++;
  50946. /* Set the pointer-map entry for the new sibling page. */
  50947. if( ISAUTOVACUUM ){
  50948. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  50949. if( rc!=SQLITE_OK ){
  50950. goto balance_cleanup;
  50951. }
  50952. }
  50953. }
  50954. }
  50955. /* Free any old pages that were not reused as new pages.
  50956. */
  50957. while( i<nOld ){
  50958. freePage(apOld[i], &rc);
  50959. if( rc ) goto balance_cleanup;
  50960. releasePage(apOld[i]);
  50961. apOld[i] = 0;
  50962. i++;
  50963. }
  50964. /*
  50965. ** Put the new pages in accending order. This helps to
  50966. ** keep entries in the disk file in order so that a scan
  50967. ** of the table is a linear scan through the file. That
  50968. ** in turn helps the operating system to deliver pages
  50969. ** from the disk more rapidly.
  50970. **
  50971. ** An O(n^2) insertion sort algorithm is used, but since
  50972. ** n is never more than NB (a small constant), that should
  50973. ** not be a problem.
  50974. **
  50975. ** When NB==3, this one optimization makes the database
  50976. ** about 25% faster for large insertions and deletions.
  50977. */
  50978. for(i=0; i<k-1; i++){
  50979. int minV = apNew[i]->pgno;
  50980. int minI = i;
  50981. for(j=i+1; j<k; j++){
  50982. if( apNew[j]->pgno<(unsigned)minV ){
  50983. minI = j;
  50984. minV = apNew[j]->pgno;
  50985. }
  50986. }
  50987. if( minI>i ){
  50988. MemPage *pT;
  50989. pT = apNew[i];
  50990. apNew[i] = apNew[minI];
  50991. apNew[minI] = pT;
  50992. }
  50993. }
  50994. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  50995. apNew[0]->pgno, szNew[0],
  50996. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  50997. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  50998. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  50999. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  51000. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  51001. put4byte(pRight, apNew[nNew-1]->pgno);
  51002. /*
  51003. ** Evenly distribute the data in apCell[] across the new pages.
  51004. ** Insert divider cells into pParent as necessary.
  51005. */
  51006. j = 0;
  51007. for(i=0; i<nNew; i++){
  51008. /* Assemble the new sibling page. */
  51009. MemPage *pNew = apNew[i];
  51010. assert( j<nMaxCells );
  51011. zeroPage(pNew, pageFlags);
  51012. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  51013. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  51014. assert( pNew->nOverflow==0 );
  51015. j = cntNew[i];
  51016. /* If the sibling page assembled above was not the right-most sibling,
  51017. ** insert a divider cell into the parent page.
  51018. */
  51019. assert( i<nNew-1 || j==nCell );
  51020. if( j<nCell ){
  51021. u8 *pCell;
  51022. u8 *pTemp;
  51023. int sz;
  51024. assert( j<nMaxCells );
  51025. pCell = apCell[j];
  51026. sz = szCell[j] + leafCorrection;
  51027. pTemp = &aOvflSpace[iOvflSpace];
  51028. if( !pNew->leaf ){
  51029. memcpy(&pNew->aData[8], pCell, 4);
  51030. }else if( leafData ){
  51031. /* If the tree is a leaf-data tree, and the siblings are leaves,
  51032. ** then there is no divider cell in apCell[]. Instead, the divider
  51033. ** cell consists of the integer key for the right-most cell of
  51034. ** the sibling-page assembled above only.
  51035. */
  51036. CellInfo info;
  51037. j--;
  51038. btreeParseCellPtr(pNew, apCell[j], &info);
  51039. pCell = pTemp;
  51040. sz = 4 + putVarint(&pCell[4], info.nKey);
  51041. pTemp = 0;
  51042. }else{
  51043. pCell -= 4;
  51044. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  51045. ** previously stored on a leaf node, and its reported size was 4
  51046. ** bytes, then it may actually be smaller than this
  51047. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  51048. ** any cell). But it is important to pass the correct size to
  51049. ** insertCell(), so reparse the cell now.
  51050. **
  51051. ** Note that this can never happen in an SQLite data file, as all
  51052. ** cells are at least 4 bytes. It only happens in b-trees used
  51053. ** to evaluate "IN (SELECT ...)" and similar clauses.
  51054. */
  51055. if( szCell[j]==4 ){
  51056. assert(leafCorrection==4);
  51057. sz = cellSizePtr(pParent, pCell);
  51058. }
  51059. }
  51060. iOvflSpace += sz;
  51061. assert( sz<=pBt->maxLocal+23 );
  51062. assert( iOvflSpace <= (int)pBt->pageSize );
  51063. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  51064. if( rc!=SQLITE_OK ) goto balance_cleanup;
  51065. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  51066. j++;
  51067. nxDiv++;
  51068. }
  51069. }
  51070. assert( j==nCell );
  51071. assert( nOld>0 );
  51072. assert( nNew>0 );
  51073. if( (pageFlags & PTF_LEAF)==0 ){
  51074. u8 *zChild = &apCopy[nOld-1]->aData[8];
  51075. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  51076. }
  51077. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  51078. /* The root page of the b-tree now contains no cells. The only sibling
  51079. ** page is the right-child of the parent. Copy the contents of the
  51080. ** child page into the parent, decreasing the overall height of the
  51081. ** b-tree structure by one. This is described as the "balance-shallower"
  51082. ** sub-algorithm in some documentation.
  51083. **
  51084. ** If this is an auto-vacuum database, the call to copyNodeContent()
  51085. ** sets all pointer-map entries corresponding to database image pages
  51086. ** for which the pointer is stored within the content being copied.
  51087. **
  51088. ** The second assert below verifies that the child page is defragmented
  51089. ** (it must be, as it was just reconstructed using assemblePage()). This
  51090. ** is important if the parent page happens to be page 1 of the database
  51091. ** image. */
  51092. assert( nNew==1 );
  51093. assert( apNew[0]->nFree ==
  51094. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  51095. );
  51096. copyNodeContent(apNew[0], pParent, &rc);
  51097. freePage(apNew[0], &rc);
  51098. }else if( ISAUTOVACUUM ){
  51099. /* Fix the pointer-map entries for all the cells that were shifted around.
  51100. ** There are several different types of pointer-map entries that need to
  51101. ** be dealt with by this routine. Some of these have been set already, but
  51102. ** many have not. The following is a summary:
  51103. **
  51104. ** 1) The entries associated with new sibling pages that were not
  51105. ** siblings when this function was called. These have already
  51106. ** been set. We don't need to worry about old siblings that were
  51107. ** moved to the free-list - the freePage() code has taken care
  51108. ** of those.
  51109. **
  51110. ** 2) The pointer-map entries associated with the first overflow
  51111. ** page in any overflow chains used by new divider cells. These
  51112. ** have also already been taken care of by the insertCell() code.
  51113. **
  51114. ** 3) If the sibling pages are not leaves, then the child pages of
  51115. ** cells stored on the sibling pages may need to be updated.
  51116. **
  51117. ** 4) If the sibling pages are not internal intkey nodes, then any
  51118. ** overflow pages used by these cells may need to be updated
  51119. ** (internal intkey nodes never contain pointers to overflow pages).
  51120. **
  51121. ** 5) If the sibling pages are not leaves, then the pointer-map
  51122. ** entries for the right-child pages of each sibling may need
  51123. ** to be updated.
  51124. **
  51125. ** Cases 1 and 2 are dealt with above by other code. The next
  51126. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  51127. ** setting a pointer map entry is a relatively expensive operation, this
  51128. ** code only sets pointer map entries for child or overflow pages that have
  51129. ** actually moved between pages. */
  51130. MemPage *pNew = apNew[0];
  51131. MemPage *pOld = apCopy[0];
  51132. int nOverflow = pOld->nOverflow;
  51133. int iNextOld = pOld->nCell + nOverflow;
  51134. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  51135. j = 0; /* Current 'old' sibling page */
  51136. k = 0; /* Current 'new' sibling page */
  51137. for(i=0; i<nCell; i++){
  51138. int isDivider = 0;
  51139. while( i==iNextOld ){
  51140. /* Cell i is the cell immediately following the last cell on old
  51141. ** sibling page j. If the siblings are not leaf pages of an
  51142. ** intkey b-tree, then cell i was a divider cell. */
  51143. assert( j+1 < ArraySize(apCopy) );
  51144. assert( j+1 < nOld );
  51145. pOld = apCopy[++j];
  51146. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  51147. if( pOld->nOverflow ){
  51148. nOverflow = pOld->nOverflow;
  51149. iOverflow = i + !leafData + pOld->aiOvfl[0];
  51150. }
  51151. isDivider = !leafData;
  51152. }
  51153. assert(nOverflow>0 || iOverflow<i );
  51154. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  51155. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  51156. if( i==iOverflow ){
  51157. isDivider = 1;
  51158. if( (--nOverflow)>0 ){
  51159. iOverflow++;
  51160. }
  51161. }
  51162. if( i==cntNew[k] ){
  51163. /* Cell i is the cell immediately following the last cell on new
  51164. ** sibling page k. If the siblings are not leaf pages of an
  51165. ** intkey b-tree, then cell i is a divider cell. */
  51166. pNew = apNew[++k];
  51167. if( !leafData ) continue;
  51168. }
  51169. assert( j<nOld );
  51170. assert( k<nNew );
  51171. /* If the cell was originally divider cell (and is not now) or
  51172. ** an overflow cell, or if the cell was located on a different sibling
  51173. ** page before the balancing, then the pointer map entries associated
  51174. ** with any child or overflow pages need to be updated. */
  51175. if( isDivider || pOld->pgno!=pNew->pgno ){
  51176. if( !leafCorrection ){
  51177. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  51178. }
  51179. if( szCell[i]>pNew->minLocal ){
  51180. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  51181. }
  51182. }
  51183. }
  51184. if( !leafCorrection ){
  51185. for(i=0; i<nNew; i++){
  51186. u32 key = get4byte(&apNew[i]->aData[8]);
  51187. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  51188. }
  51189. }
  51190. #if 0
  51191. /* The ptrmapCheckPages() contains assert() statements that verify that
  51192. ** all pointer map pages are set correctly. This is helpful while
  51193. ** debugging. This is usually disabled because a corrupt database may
  51194. ** cause an assert() statement to fail. */
  51195. ptrmapCheckPages(apNew, nNew);
  51196. ptrmapCheckPages(&pParent, 1);
  51197. #endif
  51198. }
  51199. assert( pParent->isInit );
  51200. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  51201. nOld, nNew, nCell));
  51202. /*
  51203. ** Cleanup before returning.
  51204. */
  51205. balance_cleanup:
  51206. sqlite3ScratchFree(apCell);
  51207. for(i=0; i<nOld; i++){
  51208. releasePage(apOld[i]);
  51209. }
  51210. for(i=0; i<nNew; i++){
  51211. releasePage(apNew[i]);
  51212. }
  51213. return rc;
  51214. }
  51215. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  51216. #pragma optimize("", on)
  51217. #endif
  51218. /*
  51219. ** This function is called when the root page of a b-tree structure is
  51220. ** overfull (has one or more overflow pages).
  51221. **
  51222. ** A new child page is allocated and the contents of the current root
  51223. ** page, including overflow cells, are copied into the child. The root
  51224. ** page is then overwritten to make it an empty page with the right-child
  51225. ** pointer pointing to the new page.
  51226. **
  51227. ** Before returning, all pointer-map entries corresponding to pages
  51228. ** that the new child-page now contains pointers to are updated. The
  51229. ** entry corresponding to the new right-child pointer of the root
  51230. ** page is also updated.
  51231. **
  51232. ** If successful, *ppChild is set to contain a reference to the child
  51233. ** page and SQLITE_OK is returned. In this case the caller is required
  51234. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  51235. ** an error code is returned and *ppChild is set to 0.
  51236. */
  51237. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  51238. int rc; /* Return value from subprocedures */
  51239. MemPage *pChild = 0; /* Pointer to a new child page */
  51240. Pgno pgnoChild = 0; /* Page number of the new child page */
  51241. BtShared *pBt = pRoot->pBt; /* The BTree */
  51242. assert( pRoot->nOverflow>0 );
  51243. assert( sqlite3_mutex_held(pBt->mutex) );
  51244. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  51245. ** page that will become the new right-child of pPage. Copy the contents
  51246. ** of the node stored on pRoot into the new child page.
  51247. */
  51248. rc = sqlite3PagerWrite(pRoot->pDbPage);
  51249. if( rc==SQLITE_OK ){
  51250. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  51251. copyNodeContent(pRoot, pChild, &rc);
  51252. if( ISAUTOVACUUM ){
  51253. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  51254. }
  51255. }
  51256. if( rc ){
  51257. *ppChild = 0;
  51258. releasePage(pChild);
  51259. return rc;
  51260. }
  51261. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  51262. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  51263. assert( pChild->nCell==pRoot->nCell );
  51264. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  51265. /* Copy the overflow cells from pRoot to pChild */
  51266. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  51267. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  51268. memcpy(pChild->apOvfl, pRoot->apOvfl,
  51269. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  51270. pChild->nOverflow = pRoot->nOverflow;
  51271. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  51272. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  51273. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  51274. *ppChild = pChild;
  51275. return SQLITE_OK;
  51276. }
  51277. /*
  51278. ** The page that pCur currently points to has just been modified in
  51279. ** some way. This function figures out if this modification means the
  51280. ** tree needs to be balanced, and if so calls the appropriate balancing
  51281. ** routine. Balancing routines are:
  51282. **
  51283. ** balance_quick()
  51284. ** balance_deeper()
  51285. ** balance_nonroot()
  51286. */
  51287. static int balance(BtCursor *pCur){
  51288. int rc = SQLITE_OK;
  51289. const int nMin = pCur->pBt->usableSize * 2 / 3;
  51290. u8 aBalanceQuickSpace[13];
  51291. u8 *pFree = 0;
  51292. TESTONLY( int balance_quick_called = 0 );
  51293. TESTONLY( int balance_deeper_called = 0 );
  51294. do {
  51295. int iPage = pCur->iPage;
  51296. MemPage *pPage = pCur->apPage[iPage];
  51297. if( iPage==0 ){
  51298. if( pPage->nOverflow ){
  51299. /* The root page of the b-tree is overfull. In this case call the
  51300. ** balance_deeper() function to create a new child for the root-page
  51301. ** and copy the current contents of the root-page to it. The
  51302. ** next iteration of the do-loop will balance the child page.
  51303. */
  51304. assert( (balance_deeper_called++)==0 );
  51305. rc = balance_deeper(pPage, &pCur->apPage[1]);
  51306. if( rc==SQLITE_OK ){
  51307. pCur->iPage = 1;
  51308. pCur->aiIdx[0] = 0;
  51309. pCur->aiIdx[1] = 0;
  51310. assert( pCur->apPage[1]->nOverflow );
  51311. }
  51312. }else{
  51313. break;
  51314. }
  51315. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  51316. break;
  51317. }else{
  51318. MemPage * const pParent = pCur->apPage[iPage-1];
  51319. int const iIdx = pCur->aiIdx[iPage-1];
  51320. rc = sqlite3PagerWrite(pParent->pDbPage);
  51321. if( rc==SQLITE_OK ){
  51322. #ifndef SQLITE_OMIT_QUICKBALANCE
  51323. if( pPage->hasData
  51324. && pPage->nOverflow==1
  51325. && pPage->aiOvfl[0]==pPage->nCell
  51326. && pParent->pgno!=1
  51327. && pParent->nCell==iIdx
  51328. ){
  51329. /* Call balance_quick() to create a new sibling of pPage on which
  51330. ** to store the overflow cell. balance_quick() inserts a new cell
  51331. ** into pParent, which may cause pParent overflow. If this
  51332. ** happens, the next interation of the do-loop will balance pParent
  51333. ** use either balance_nonroot() or balance_deeper(). Until this
  51334. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  51335. ** buffer.
  51336. **
  51337. ** The purpose of the following assert() is to check that only a
  51338. ** single call to balance_quick() is made for each call to this
  51339. ** function. If this were not verified, a subtle bug involving reuse
  51340. ** of the aBalanceQuickSpace[] might sneak in.
  51341. */
  51342. assert( (balance_quick_called++)==0 );
  51343. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  51344. }else
  51345. #endif
  51346. {
  51347. /* In this case, call balance_nonroot() to redistribute cells
  51348. ** between pPage and up to 2 of its sibling pages. This involves
  51349. ** modifying the contents of pParent, which may cause pParent to
  51350. ** become overfull or underfull. The next iteration of the do-loop
  51351. ** will balance the parent page to correct this.
  51352. **
  51353. ** If the parent page becomes overfull, the overflow cell or cells
  51354. ** are stored in the pSpace buffer allocated immediately below.
  51355. ** A subsequent iteration of the do-loop will deal with this by
  51356. ** calling balance_nonroot() (balance_deeper() may be called first,
  51357. ** but it doesn't deal with overflow cells - just moves them to a
  51358. ** different page). Once this subsequent call to balance_nonroot()
  51359. ** has completed, it is safe to release the pSpace buffer used by
  51360. ** the previous call, as the overflow cell data will have been
  51361. ** copied either into the body of a database page or into the new
  51362. ** pSpace buffer passed to the latter call to balance_nonroot().
  51363. */
  51364. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  51365. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  51366. if( pFree ){
  51367. /* If pFree is not NULL, it points to the pSpace buffer used
  51368. ** by a previous call to balance_nonroot(). Its contents are
  51369. ** now stored either on real database pages or within the
  51370. ** new pSpace buffer, so it may be safely freed here. */
  51371. sqlite3PageFree(pFree);
  51372. }
  51373. /* The pSpace buffer will be freed after the next call to
  51374. ** balance_nonroot(), or just before this function returns, whichever
  51375. ** comes first. */
  51376. pFree = pSpace;
  51377. }
  51378. }
  51379. pPage->nOverflow = 0;
  51380. /* The next iteration of the do-loop balances the parent page. */
  51381. releasePage(pPage);
  51382. pCur->iPage--;
  51383. }
  51384. }while( rc==SQLITE_OK );
  51385. if( pFree ){
  51386. sqlite3PageFree(pFree);
  51387. }
  51388. return rc;
  51389. }
  51390. /*
  51391. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  51392. ** and the data is given by (pData,nData). The cursor is used only to
  51393. ** define what table the record should be inserted into. The cursor
  51394. ** is left pointing at a random location.
  51395. **
  51396. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  51397. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  51398. **
  51399. ** If the seekResult parameter is non-zero, then a successful call to
  51400. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  51401. ** been performed. seekResult is the search result returned (a negative
  51402. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  51403. ** a positive value if pCur points at an etry that is larger than
  51404. ** (pKey, nKey)).
  51405. **
  51406. ** If the seekResult parameter is non-zero, then the caller guarantees that
  51407. ** cursor pCur is pointing at the existing copy of a row that is to be
  51408. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  51409. ** point to any entry or to no entry at all and so this function has to seek
  51410. ** the cursor before the new key can be inserted.
  51411. */
  51412. SQLITE_PRIVATE int sqlite3BtreeInsert(
  51413. BtCursor *pCur, /* Insert data into the table of this cursor */
  51414. const void *pKey, i64 nKey, /* The key of the new record */
  51415. const void *pData, int nData, /* The data of the new record */
  51416. int nZero, /* Number of extra 0 bytes to append to data */
  51417. int appendBias, /* True if this is likely an append */
  51418. int seekResult /* Result of prior MovetoUnpacked() call */
  51419. ){
  51420. int rc;
  51421. int loc = seekResult; /* -1: before desired location +1: after */
  51422. int szNew = 0;
  51423. int idx;
  51424. MemPage *pPage;
  51425. Btree *p = pCur->pBtree;
  51426. BtShared *pBt = p->pBt;
  51427. unsigned char *oldCell;
  51428. unsigned char *newCell = 0;
  51429. if( pCur->eState==CURSOR_FAULT ){
  51430. assert( pCur->skipNext!=SQLITE_OK );
  51431. return pCur->skipNext;
  51432. }
  51433. assert( cursorHoldsMutex(pCur) );
  51434. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  51435. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  51436. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  51437. /* Assert that the caller has been consistent. If this cursor was opened
  51438. ** expecting an index b-tree, then the caller should be inserting blob
  51439. ** keys with no associated data. If the cursor was opened expecting an
  51440. ** intkey table, the caller should be inserting integer keys with a
  51441. ** blob of associated data. */
  51442. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  51443. /* Save the positions of any other cursors open on this table.
  51444. **
  51445. ** In some cases, the call to btreeMoveto() below is a no-op. For
  51446. ** example, when inserting data into a table with auto-generated integer
  51447. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  51448. ** integer key to use. It then calls this function to actually insert the
  51449. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  51450. ** that the cursor is already where it needs to be and returns without
  51451. ** doing any work. To avoid thwarting these optimizations, it is important
  51452. ** not to clear the cursor here.
  51453. */
  51454. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  51455. if( rc ) return rc;
  51456. /* If this is an insert into a table b-tree, invalidate any incrblob
  51457. ** cursors open on the row being replaced (assuming this is a replace
  51458. ** operation - if it is not, the following is a no-op). */
  51459. if( pCur->pKeyInfo==0 ){
  51460. invalidateIncrblobCursors(p, nKey, 0);
  51461. }
  51462. if( !loc ){
  51463. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  51464. if( rc ) return rc;
  51465. }
  51466. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  51467. pPage = pCur->apPage[pCur->iPage];
  51468. assert( pPage->intKey || nKey>=0 );
  51469. assert( pPage->leaf || !pPage->intKey );
  51470. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  51471. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  51472. loc==0 ? "overwrite" : "new entry"));
  51473. assert( pPage->isInit );
  51474. allocateTempSpace(pBt);
  51475. newCell = pBt->pTmpSpace;
  51476. if( newCell==0 ) return SQLITE_NOMEM;
  51477. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  51478. if( rc ) goto end_insert;
  51479. assert( szNew==cellSizePtr(pPage, newCell) );
  51480. assert( szNew <= MX_CELL_SIZE(pBt) );
  51481. idx = pCur->aiIdx[pCur->iPage];
  51482. if( loc==0 ){
  51483. u16 szOld;
  51484. assert( idx<pPage->nCell );
  51485. rc = sqlite3PagerWrite(pPage->pDbPage);
  51486. if( rc ){
  51487. goto end_insert;
  51488. }
  51489. oldCell = findCell(pPage, idx);
  51490. if( !pPage->leaf ){
  51491. memcpy(newCell, oldCell, 4);
  51492. }
  51493. szOld = cellSizePtr(pPage, oldCell);
  51494. rc = clearCell(pPage, oldCell);
  51495. dropCell(pPage, idx, szOld, &rc);
  51496. if( rc ) goto end_insert;
  51497. }else if( loc<0 && pPage->nCell>0 ){
  51498. assert( pPage->leaf );
  51499. idx = ++pCur->aiIdx[pCur->iPage];
  51500. }else{
  51501. assert( pPage->leaf );
  51502. }
  51503. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  51504. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  51505. /* If no error has occured and pPage has an overflow cell, call balance()
  51506. ** to redistribute the cells within the tree. Since balance() may move
  51507. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  51508. ** variables.
  51509. **
  51510. ** Previous versions of SQLite called moveToRoot() to move the cursor
  51511. ** back to the root page as balance() used to invalidate the contents
  51512. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  51513. ** set the cursor state to "invalid". This makes common insert operations
  51514. ** slightly faster.
  51515. **
  51516. ** There is a subtle but important optimization here too. When inserting
  51517. ** multiple records into an intkey b-tree using a single cursor (as can
  51518. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  51519. ** is advantageous to leave the cursor pointing to the last entry in
  51520. ** the b-tree if possible. If the cursor is left pointing to the last
  51521. ** entry in the table, and the next row inserted has an integer key
  51522. ** larger than the largest existing key, it is possible to insert the
  51523. ** row without seeking the cursor. This can be a big performance boost.
  51524. */
  51525. pCur->info.nSize = 0;
  51526. pCur->validNKey = 0;
  51527. if( rc==SQLITE_OK && pPage->nOverflow ){
  51528. rc = balance(pCur);
  51529. /* Must make sure nOverflow is reset to zero even if the balance()
  51530. ** fails. Internal data structure corruption will result otherwise.
  51531. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  51532. ** from trying to save the current position of the cursor. */
  51533. pCur->apPage[pCur->iPage]->nOverflow = 0;
  51534. pCur->eState = CURSOR_INVALID;
  51535. }
  51536. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  51537. end_insert:
  51538. return rc;
  51539. }
  51540. /*
  51541. ** Delete the entry that the cursor is pointing to. The cursor
  51542. ** is left pointing at a arbitrary location.
  51543. */
  51544. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  51545. Btree *p = pCur->pBtree;
  51546. BtShared *pBt = p->pBt;
  51547. int rc; /* Return code */
  51548. MemPage *pPage; /* Page to delete cell from */
  51549. unsigned char *pCell; /* Pointer to cell to delete */
  51550. int iCellIdx; /* Index of cell to delete */
  51551. int iCellDepth; /* Depth of node containing pCell */
  51552. assert( cursorHoldsMutex(pCur) );
  51553. assert( pBt->inTransaction==TRANS_WRITE );
  51554. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  51555. assert( pCur->wrFlag );
  51556. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  51557. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  51558. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  51559. || NEVER(pCur->eState!=CURSOR_VALID)
  51560. ){
  51561. return SQLITE_ERROR; /* Something has gone awry. */
  51562. }
  51563. iCellDepth = pCur->iPage;
  51564. iCellIdx = pCur->aiIdx[iCellDepth];
  51565. pPage = pCur->apPage[iCellDepth];
  51566. pCell = findCell(pPage, iCellIdx);
  51567. /* If the page containing the entry to delete is not a leaf page, move
  51568. ** the cursor to the largest entry in the tree that is smaller than
  51569. ** the entry being deleted. This cell will replace the cell being deleted
  51570. ** from the internal node. The 'previous' entry is used for this instead
  51571. ** of the 'next' entry, as the previous entry is always a part of the
  51572. ** sub-tree headed by the child page of the cell being deleted. This makes
  51573. ** balancing the tree following the delete operation easier. */
  51574. if( !pPage->leaf ){
  51575. int notUsed;
  51576. rc = sqlite3BtreePrevious(pCur, &notUsed);
  51577. if( rc ) return rc;
  51578. }
  51579. /* Save the positions of any other cursors open on this table before
  51580. ** making any modifications. Make the page containing the entry to be
  51581. ** deleted writable. Then free any overflow pages associated with the
  51582. ** entry and finally remove the cell itself from within the page.
  51583. */
  51584. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  51585. if( rc ) return rc;
  51586. /* If this is a delete operation to remove a row from a table b-tree,
  51587. ** invalidate any incrblob cursors open on the row being deleted. */
  51588. if( pCur->pKeyInfo==0 ){
  51589. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  51590. }
  51591. rc = sqlite3PagerWrite(pPage->pDbPage);
  51592. if( rc ) return rc;
  51593. rc = clearCell(pPage, pCell);
  51594. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  51595. if( rc ) return rc;
  51596. /* If the cell deleted was not located on a leaf page, then the cursor
  51597. ** is currently pointing to the largest entry in the sub-tree headed
  51598. ** by the child-page of the cell that was just deleted from an internal
  51599. ** node. The cell from the leaf node needs to be moved to the internal
  51600. ** node to replace the deleted cell. */
  51601. if( !pPage->leaf ){
  51602. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  51603. int nCell;
  51604. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  51605. unsigned char *pTmp;
  51606. pCell = findCell(pLeaf, pLeaf->nCell-1);
  51607. nCell = cellSizePtr(pLeaf, pCell);
  51608. assert( MX_CELL_SIZE(pBt) >= nCell );
  51609. allocateTempSpace(pBt);
  51610. pTmp = pBt->pTmpSpace;
  51611. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  51612. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  51613. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  51614. if( rc ) return rc;
  51615. }
  51616. /* Balance the tree. If the entry deleted was located on a leaf page,
  51617. ** then the cursor still points to that page. In this case the first
  51618. ** call to balance() repairs the tree, and the if(...) condition is
  51619. ** never true.
  51620. **
  51621. ** Otherwise, if the entry deleted was on an internal node page, then
  51622. ** pCur is pointing to the leaf page from which a cell was removed to
  51623. ** replace the cell deleted from the internal node. This is slightly
  51624. ** tricky as the leaf node may be underfull, and the internal node may
  51625. ** be either under or overfull. In this case run the balancing algorithm
  51626. ** on the leaf node first. If the balance proceeds far enough up the
  51627. ** tree that we can be sure that any problem in the internal node has
  51628. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  51629. ** walk the cursor up the tree to the internal node and balance it as
  51630. ** well. */
  51631. rc = balance(pCur);
  51632. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  51633. while( pCur->iPage>iCellDepth ){
  51634. releasePage(pCur->apPage[pCur->iPage--]);
  51635. }
  51636. rc = balance(pCur);
  51637. }
  51638. if( rc==SQLITE_OK ){
  51639. moveToRoot(pCur);
  51640. }
  51641. return rc;
  51642. }
  51643. /*
  51644. ** Create a new BTree table. Write into *piTable the page
  51645. ** number for the root page of the new table.
  51646. **
  51647. ** The type of type is determined by the flags parameter. Only the
  51648. ** following values of flags are currently in use. Other values for
  51649. ** flags might not work:
  51650. **
  51651. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  51652. ** BTREE_ZERODATA Used for SQL indices
  51653. */
  51654. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  51655. BtShared *pBt = p->pBt;
  51656. MemPage *pRoot;
  51657. Pgno pgnoRoot;
  51658. int rc;
  51659. int ptfFlags; /* Page-type flage for the root page of new table */
  51660. assert( sqlite3BtreeHoldsMutex(p) );
  51661. assert( pBt->inTransaction==TRANS_WRITE );
  51662. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  51663. #ifdef SQLITE_OMIT_AUTOVACUUM
  51664. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  51665. if( rc ){
  51666. return rc;
  51667. }
  51668. #else
  51669. if( pBt->autoVacuum ){
  51670. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  51671. MemPage *pPageMove; /* The page to move to. */
  51672. /* Creating a new table may probably require moving an existing database
  51673. ** to make room for the new tables root page. In case this page turns
  51674. ** out to be an overflow page, delete all overflow page-map caches
  51675. ** held by open cursors.
  51676. */
  51677. invalidateAllOverflowCache(pBt);
  51678. /* Read the value of meta[3] from the database to determine where the
  51679. ** root page of the new table should go. meta[3] is the largest root-page
  51680. ** created so far, so the new root-page is (meta[3]+1).
  51681. */
  51682. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  51683. pgnoRoot++;
  51684. /* The new root-page may not be allocated on a pointer-map page, or the
  51685. ** PENDING_BYTE page.
  51686. */
  51687. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  51688. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  51689. pgnoRoot++;
  51690. }
  51691. assert( pgnoRoot>=3 );
  51692. /* Allocate a page. The page that currently resides at pgnoRoot will
  51693. ** be moved to the allocated page (unless the allocated page happens
  51694. ** to reside at pgnoRoot).
  51695. */
  51696. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
  51697. if( rc!=SQLITE_OK ){
  51698. return rc;
  51699. }
  51700. if( pgnoMove!=pgnoRoot ){
  51701. /* pgnoRoot is the page that will be used for the root-page of
  51702. ** the new table (assuming an error did not occur). But we were
  51703. ** allocated pgnoMove. If required (i.e. if it was not allocated
  51704. ** by extending the file), the current page at position pgnoMove
  51705. ** is already journaled.
  51706. */
  51707. u8 eType = 0;
  51708. Pgno iPtrPage = 0;
  51709. releasePage(pPageMove);
  51710. /* Move the page currently at pgnoRoot to pgnoMove. */
  51711. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  51712. if( rc!=SQLITE_OK ){
  51713. return rc;
  51714. }
  51715. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  51716. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  51717. rc = SQLITE_CORRUPT_BKPT;
  51718. }
  51719. if( rc!=SQLITE_OK ){
  51720. releasePage(pRoot);
  51721. return rc;
  51722. }
  51723. assert( eType!=PTRMAP_ROOTPAGE );
  51724. assert( eType!=PTRMAP_FREEPAGE );
  51725. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  51726. releasePage(pRoot);
  51727. /* Obtain the page at pgnoRoot */
  51728. if( rc!=SQLITE_OK ){
  51729. return rc;
  51730. }
  51731. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  51732. if( rc!=SQLITE_OK ){
  51733. return rc;
  51734. }
  51735. rc = sqlite3PagerWrite(pRoot->pDbPage);
  51736. if( rc!=SQLITE_OK ){
  51737. releasePage(pRoot);
  51738. return rc;
  51739. }
  51740. }else{
  51741. pRoot = pPageMove;
  51742. }
  51743. /* Update the pointer-map and meta-data with the new root-page number. */
  51744. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  51745. if( rc ){
  51746. releasePage(pRoot);
  51747. return rc;
  51748. }
  51749. /* When the new root page was allocated, page 1 was made writable in
  51750. ** order either to increase the database filesize, or to decrement the
  51751. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  51752. */
  51753. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  51754. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  51755. if( NEVER(rc) ){
  51756. releasePage(pRoot);
  51757. return rc;
  51758. }
  51759. }else{
  51760. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  51761. if( rc ) return rc;
  51762. }
  51763. #endif
  51764. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  51765. if( createTabFlags & BTREE_INTKEY ){
  51766. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  51767. }else{
  51768. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  51769. }
  51770. zeroPage(pRoot, ptfFlags);
  51771. sqlite3PagerUnref(pRoot->pDbPage);
  51772. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  51773. *piTable = (int)pgnoRoot;
  51774. return SQLITE_OK;
  51775. }
  51776. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  51777. int rc;
  51778. sqlite3BtreeEnter(p);
  51779. rc = btreeCreateTable(p, piTable, flags);
  51780. sqlite3BtreeLeave(p);
  51781. return rc;
  51782. }
  51783. /*
  51784. ** Erase the given database page and all its children. Return
  51785. ** the page to the freelist.
  51786. */
  51787. static int clearDatabasePage(
  51788. BtShared *pBt, /* The BTree that contains the table */
  51789. Pgno pgno, /* Page number to clear */
  51790. int freePageFlag, /* Deallocate page if true */
  51791. int *pnChange /* Add number of Cells freed to this counter */
  51792. ){
  51793. MemPage *pPage;
  51794. int rc;
  51795. unsigned char *pCell;
  51796. int i;
  51797. assert( sqlite3_mutex_held(pBt->mutex) );
  51798. if( pgno>btreePagecount(pBt) ){
  51799. return SQLITE_CORRUPT_BKPT;
  51800. }
  51801. rc = getAndInitPage(pBt, pgno, &pPage);
  51802. if( rc ) return rc;
  51803. for(i=0; i<pPage->nCell; i++){
  51804. pCell = findCell(pPage, i);
  51805. if( !pPage->leaf ){
  51806. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  51807. if( rc ) goto cleardatabasepage_out;
  51808. }
  51809. rc = clearCell(pPage, pCell);
  51810. if( rc ) goto cleardatabasepage_out;
  51811. }
  51812. if( !pPage->leaf ){
  51813. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  51814. if( rc ) goto cleardatabasepage_out;
  51815. }else if( pnChange ){
  51816. assert( pPage->intKey );
  51817. *pnChange += pPage->nCell;
  51818. }
  51819. if( freePageFlag ){
  51820. freePage(pPage, &rc);
  51821. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  51822. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  51823. }
  51824. cleardatabasepage_out:
  51825. releasePage(pPage);
  51826. return rc;
  51827. }
  51828. /*
  51829. ** Delete all information from a single table in the database. iTable is
  51830. ** the page number of the root of the table. After this routine returns,
  51831. ** the root page is empty, but still exists.
  51832. **
  51833. ** This routine will fail with SQLITE_LOCKED if there are any open
  51834. ** read cursors on the table. Open write cursors are moved to the
  51835. ** root of the table.
  51836. **
  51837. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  51838. ** integer value pointed to by pnChange is incremented by the number of
  51839. ** entries in the table.
  51840. */
  51841. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  51842. int rc;
  51843. BtShared *pBt = p->pBt;
  51844. sqlite3BtreeEnter(p);
  51845. assert( p->inTrans==TRANS_WRITE );
  51846. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  51847. if( SQLITE_OK==rc ){
  51848. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  51849. ** is the root of a table b-tree - if it is not, the following call is
  51850. ** a no-op). */
  51851. invalidateIncrblobCursors(p, 0, 1);
  51852. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  51853. }
  51854. sqlite3BtreeLeave(p);
  51855. return rc;
  51856. }
  51857. /*
  51858. ** Erase all information in a table and add the root of the table to
  51859. ** the freelist. Except, the root of the principle table (the one on
  51860. ** page 1) is never added to the freelist.
  51861. **
  51862. ** This routine will fail with SQLITE_LOCKED if there are any open
  51863. ** cursors on the table.
  51864. **
  51865. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  51866. ** root page in the database file, then the last root page
  51867. ** in the database file is moved into the slot formerly occupied by
  51868. ** iTable and that last slot formerly occupied by the last root page
  51869. ** is added to the freelist instead of iTable. In this say, all
  51870. ** root pages are kept at the beginning of the database file, which
  51871. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  51872. ** page number that used to be the last root page in the file before
  51873. ** the move. If no page gets moved, *piMoved is set to 0.
  51874. ** The last root page is recorded in meta[3] and the value of
  51875. ** meta[3] is updated by this procedure.
  51876. */
  51877. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  51878. int rc;
  51879. MemPage *pPage = 0;
  51880. BtShared *pBt = p->pBt;
  51881. assert( sqlite3BtreeHoldsMutex(p) );
  51882. assert( p->inTrans==TRANS_WRITE );
  51883. /* It is illegal to drop a table if any cursors are open on the
  51884. ** database. This is because in auto-vacuum mode the backend may
  51885. ** need to move another root-page to fill a gap left by the deleted
  51886. ** root page. If an open cursor was using this page a problem would
  51887. ** occur.
  51888. **
  51889. ** This error is caught long before control reaches this point.
  51890. */
  51891. if( NEVER(pBt->pCursor) ){
  51892. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  51893. return SQLITE_LOCKED_SHAREDCACHE;
  51894. }
  51895. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  51896. if( rc ) return rc;
  51897. rc = sqlite3BtreeClearTable(p, iTable, 0);
  51898. if( rc ){
  51899. releasePage(pPage);
  51900. return rc;
  51901. }
  51902. *piMoved = 0;
  51903. if( iTable>1 ){
  51904. #ifdef SQLITE_OMIT_AUTOVACUUM
  51905. freePage(pPage, &rc);
  51906. releasePage(pPage);
  51907. #else
  51908. if( pBt->autoVacuum ){
  51909. Pgno maxRootPgno;
  51910. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  51911. if( iTable==maxRootPgno ){
  51912. /* If the table being dropped is the table with the largest root-page
  51913. ** number in the database, put the root page on the free list.
  51914. */
  51915. freePage(pPage, &rc);
  51916. releasePage(pPage);
  51917. if( rc!=SQLITE_OK ){
  51918. return rc;
  51919. }
  51920. }else{
  51921. /* The table being dropped does not have the largest root-page
  51922. ** number in the database. So move the page that does into the
  51923. ** gap left by the deleted root-page.
  51924. */
  51925. MemPage *pMove;
  51926. releasePage(pPage);
  51927. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  51928. if( rc!=SQLITE_OK ){
  51929. return rc;
  51930. }
  51931. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  51932. releasePage(pMove);
  51933. if( rc!=SQLITE_OK ){
  51934. return rc;
  51935. }
  51936. pMove = 0;
  51937. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  51938. freePage(pMove, &rc);
  51939. releasePage(pMove);
  51940. if( rc!=SQLITE_OK ){
  51941. return rc;
  51942. }
  51943. *piMoved = maxRootPgno;
  51944. }
  51945. /* Set the new 'max-root-page' value in the database header. This
  51946. ** is the old value less one, less one more if that happens to
  51947. ** be a root-page number, less one again if that is the
  51948. ** PENDING_BYTE_PAGE.
  51949. */
  51950. maxRootPgno--;
  51951. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  51952. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  51953. maxRootPgno--;
  51954. }
  51955. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  51956. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  51957. }else{
  51958. freePage(pPage, &rc);
  51959. releasePage(pPage);
  51960. }
  51961. #endif
  51962. }else{
  51963. /* If sqlite3BtreeDropTable was called on page 1.
  51964. ** This really never should happen except in a corrupt
  51965. ** database.
  51966. */
  51967. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  51968. releasePage(pPage);
  51969. }
  51970. return rc;
  51971. }
  51972. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  51973. int rc;
  51974. sqlite3BtreeEnter(p);
  51975. rc = btreeDropTable(p, iTable, piMoved);
  51976. sqlite3BtreeLeave(p);
  51977. return rc;
  51978. }
  51979. /*
  51980. ** This function may only be called if the b-tree connection already
  51981. ** has a read or write transaction open on the database.
  51982. **
  51983. ** Read the meta-information out of a database file. Meta[0]
  51984. ** is the number of free pages currently in the database. Meta[1]
  51985. ** through meta[15] are available for use by higher layers. Meta[0]
  51986. ** is read-only, the others are read/write.
  51987. **
  51988. ** The schema layer numbers meta values differently. At the schema
  51989. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  51990. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  51991. */
  51992. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  51993. BtShared *pBt = p->pBt;
  51994. sqlite3BtreeEnter(p);
  51995. assert( p->inTrans>TRANS_NONE );
  51996. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  51997. assert( pBt->pPage1 );
  51998. assert( idx>=0 && idx<=15 );
  51999. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  52000. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  52001. ** database, mark the database as read-only. */
  52002. #ifdef SQLITE_OMIT_AUTOVACUUM
  52003. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  52004. pBt->btsFlags |= BTS_READ_ONLY;
  52005. }
  52006. #endif
  52007. sqlite3BtreeLeave(p);
  52008. }
  52009. /*
  52010. ** Write meta-information back into the database. Meta[0] is
  52011. ** read-only and may not be written.
  52012. */
  52013. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  52014. BtShared *pBt = p->pBt;
  52015. unsigned char *pP1;
  52016. int rc;
  52017. assert( idx>=1 && idx<=15 );
  52018. sqlite3BtreeEnter(p);
  52019. assert( p->inTrans==TRANS_WRITE );
  52020. assert( pBt->pPage1!=0 );
  52021. pP1 = pBt->pPage1->aData;
  52022. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52023. if( rc==SQLITE_OK ){
  52024. put4byte(&pP1[36 + idx*4], iMeta);
  52025. #ifndef SQLITE_OMIT_AUTOVACUUM
  52026. if( idx==BTREE_INCR_VACUUM ){
  52027. assert( pBt->autoVacuum || iMeta==0 );
  52028. assert( iMeta==0 || iMeta==1 );
  52029. pBt->incrVacuum = (u8)iMeta;
  52030. }
  52031. #endif
  52032. }
  52033. sqlite3BtreeLeave(p);
  52034. return rc;
  52035. }
  52036. #ifndef SQLITE_OMIT_BTREECOUNT
  52037. /*
  52038. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  52039. ** number of entries in the b-tree and write the result to *pnEntry.
  52040. **
  52041. ** SQLITE_OK is returned if the operation is successfully executed.
  52042. ** Otherwise, if an error is encountered (i.e. an IO error or database
  52043. ** corruption) an SQLite error code is returned.
  52044. */
  52045. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  52046. i64 nEntry = 0; /* Value to return in *pnEntry */
  52047. int rc; /* Return code */
  52048. if( pCur->pgnoRoot==0 ){
  52049. *pnEntry = 0;
  52050. return SQLITE_OK;
  52051. }
  52052. rc = moveToRoot(pCur);
  52053. /* Unless an error occurs, the following loop runs one iteration for each
  52054. ** page in the B-Tree structure (not including overflow pages).
  52055. */
  52056. while( rc==SQLITE_OK ){
  52057. int iIdx; /* Index of child node in parent */
  52058. MemPage *pPage; /* Current page of the b-tree */
  52059. /* If this is a leaf page or the tree is not an int-key tree, then
  52060. ** this page contains countable entries. Increment the entry counter
  52061. ** accordingly.
  52062. */
  52063. pPage = pCur->apPage[pCur->iPage];
  52064. if( pPage->leaf || !pPage->intKey ){
  52065. nEntry += pPage->nCell;
  52066. }
  52067. /* pPage is a leaf node. This loop navigates the cursor so that it
  52068. ** points to the first interior cell that it points to the parent of
  52069. ** the next page in the tree that has not yet been visited. The
  52070. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  52071. ** of the page, or to the number of cells in the page if the next page
  52072. ** to visit is the right-child of its parent.
  52073. **
  52074. ** If all pages in the tree have been visited, return SQLITE_OK to the
  52075. ** caller.
  52076. */
  52077. if( pPage->leaf ){
  52078. do {
  52079. if( pCur->iPage==0 ){
  52080. /* All pages of the b-tree have been visited. Return successfully. */
  52081. *pnEntry = nEntry;
  52082. return SQLITE_OK;
  52083. }
  52084. moveToParent(pCur);
  52085. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  52086. pCur->aiIdx[pCur->iPage]++;
  52087. pPage = pCur->apPage[pCur->iPage];
  52088. }
  52089. /* Descend to the child node of the cell that the cursor currently
  52090. ** points at. This is the right-child if (iIdx==pPage->nCell).
  52091. */
  52092. iIdx = pCur->aiIdx[pCur->iPage];
  52093. if( iIdx==pPage->nCell ){
  52094. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  52095. }else{
  52096. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  52097. }
  52098. }
  52099. /* An error has occurred. Return an error code. */
  52100. return rc;
  52101. }
  52102. #endif
  52103. /*
  52104. ** Return the pager associated with a BTree. This routine is used for
  52105. ** testing and debugging only.
  52106. */
  52107. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  52108. return p->pBt->pPager;
  52109. }
  52110. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  52111. /*
  52112. ** Append a message to the error message string.
  52113. */
  52114. static void checkAppendMsg(
  52115. IntegrityCk *pCheck,
  52116. char *zMsg1,
  52117. const char *zFormat,
  52118. ...
  52119. ){
  52120. va_list ap;
  52121. if( !pCheck->mxErr ) return;
  52122. pCheck->mxErr--;
  52123. pCheck->nErr++;
  52124. va_start(ap, zFormat);
  52125. if( pCheck->errMsg.nChar ){
  52126. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  52127. }
  52128. if( zMsg1 ){
  52129. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  52130. }
  52131. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  52132. va_end(ap);
  52133. if( pCheck->errMsg.mallocFailed ){
  52134. pCheck->mallocFailed = 1;
  52135. }
  52136. }
  52137. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  52138. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  52139. /*
  52140. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  52141. ** corresponds to page iPg is already set.
  52142. */
  52143. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  52144. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  52145. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  52146. }
  52147. /*
  52148. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  52149. */
  52150. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  52151. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  52152. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  52153. }
  52154. /*
  52155. ** Add 1 to the reference count for page iPage. If this is the second
  52156. ** reference to the page, add an error message to pCheck->zErrMsg.
  52157. ** Return 1 if there are 2 ore more references to the page and 0 if
  52158. ** if this is the first reference to the page.
  52159. **
  52160. ** Also check that the page number is in bounds.
  52161. */
  52162. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  52163. if( iPage==0 ) return 1;
  52164. if( iPage>pCheck->nPage ){
  52165. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  52166. return 1;
  52167. }
  52168. if( getPageReferenced(pCheck, iPage) ){
  52169. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  52170. return 1;
  52171. }
  52172. setPageReferenced(pCheck, iPage);
  52173. return 0;
  52174. }
  52175. #ifndef SQLITE_OMIT_AUTOVACUUM
  52176. /*
  52177. ** Check that the entry in the pointer-map for page iChild maps to
  52178. ** page iParent, pointer type ptrType. If not, append an error message
  52179. ** to pCheck.
  52180. */
  52181. static void checkPtrmap(
  52182. IntegrityCk *pCheck, /* Integrity check context */
  52183. Pgno iChild, /* Child page number */
  52184. u8 eType, /* Expected pointer map type */
  52185. Pgno iParent, /* Expected pointer map parent page number */
  52186. char *zContext /* Context description (used for error msg) */
  52187. ){
  52188. int rc;
  52189. u8 ePtrmapType;
  52190. Pgno iPtrmapParent;
  52191. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  52192. if( rc!=SQLITE_OK ){
  52193. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  52194. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  52195. return;
  52196. }
  52197. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  52198. checkAppendMsg(pCheck, zContext,
  52199. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  52200. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  52201. }
  52202. }
  52203. #endif
  52204. /*
  52205. ** Check the integrity of the freelist or of an overflow page list.
  52206. ** Verify that the number of pages on the list is N.
  52207. */
  52208. static void checkList(
  52209. IntegrityCk *pCheck, /* Integrity checking context */
  52210. int isFreeList, /* True for a freelist. False for overflow page list */
  52211. int iPage, /* Page number for first page in the list */
  52212. int N, /* Expected number of pages in the list */
  52213. char *zContext /* Context for error messages */
  52214. ){
  52215. int i;
  52216. int expected = N;
  52217. int iFirst = iPage;
  52218. while( N-- > 0 && pCheck->mxErr ){
  52219. DbPage *pOvflPage;
  52220. unsigned char *pOvflData;
  52221. if( iPage<1 ){
  52222. checkAppendMsg(pCheck, zContext,
  52223. "%d of %d pages missing from overflow list starting at %d",
  52224. N+1, expected, iFirst);
  52225. break;
  52226. }
  52227. if( checkRef(pCheck, iPage, zContext) ) break;
  52228. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  52229. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  52230. break;
  52231. }
  52232. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  52233. if( isFreeList ){
  52234. int n = get4byte(&pOvflData[4]);
  52235. #ifndef SQLITE_OMIT_AUTOVACUUM
  52236. if( pCheck->pBt->autoVacuum ){
  52237. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  52238. }
  52239. #endif
  52240. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  52241. checkAppendMsg(pCheck, zContext,
  52242. "freelist leaf count too big on page %d", iPage);
  52243. N--;
  52244. }else{
  52245. for(i=0; i<n; i++){
  52246. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  52247. #ifndef SQLITE_OMIT_AUTOVACUUM
  52248. if( pCheck->pBt->autoVacuum ){
  52249. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  52250. }
  52251. #endif
  52252. checkRef(pCheck, iFreePage, zContext);
  52253. }
  52254. N -= n;
  52255. }
  52256. }
  52257. #ifndef SQLITE_OMIT_AUTOVACUUM
  52258. else{
  52259. /* If this database supports auto-vacuum and iPage is not the last
  52260. ** page in this overflow list, check that the pointer-map entry for
  52261. ** the following page matches iPage.
  52262. */
  52263. if( pCheck->pBt->autoVacuum && N>0 ){
  52264. i = get4byte(pOvflData);
  52265. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  52266. }
  52267. }
  52268. #endif
  52269. iPage = get4byte(pOvflData);
  52270. sqlite3PagerUnref(pOvflPage);
  52271. }
  52272. }
  52273. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  52274. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  52275. /*
  52276. ** Do various sanity checks on a single page of a tree. Return
  52277. ** the tree depth. Root pages return 0. Parents of root pages
  52278. ** return 1, and so forth.
  52279. **
  52280. ** These checks are done:
  52281. **
  52282. ** 1. Make sure that cells and freeblocks do not overlap
  52283. ** but combine to completely cover the page.
  52284. ** NO 2. Make sure cell keys are in order.
  52285. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  52286. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  52287. ** 5. Check the integrity of overflow pages.
  52288. ** 6. Recursively call checkTreePage on all children.
  52289. ** 7. Verify that the depth of all children is the same.
  52290. ** 8. Make sure this page is at least 33% full or else it is
  52291. ** the root of the tree.
  52292. */
  52293. static int checkTreePage(
  52294. IntegrityCk *pCheck, /* Context for the sanity check */
  52295. int iPage, /* Page number of the page to check */
  52296. char *zParentContext, /* Parent context */
  52297. i64 *pnParentMinKey,
  52298. i64 *pnParentMaxKey
  52299. ){
  52300. MemPage *pPage;
  52301. int i, rc, depth, d2, pgno, cnt;
  52302. int hdr, cellStart;
  52303. int nCell;
  52304. u8 *data;
  52305. BtShared *pBt;
  52306. int usableSize;
  52307. char zContext[100];
  52308. char *hit = 0;
  52309. i64 nMinKey = 0;
  52310. i64 nMaxKey = 0;
  52311. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  52312. /* Check that the page exists
  52313. */
  52314. pBt = pCheck->pBt;
  52315. usableSize = pBt->usableSize;
  52316. if( iPage==0 ) return 0;
  52317. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  52318. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  52319. checkAppendMsg(pCheck, zContext,
  52320. "unable to get the page. error code=%d", rc);
  52321. return 0;
  52322. }
  52323. /* Clear MemPage.isInit to make sure the corruption detection code in
  52324. ** btreeInitPage() is executed. */
  52325. pPage->isInit = 0;
  52326. if( (rc = btreeInitPage(pPage))!=0 ){
  52327. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  52328. checkAppendMsg(pCheck, zContext,
  52329. "btreeInitPage() returns error code %d", rc);
  52330. releasePage(pPage);
  52331. return 0;
  52332. }
  52333. /* Check out all the cells.
  52334. */
  52335. depth = 0;
  52336. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  52337. u8 *pCell;
  52338. u32 sz;
  52339. CellInfo info;
  52340. /* Check payload overflow pages
  52341. */
  52342. sqlite3_snprintf(sizeof(zContext), zContext,
  52343. "On tree page %d cell %d: ", iPage, i);
  52344. pCell = findCell(pPage,i);
  52345. btreeParseCellPtr(pPage, pCell, &info);
  52346. sz = info.nData;
  52347. if( !pPage->intKey ) sz += (int)info.nKey;
  52348. /* For intKey pages, check that the keys are in order.
  52349. */
  52350. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  52351. else{
  52352. if( info.nKey <= nMaxKey ){
  52353. checkAppendMsg(pCheck, zContext,
  52354. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  52355. }
  52356. nMaxKey = info.nKey;
  52357. }
  52358. assert( sz==info.nPayload );
  52359. if( (sz>info.nLocal)
  52360. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  52361. ){
  52362. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  52363. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  52364. #ifndef SQLITE_OMIT_AUTOVACUUM
  52365. if( pBt->autoVacuum ){
  52366. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  52367. }
  52368. #endif
  52369. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  52370. }
  52371. /* Check sanity of left child page.
  52372. */
  52373. if( !pPage->leaf ){
  52374. pgno = get4byte(pCell);
  52375. #ifndef SQLITE_OMIT_AUTOVACUUM
  52376. if( pBt->autoVacuum ){
  52377. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  52378. }
  52379. #endif
  52380. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  52381. if( i>0 && d2!=depth ){
  52382. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  52383. }
  52384. depth = d2;
  52385. }
  52386. }
  52387. if( !pPage->leaf ){
  52388. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52389. sqlite3_snprintf(sizeof(zContext), zContext,
  52390. "On page %d at right child: ", iPage);
  52391. #ifndef SQLITE_OMIT_AUTOVACUUM
  52392. if( pBt->autoVacuum ){
  52393. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  52394. }
  52395. #endif
  52396. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  52397. }
  52398. /* For intKey leaf pages, check that the min/max keys are in order
  52399. ** with any left/parent/right pages.
  52400. */
  52401. if( pPage->leaf && pPage->intKey ){
  52402. /* if we are a left child page */
  52403. if( pnParentMinKey ){
  52404. /* if we are the left most child page */
  52405. if( !pnParentMaxKey ){
  52406. if( nMaxKey > *pnParentMinKey ){
  52407. checkAppendMsg(pCheck, zContext,
  52408. "Rowid %lld out of order (max larger than parent min of %lld)",
  52409. nMaxKey, *pnParentMinKey);
  52410. }
  52411. }else{
  52412. if( nMinKey <= *pnParentMinKey ){
  52413. checkAppendMsg(pCheck, zContext,
  52414. "Rowid %lld out of order (min less than parent min of %lld)",
  52415. nMinKey, *pnParentMinKey);
  52416. }
  52417. if( nMaxKey > *pnParentMaxKey ){
  52418. checkAppendMsg(pCheck, zContext,
  52419. "Rowid %lld out of order (max larger than parent max of %lld)",
  52420. nMaxKey, *pnParentMaxKey);
  52421. }
  52422. *pnParentMinKey = nMaxKey;
  52423. }
  52424. /* else if we're a right child page */
  52425. } else if( pnParentMaxKey ){
  52426. if( nMinKey <= *pnParentMaxKey ){
  52427. checkAppendMsg(pCheck, zContext,
  52428. "Rowid %lld out of order (min less than parent max of %lld)",
  52429. nMinKey, *pnParentMaxKey);
  52430. }
  52431. }
  52432. }
  52433. /* Check for complete coverage of the page
  52434. */
  52435. data = pPage->aData;
  52436. hdr = pPage->hdrOffset;
  52437. hit = sqlite3PageMalloc( pBt->pageSize );
  52438. if( hit==0 ){
  52439. pCheck->mallocFailed = 1;
  52440. }else{
  52441. int contentOffset = get2byteNotZero(&data[hdr+5]);
  52442. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  52443. memset(hit+contentOffset, 0, usableSize-contentOffset);
  52444. memset(hit, 1, contentOffset);
  52445. nCell = get2byte(&data[hdr+3]);
  52446. cellStart = hdr + 12 - 4*pPage->leaf;
  52447. for(i=0; i<nCell; i++){
  52448. int pc = get2byte(&data[cellStart+i*2]);
  52449. u32 size = 65536;
  52450. int j;
  52451. if( pc<=usableSize-4 ){
  52452. size = cellSizePtr(pPage, &data[pc]);
  52453. }
  52454. if( (int)(pc+size-1)>=usableSize ){
  52455. checkAppendMsg(pCheck, 0,
  52456. "Corruption detected in cell %d on page %d",i,iPage);
  52457. }else{
  52458. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  52459. }
  52460. }
  52461. i = get2byte(&data[hdr+1]);
  52462. while( i>0 ){
  52463. int size, j;
  52464. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  52465. size = get2byte(&data[i+2]);
  52466. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  52467. for(j=i+size-1; j>=i; j--) hit[j]++;
  52468. j = get2byte(&data[i]);
  52469. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  52470. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  52471. i = j;
  52472. }
  52473. for(i=cnt=0; i<usableSize; i++){
  52474. if( hit[i]==0 ){
  52475. cnt++;
  52476. }else if( hit[i]>1 ){
  52477. checkAppendMsg(pCheck, 0,
  52478. "Multiple uses for byte %d of page %d", i, iPage);
  52479. break;
  52480. }
  52481. }
  52482. if( cnt!=data[hdr+7] ){
  52483. checkAppendMsg(pCheck, 0,
  52484. "Fragmentation of %d bytes reported as %d on page %d",
  52485. cnt, data[hdr+7], iPage);
  52486. }
  52487. }
  52488. sqlite3PageFree(hit);
  52489. releasePage(pPage);
  52490. return depth+1;
  52491. }
  52492. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  52493. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  52494. /*
  52495. ** This routine does a complete check of the given BTree file. aRoot[] is
  52496. ** an array of pages numbers were each page number is the root page of
  52497. ** a table. nRoot is the number of entries in aRoot.
  52498. **
  52499. ** A read-only or read-write transaction must be opened before calling
  52500. ** this function.
  52501. **
  52502. ** Write the number of error seen in *pnErr. Except for some memory
  52503. ** allocation errors, an error message held in memory obtained from
  52504. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  52505. ** returned. If a memory allocation error occurs, NULL is returned.
  52506. */
  52507. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  52508. Btree *p, /* The btree to be checked */
  52509. int *aRoot, /* An array of root pages numbers for individual trees */
  52510. int nRoot, /* Number of entries in aRoot[] */
  52511. int mxErr, /* Stop reporting errors after this many */
  52512. int *pnErr /* Write number of errors seen to this variable */
  52513. ){
  52514. Pgno i;
  52515. int nRef;
  52516. IntegrityCk sCheck;
  52517. BtShared *pBt = p->pBt;
  52518. char zErr[100];
  52519. sqlite3BtreeEnter(p);
  52520. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  52521. nRef = sqlite3PagerRefcount(pBt->pPager);
  52522. sCheck.pBt = pBt;
  52523. sCheck.pPager = pBt->pPager;
  52524. sCheck.nPage = btreePagecount(sCheck.pBt);
  52525. sCheck.mxErr = mxErr;
  52526. sCheck.nErr = 0;
  52527. sCheck.mallocFailed = 0;
  52528. *pnErr = 0;
  52529. if( sCheck.nPage==0 ){
  52530. sqlite3BtreeLeave(p);
  52531. return 0;
  52532. }
  52533. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  52534. if( !sCheck.aPgRef ){
  52535. *pnErr = 1;
  52536. sqlite3BtreeLeave(p);
  52537. return 0;
  52538. }
  52539. i = PENDING_BYTE_PAGE(pBt);
  52540. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  52541. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
  52542. sCheck.errMsg.useMalloc = 2;
  52543. /* Check the integrity of the freelist
  52544. */
  52545. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  52546. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  52547. /* Check all the tables.
  52548. */
  52549. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  52550. if( aRoot[i]==0 ) continue;
  52551. #ifndef SQLITE_OMIT_AUTOVACUUM
  52552. if( pBt->autoVacuum && aRoot[i]>1 ){
  52553. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  52554. }
  52555. #endif
  52556. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  52557. }
  52558. /* Make sure every page in the file is referenced
  52559. */
  52560. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  52561. #ifdef SQLITE_OMIT_AUTOVACUUM
  52562. if( getPageReferenced(&sCheck, i)==0 ){
  52563. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  52564. }
  52565. #else
  52566. /* If the database supports auto-vacuum, make sure no tables contain
  52567. ** references to pointer-map pages.
  52568. */
  52569. if( getPageReferenced(&sCheck, i)==0 &&
  52570. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  52571. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  52572. }
  52573. if( getPageReferenced(&sCheck, i)!=0 &&
  52574. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  52575. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  52576. }
  52577. #endif
  52578. }
  52579. /* Make sure this analysis did not leave any unref() pages.
  52580. ** This is an internal consistency check; an integrity check
  52581. ** of the integrity check.
  52582. */
  52583. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  52584. checkAppendMsg(&sCheck, 0,
  52585. "Outstanding page count goes from %d to %d during this analysis",
  52586. nRef, sqlite3PagerRefcount(pBt->pPager)
  52587. );
  52588. }
  52589. /* Clean up and report errors.
  52590. */
  52591. sqlite3BtreeLeave(p);
  52592. sqlite3_free(sCheck.aPgRef);
  52593. if( sCheck.mallocFailed ){
  52594. sqlite3StrAccumReset(&sCheck.errMsg);
  52595. *pnErr = sCheck.nErr+1;
  52596. return 0;
  52597. }
  52598. *pnErr = sCheck.nErr;
  52599. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  52600. return sqlite3StrAccumFinish(&sCheck.errMsg);
  52601. }
  52602. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  52603. /*
  52604. ** Return the full pathname of the underlying database file. Return
  52605. ** an empty string if the database is in-memory or a TEMP database.
  52606. **
  52607. ** The pager filename is invariant as long as the pager is
  52608. ** open so it is safe to access without the BtShared mutex.
  52609. */
  52610. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  52611. assert( p->pBt->pPager!=0 );
  52612. return sqlite3PagerFilename(p->pBt->pPager, 1);
  52613. }
  52614. /*
  52615. ** Return the pathname of the journal file for this database. The return
  52616. ** value of this routine is the same regardless of whether the journal file
  52617. ** has been created or not.
  52618. **
  52619. ** The pager journal filename is invariant as long as the pager is
  52620. ** open so it is safe to access without the BtShared mutex.
  52621. */
  52622. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  52623. assert( p->pBt->pPager!=0 );
  52624. return sqlite3PagerJournalname(p->pBt->pPager);
  52625. }
  52626. /*
  52627. ** Return non-zero if a transaction is active.
  52628. */
  52629. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  52630. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  52631. return (p && (p->inTrans==TRANS_WRITE));
  52632. }
  52633. #ifndef SQLITE_OMIT_WAL
  52634. /*
  52635. ** Run a checkpoint on the Btree passed as the first argument.
  52636. **
  52637. ** Return SQLITE_LOCKED if this or any other connection has an open
  52638. ** transaction on the shared-cache the argument Btree is connected to.
  52639. **
  52640. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  52641. */
  52642. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  52643. int rc = SQLITE_OK;
  52644. if( p ){
  52645. BtShared *pBt = p->pBt;
  52646. sqlite3BtreeEnter(p);
  52647. if( pBt->inTransaction!=TRANS_NONE ){
  52648. rc = SQLITE_LOCKED;
  52649. }else{
  52650. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  52651. }
  52652. sqlite3BtreeLeave(p);
  52653. }
  52654. return rc;
  52655. }
  52656. #endif
  52657. /*
  52658. ** Return non-zero if a read (or write) transaction is active.
  52659. */
  52660. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  52661. assert( p );
  52662. assert( sqlite3_mutex_held(p->db->mutex) );
  52663. return p->inTrans!=TRANS_NONE;
  52664. }
  52665. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  52666. assert( p );
  52667. assert( sqlite3_mutex_held(p->db->mutex) );
  52668. return p->nBackup!=0;
  52669. }
  52670. /*
  52671. ** This function returns a pointer to a blob of memory associated with
  52672. ** a single shared-btree. The memory is used by client code for its own
  52673. ** purposes (for example, to store a high-level schema associated with
  52674. ** the shared-btree). The btree layer manages reference counting issues.
  52675. **
  52676. ** The first time this is called on a shared-btree, nBytes bytes of memory
  52677. ** are allocated, zeroed, and returned to the caller. For each subsequent
  52678. ** call the nBytes parameter is ignored and a pointer to the same blob
  52679. ** of memory returned.
  52680. **
  52681. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  52682. ** allocated, a null pointer is returned. If the blob has already been
  52683. ** allocated, it is returned as normal.
  52684. **
  52685. ** Just before the shared-btree is closed, the function passed as the
  52686. ** xFree argument when the memory allocation was made is invoked on the
  52687. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  52688. ** on the memory, the btree layer does that.
  52689. */
  52690. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  52691. BtShared *pBt = p->pBt;
  52692. sqlite3BtreeEnter(p);
  52693. if( !pBt->pSchema && nBytes ){
  52694. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  52695. pBt->xFreeSchema = xFree;
  52696. }
  52697. sqlite3BtreeLeave(p);
  52698. return pBt->pSchema;
  52699. }
  52700. /*
  52701. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  52702. ** btree as the argument handle holds an exclusive lock on the
  52703. ** sqlite_master table. Otherwise SQLITE_OK.
  52704. */
  52705. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  52706. int rc;
  52707. assert( sqlite3_mutex_held(p->db->mutex) );
  52708. sqlite3BtreeEnter(p);
  52709. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  52710. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  52711. sqlite3BtreeLeave(p);
  52712. return rc;
  52713. }
  52714. #ifndef SQLITE_OMIT_SHARED_CACHE
  52715. /*
  52716. ** Obtain a lock on the table whose root page is iTab. The
  52717. ** lock is a write lock if isWritelock is true or a read lock
  52718. ** if it is false.
  52719. */
  52720. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  52721. int rc = SQLITE_OK;
  52722. assert( p->inTrans!=TRANS_NONE );
  52723. if( p->sharable ){
  52724. u8 lockType = READ_LOCK + isWriteLock;
  52725. assert( READ_LOCK+1==WRITE_LOCK );
  52726. assert( isWriteLock==0 || isWriteLock==1 );
  52727. sqlite3BtreeEnter(p);
  52728. rc = querySharedCacheTableLock(p, iTab, lockType);
  52729. if( rc==SQLITE_OK ){
  52730. rc = setSharedCacheTableLock(p, iTab, lockType);
  52731. }
  52732. sqlite3BtreeLeave(p);
  52733. }
  52734. return rc;
  52735. }
  52736. #endif
  52737. #ifndef SQLITE_OMIT_INCRBLOB
  52738. /*
  52739. ** Argument pCsr must be a cursor opened for writing on an
  52740. ** INTKEY table currently pointing at a valid table entry.
  52741. ** This function modifies the data stored as part of that entry.
  52742. **
  52743. ** Only the data content may only be modified, it is not possible to
  52744. ** change the length of the data stored. If this function is called with
  52745. ** parameters that attempt to write past the end of the existing data,
  52746. ** no modifications are made and SQLITE_CORRUPT is returned.
  52747. */
  52748. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  52749. int rc;
  52750. assert( cursorHoldsMutex(pCsr) );
  52751. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  52752. assert( pCsr->isIncrblobHandle );
  52753. rc = restoreCursorPosition(pCsr);
  52754. if( rc!=SQLITE_OK ){
  52755. return rc;
  52756. }
  52757. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  52758. if( pCsr->eState!=CURSOR_VALID ){
  52759. return SQLITE_ABORT;
  52760. }
  52761. /* Check some assumptions:
  52762. ** (a) the cursor is open for writing,
  52763. ** (b) there is a read/write transaction open,
  52764. ** (c) the connection holds a write-lock on the table (if required),
  52765. ** (d) there are no conflicting read-locks, and
  52766. ** (e) the cursor points at a valid row of an intKey table.
  52767. */
  52768. if( !pCsr->wrFlag ){
  52769. return SQLITE_READONLY;
  52770. }
  52771. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  52772. && pCsr->pBt->inTransaction==TRANS_WRITE );
  52773. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  52774. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  52775. assert( pCsr->apPage[pCsr->iPage]->intKey );
  52776. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  52777. }
  52778. /*
  52779. ** Set a flag on this cursor to cache the locations of pages from the
  52780. ** overflow list for the current row. This is used by cursors opened
  52781. ** for incremental blob IO only.
  52782. **
  52783. ** This function sets a flag only. The actual page location cache
  52784. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  52785. ** accessPayload() (the worker function for sqlite3BtreeData() and
  52786. ** sqlite3BtreePutData()).
  52787. */
  52788. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  52789. assert( cursorHoldsMutex(pCur) );
  52790. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  52791. invalidateOverflowCache(pCur);
  52792. pCur->isIncrblobHandle = 1;
  52793. }
  52794. #endif
  52795. /*
  52796. ** Set both the "read version" (single byte at byte offset 18) and
  52797. ** "write version" (single byte at byte offset 19) fields in the database
  52798. ** header to iVersion.
  52799. */
  52800. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  52801. BtShared *pBt = pBtree->pBt;
  52802. int rc; /* Return code */
  52803. assert( iVersion==1 || iVersion==2 );
  52804. /* If setting the version fields to 1, do not automatically open the
  52805. ** WAL connection, even if the version fields are currently set to 2.
  52806. */
  52807. pBt->btsFlags &= ~BTS_NO_WAL;
  52808. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  52809. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  52810. if( rc==SQLITE_OK ){
  52811. u8 *aData = pBt->pPage1->aData;
  52812. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  52813. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  52814. if( rc==SQLITE_OK ){
  52815. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52816. if( rc==SQLITE_OK ){
  52817. aData[18] = (u8)iVersion;
  52818. aData[19] = (u8)iVersion;
  52819. }
  52820. }
  52821. }
  52822. }
  52823. pBt->btsFlags &= ~BTS_NO_WAL;
  52824. return rc;
  52825. }
  52826. /*
  52827. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  52828. ** values are 0 and BTREE_BULKLOAD.
  52829. */
  52830. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  52831. assert( mask==BTREE_BULKLOAD || mask==0 );
  52832. pCsr->hints = mask;
  52833. }
  52834. /************** End of btree.c ***********************************************/
  52835. /************** Begin file backup.c ******************************************/
  52836. /*
  52837. ** 2009 January 28
  52838. **
  52839. ** The author disclaims copyright to this source code. In place of
  52840. ** a legal notice, here is a blessing:
  52841. **
  52842. ** May you do good and not evil.
  52843. ** May you find forgiveness for yourself and forgive others.
  52844. ** May you share freely, never taking more than you give.
  52845. **
  52846. *************************************************************************
  52847. ** This file contains the implementation of the sqlite3_backup_XXX()
  52848. ** API functions and the related features.
  52849. */
  52850. /* Macro to find the minimum of two numeric values.
  52851. */
  52852. #ifndef MIN
  52853. # define MIN(x,y) ((x)<(y)?(x):(y))
  52854. #endif
  52855. /*
  52856. ** Structure allocated for each backup operation.
  52857. */
  52858. struct sqlite3_backup {
  52859. sqlite3* pDestDb; /* Destination database handle */
  52860. Btree *pDest; /* Destination b-tree file */
  52861. u32 iDestSchema; /* Original schema cookie in destination */
  52862. int bDestLocked; /* True once a write-transaction is open on pDest */
  52863. Pgno iNext; /* Page number of the next source page to copy */
  52864. sqlite3* pSrcDb; /* Source database handle */
  52865. Btree *pSrc; /* Source b-tree file */
  52866. int rc; /* Backup process error code */
  52867. /* These two variables are set by every call to backup_step(). They are
  52868. ** read by calls to backup_remaining() and backup_pagecount().
  52869. */
  52870. Pgno nRemaining; /* Number of pages left to copy */
  52871. Pgno nPagecount; /* Total number of pages to copy */
  52872. int isAttached; /* True once backup has been registered with pager */
  52873. sqlite3_backup *pNext; /* Next backup associated with source pager */
  52874. };
  52875. /*
  52876. ** THREAD SAFETY NOTES:
  52877. **
  52878. ** Once it has been created using backup_init(), a single sqlite3_backup
  52879. ** structure may be accessed via two groups of thread-safe entry points:
  52880. **
  52881. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  52882. ** backup_finish(). Both these functions obtain the source database
  52883. ** handle mutex and the mutex associated with the source BtShared
  52884. ** structure, in that order.
  52885. **
  52886. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  52887. ** invoked by the pager layer to report various state changes in
  52888. ** the page cache associated with the source database. The mutex
  52889. ** associated with the source database BtShared structure will always
  52890. ** be held when either of these functions are invoked.
  52891. **
  52892. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  52893. ** backup_pagecount() are not thread-safe functions. If they are called
  52894. ** while some other thread is calling backup_step() or backup_finish(),
  52895. ** the values returned may be invalid. There is no way for a call to
  52896. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  52897. ** or backup_pagecount().
  52898. **
  52899. ** Depending on the SQLite configuration, the database handles and/or
  52900. ** the Btree objects may have their own mutexes that require locking.
  52901. ** Non-sharable Btrees (in-memory databases for example), do not have
  52902. ** associated mutexes.
  52903. */
  52904. /*
  52905. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  52906. ** in connection handle pDb. If such a database cannot be found, return
  52907. ** a NULL pointer and write an error message to pErrorDb.
  52908. **
  52909. ** If the "temp" database is requested, it may need to be opened by this
  52910. ** function. If an error occurs while doing so, return 0 and write an
  52911. ** error message to pErrorDb.
  52912. */
  52913. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  52914. int i = sqlite3FindDbName(pDb, zDb);
  52915. if( i==1 ){
  52916. Parse *pParse;
  52917. int rc = 0;
  52918. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  52919. if( pParse==0 ){
  52920. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  52921. rc = SQLITE_NOMEM;
  52922. }else{
  52923. pParse->db = pDb;
  52924. if( sqlite3OpenTempDatabase(pParse) ){
  52925. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  52926. rc = SQLITE_ERROR;
  52927. }
  52928. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  52929. sqlite3StackFree(pErrorDb, pParse);
  52930. }
  52931. if( rc ){
  52932. return 0;
  52933. }
  52934. }
  52935. if( i<0 ){
  52936. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  52937. return 0;
  52938. }
  52939. return pDb->aDb[i].pBt;
  52940. }
  52941. /*
  52942. ** Attempt to set the page size of the destination to match the page size
  52943. ** of the source.
  52944. */
  52945. static int setDestPgsz(sqlite3_backup *p){
  52946. int rc;
  52947. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  52948. return rc;
  52949. }
  52950. /*
  52951. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  52952. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  52953. ** a pointer to the new sqlite3_backup object.
  52954. **
  52955. ** If an error occurs, NULL is returned and an error code and error message
  52956. ** stored in database handle pDestDb.
  52957. */
  52958. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  52959. sqlite3* pDestDb, /* Database to write to */
  52960. const char *zDestDb, /* Name of database within pDestDb */
  52961. sqlite3* pSrcDb, /* Database connection to read from */
  52962. const char *zSrcDb /* Name of database within pSrcDb */
  52963. ){
  52964. sqlite3_backup *p; /* Value to return */
  52965. /* Lock the source database handle. The destination database
  52966. ** handle is not locked in this routine, but it is locked in
  52967. ** sqlite3_backup_step(). The user is required to ensure that no
  52968. ** other thread accesses the destination handle for the duration
  52969. ** of the backup operation. Any attempt to use the destination
  52970. ** database connection while a backup is in progress may cause
  52971. ** a malfunction or a deadlock.
  52972. */
  52973. sqlite3_mutex_enter(pSrcDb->mutex);
  52974. sqlite3_mutex_enter(pDestDb->mutex);
  52975. if( pSrcDb==pDestDb ){
  52976. sqlite3Error(
  52977. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  52978. );
  52979. p = 0;
  52980. }else {
  52981. /* Allocate space for a new sqlite3_backup object...
  52982. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  52983. ** call to sqlite3_backup_init() and is destroyed by a call to
  52984. ** sqlite3_backup_finish(). */
  52985. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  52986. if( !p ){
  52987. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  52988. }
  52989. }
  52990. /* If the allocation succeeded, populate the new object. */
  52991. if( p ){
  52992. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  52993. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  52994. p->pDestDb = pDestDb;
  52995. p->pSrcDb = pSrcDb;
  52996. p->iNext = 1;
  52997. p->isAttached = 0;
  52998. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  52999. /* One (or both) of the named databases did not exist or an OOM
  53000. ** error was hit. The error has already been written into the
  53001. ** pDestDb handle. All that is left to do here is free the
  53002. ** sqlite3_backup structure.
  53003. */
  53004. sqlite3_free(p);
  53005. p = 0;
  53006. }
  53007. }
  53008. if( p ){
  53009. p->pSrc->nBackup++;
  53010. }
  53011. sqlite3_mutex_leave(pDestDb->mutex);
  53012. sqlite3_mutex_leave(pSrcDb->mutex);
  53013. return p;
  53014. }
  53015. /*
  53016. ** Argument rc is an SQLite error code. Return true if this error is
  53017. ** considered fatal if encountered during a backup operation. All errors
  53018. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  53019. */
  53020. static int isFatalError(int rc){
  53021. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  53022. }
  53023. /*
  53024. ** Parameter zSrcData points to a buffer containing the data for
  53025. ** page iSrcPg from the source database. Copy this data into the
  53026. ** destination database.
  53027. */
  53028. static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
  53029. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  53030. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  53031. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  53032. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  53033. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  53034. #ifdef SQLITE_HAS_CODEC
  53035. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  53036. ** guaranteed that the shared-mutex is held by this thread, handle
  53037. ** p->pSrc may not actually be the owner. */
  53038. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  53039. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  53040. #endif
  53041. int rc = SQLITE_OK;
  53042. i64 iOff;
  53043. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  53044. assert( p->bDestLocked );
  53045. assert( !isFatalError(p->rc) );
  53046. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  53047. assert( zSrcData );
  53048. /* Catch the case where the destination is an in-memory database and the
  53049. ** page sizes of the source and destination differ.
  53050. */
  53051. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  53052. rc = SQLITE_READONLY;
  53053. }
  53054. #ifdef SQLITE_HAS_CODEC
  53055. /* Backup is not possible if the page size of the destination is changing
  53056. ** and a codec is in use.
  53057. */
  53058. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  53059. rc = SQLITE_READONLY;
  53060. }
  53061. /* Backup is not possible if the number of bytes of reserve space differ
  53062. ** between source and destination. If there is a difference, try to
  53063. ** fix the destination to agree with the source. If that is not possible,
  53064. ** then the backup cannot proceed.
  53065. */
  53066. if( nSrcReserve!=nDestReserve ){
  53067. u32 newPgsz = nSrcPgsz;
  53068. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  53069. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  53070. }
  53071. #endif
  53072. /* This loop runs once for each destination page spanned by the source
  53073. ** page. For each iteration, variable iOff is set to the byte offset
  53074. ** of the destination page.
  53075. */
  53076. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  53077. DbPage *pDestPg = 0;
  53078. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  53079. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  53080. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  53081. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  53082. ){
  53083. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  53084. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  53085. u8 *zOut = &zDestData[iOff%nDestPgsz];
  53086. /* Copy the data from the source page into the destination page.
  53087. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  53088. ** and the pager code use this trick (clearing the first byte
  53089. ** of the page 'extra' space to invalidate the Btree layers
  53090. ** cached parse of the page). MemPage.isInit is marked
  53091. ** "MUST BE FIRST" for this purpose.
  53092. */
  53093. memcpy(zOut, zIn, nCopy);
  53094. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  53095. }
  53096. sqlite3PagerUnref(pDestPg);
  53097. }
  53098. return rc;
  53099. }
  53100. /*
  53101. ** If pFile is currently larger than iSize bytes, then truncate it to
  53102. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  53103. ** this function is a no-op.
  53104. **
  53105. ** Return SQLITE_OK if everything is successful, or an SQLite error
  53106. ** code if an error occurs.
  53107. */
  53108. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  53109. i64 iCurrent;
  53110. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  53111. if( rc==SQLITE_OK && iCurrent>iSize ){
  53112. rc = sqlite3OsTruncate(pFile, iSize);
  53113. }
  53114. return rc;
  53115. }
  53116. /*
  53117. ** Register this backup object with the associated source pager for
  53118. ** callbacks when pages are changed or the cache invalidated.
  53119. */
  53120. static void attachBackupObject(sqlite3_backup *p){
  53121. sqlite3_backup **pp;
  53122. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  53123. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  53124. p->pNext = *pp;
  53125. *pp = p;
  53126. p->isAttached = 1;
  53127. }
  53128. /*
  53129. ** Copy nPage pages from the source b-tree to the destination.
  53130. */
  53131. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  53132. int rc;
  53133. int destMode; /* Destination journal mode */
  53134. int pgszSrc = 0; /* Source page size */
  53135. int pgszDest = 0; /* Destination page size */
  53136. sqlite3_mutex_enter(p->pSrcDb->mutex);
  53137. sqlite3BtreeEnter(p->pSrc);
  53138. if( p->pDestDb ){
  53139. sqlite3_mutex_enter(p->pDestDb->mutex);
  53140. }
  53141. rc = p->rc;
  53142. if( !isFatalError(rc) ){
  53143. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  53144. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  53145. int ii; /* Iterator variable */
  53146. int nSrcPage = -1; /* Size of source db in pages */
  53147. int bCloseTrans = 0; /* True if src db requires unlocking */
  53148. /* If the source pager is currently in a write-transaction, return
  53149. ** SQLITE_BUSY immediately.
  53150. */
  53151. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  53152. rc = SQLITE_BUSY;
  53153. }else{
  53154. rc = SQLITE_OK;
  53155. }
  53156. /* Lock the destination database, if it is not locked already. */
  53157. if( SQLITE_OK==rc && p->bDestLocked==0
  53158. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  53159. ){
  53160. p->bDestLocked = 1;
  53161. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  53162. }
  53163. /* If there is no open read-transaction on the source database, open
  53164. ** one now. If a transaction is opened here, then it will be closed
  53165. ** before this function exits.
  53166. */
  53167. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  53168. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  53169. bCloseTrans = 1;
  53170. }
  53171. /* Do not allow backup if the destination database is in WAL mode
  53172. ** and the page sizes are different between source and destination */
  53173. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  53174. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  53175. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  53176. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  53177. rc = SQLITE_READONLY;
  53178. }
  53179. /* Now that there is a read-lock on the source database, query the
  53180. ** source pager for the number of pages in the database.
  53181. */
  53182. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  53183. assert( nSrcPage>=0 );
  53184. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  53185. const Pgno iSrcPg = p->iNext; /* Source page number */
  53186. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  53187. DbPage *pSrcPg; /* Source page object */
  53188. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  53189. if( rc==SQLITE_OK ){
  53190. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
  53191. sqlite3PagerUnref(pSrcPg);
  53192. }
  53193. }
  53194. p->iNext++;
  53195. }
  53196. if( rc==SQLITE_OK ){
  53197. p->nPagecount = nSrcPage;
  53198. p->nRemaining = nSrcPage+1-p->iNext;
  53199. if( p->iNext>(Pgno)nSrcPage ){
  53200. rc = SQLITE_DONE;
  53201. }else if( !p->isAttached ){
  53202. attachBackupObject(p);
  53203. }
  53204. }
  53205. /* Update the schema version field in the destination database. This
  53206. ** is to make sure that the schema-version really does change in
  53207. ** the case where the source and destination databases have the
  53208. ** same schema version.
  53209. */
  53210. if( rc==SQLITE_DONE ){
  53211. if( nSrcPage==0 ){
  53212. rc = sqlite3BtreeNewDb(p->pDest);
  53213. nSrcPage = 1;
  53214. }
  53215. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  53216. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  53217. }
  53218. if( rc==SQLITE_OK ){
  53219. if( p->pDestDb ){
  53220. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  53221. }
  53222. if( destMode==PAGER_JOURNALMODE_WAL ){
  53223. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  53224. }
  53225. }
  53226. if( rc==SQLITE_OK ){
  53227. int nDestTruncate;
  53228. /* Set nDestTruncate to the final number of pages in the destination
  53229. ** database. The complication here is that the destination page
  53230. ** size may be different to the source page size.
  53231. **
  53232. ** If the source page size is smaller than the destination page size,
  53233. ** round up. In this case the call to sqlite3OsTruncate() below will
  53234. ** fix the size of the file. However it is important to call
  53235. ** sqlite3PagerTruncateImage() here so that any pages in the
  53236. ** destination file that lie beyond the nDestTruncate page mark are
  53237. ** journalled by PagerCommitPhaseOne() before they are destroyed
  53238. ** by the file truncation.
  53239. */
  53240. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  53241. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  53242. if( pgszSrc<pgszDest ){
  53243. int ratio = pgszDest/pgszSrc;
  53244. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  53245. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  53246. nDestTruncate--;
  53247. }
  53248. }else{
  53249. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  53250. }
  53251. assert( nDestTruncate>0 );
  53252. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  53253. if( pgszSrc<pgszDest ){
  53254. /* If the source page-size is smaller than the destination page-size,
  53255. ** two extra things may need to happen:
  53256. **
  53257. ** * The destination may need to be truncated, and
  53258. **
  53259. ** * Data stored on the pages immediately following the
  53260. ** pending-byte page in the source database may need to be
  53261. ** copied into the destination database.
  53262. */
  53263. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  53264. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  53265. i64 iOff;
  53266. i64 iEnd;
  53267. assert( pFile );
  53268. assert( nDestTruncate==0
  53269. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  53270. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  53271. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  53272. ));
  53273. /* This call ensures that all data required to recreate the original
  53274. ** database has been stored in the journal for pDestPager and the
  53275. ** journal synced to disk. So at this point we may safely modify
  53276. ** the database file in any way, knowing that if a power failure
  53277. ** occurs, the original database will be reconstructed from the
  53278. ** journal file. */
  53279. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  53280. /* Write the extra pages and truncate the database file as required */
  53281. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  53282. for(
  53283. iOff=PENDING_BYTE+pgszSrc;
  53284. rc==SQLITE_OK && iOff<iEnd;
  53285. iOff+=pgszSrc
  53286. ){
  53287. PgHdr *pSrcPg = 0;
  53288. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  53289. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  53290. if( rc==SQLITE_OK ){
  53291. u8 *zData = sqlite3PagerGetData(pSrcPg);
  53292. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  53293. }
  53294. sqlite3PagerUnref(pSrcPg);
  53295. }
  53296. if( rc==SQLITE_OK ){
  53297. rc = backupTruncateFile(pFile, iSize);
  53298. }
  53299. /* Sync the database file to disk. */
  53300. if( rc==SQLITE_OK ){
  53301. rc = sqlite3PagerSync(pDestPager);
  53302. }
  53303. }else{
  53304. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  53305. }
  53306. /* Finish committing the transaction to the destination database. */
  53307. if( SQLITE_OK==rc
  53308. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  53309. ){
  53310. rc = SQLITE_DONE;
  53311. }
  53312. }
  53313. }
  53314. /* If bCloseTrans is true, then this function opened a read transaction
  53315. ** on the source database. Close the read transaction here. There is
  53316. ** no need to check the return values of the btree methods here, as
  53317. ** "committing" a read-only transaction cannot fail.
  53318. */
  53319. if( bCloseTrans ){
  53320. TESTONLY( int rc2 );
  53321. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  53322. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  53323. assert( rc2==SQLITE_OK );
  53324. }
  53325. if( rc==SQLITE_IOERR_NOMEM ){
  53326. rc = SQLITE_NOMEM;
  53327. }
  53328. p->rc = rc;
  53329. }
  53330. if( p->pDestDb ){
  53331. sqlite3_mutex_leave(p->pDestDb->mutex);
  53332. }
  53333. sqlite3BtreeLeave(p->pSrc);
  53334. sqlite3_mutex_leave(p->pSrcDb->mutex);
  53335. return rc;
  53336. }
  53337. /*
  53338. ** Release all resources associated with an sqlite3_backup* handle.
  53339. */
  53340. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  53341. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  53342. sqlite3 *pSrcDb; /* Source database connection */
  53343. int rc; /* Value to return */
  53344. /* Enter the mutexes */
  53345. if( p==0 ) return SQLITE_OK;
  53346. pSrcDb = p->pSrcDb;
  53347. sqlite3_mutex_enter(pSrcDb->mutex);
  53348. sqlite3BtreeEnter(p->pSrc);
  53349. if( p->pDestDb ){
  53350. sqlite3_mutex_enter(p->pDestDb->mutex);
  53351. }
  53352. /* Detach this backup from the source pager. */
  53353. if( p->pDestDb ){
  53354. p->pSrc->nBackup--;
  53355. }
  53356. if( p->isAttached ){
  53357. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  53358. while( *pp!=p ){
  53359. pp = &(*pp)->pNext;
  53360. }
  53361. *pp = p->pNext;
  53362. }
  53363. /* If a transaction is still open on the Btree, roll it back. */
  53364. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  53365. /* Set the error code of the destination database handle. */
  53366. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  53367. sqlite3Error(p->pDestDb, rc, 0);
  53368. /* Exit the mutexes and free the backup context structure. */
  53369. if( p->pDestDb ){
  53370. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  53371. }
  53372. sqlite3BtreeLeave(p->pSrc);
  53373. if( p->pDestDb ){
  53374. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  53375. ** call to sqlite3_backup_init() and is destroyed by a call to
  53376. ** sqlite3_backup_finish(). */
  53377. sqlite3_free(p);
  53378. }
  53379. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  53380. return rc;
  53381. }
  53382. /*
  53383. ** Return the number of pages still to be backed up as of the most recent
  53384. ** call to sqlite3_backup_step().
  53385. */
  53386. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  53387. return p->nRemaining;
  53388. }
  53389. /*
  53390. ** Return the total number of pages in the source database as of the most
  53391. ** recent call to sqlite3_backup_step().
  53392. */
  53393. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  53394. return p->nPagecount;
  53395. }
  53396. /*
  53397. ** This function is called after the contents of page iPage of the
  53398. ** source database have been modified. If page iPage has already been
  53399. ** copied into the destination database, then the data written to the
  53400. ** destination is now invalidated. The destination copy of iPage needs
  53401. ** to be updated with the new data before the backup operation is
  53402. ** complete.
  53403. **
  53404. ** It is assumed that the mutex associated with the BtShared object
  53405. ** corresponding to the source database is held when this function is
  53406. ** called.
  53407. */
  53408. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  53409. sqlite3_backup *p; /* Iterator variable */
  53410. for(p=pBackup; p; p=p->pNext){
  53411. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  53412. if( !isFatalError(p->rc) && iPage<p->iNext ){
  53413. /* The backup process p has already copied page iPage. But now it
  53414. ** has been modified by a transaction on the source pager. Copy
  53415. ** the new data into the backup.
  53416. */
  53417. int rc;
  53418. assert( p->pDestDb );
  53419. sqlite3_mutex_enter(p->pDestDb->mutex);
  53420. rc = backupOnePage(p, iPage, aData);
  53421. sqlite3_mutex_leave(p->pDestDb->mutex);
  53422. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  53423. if( rc!=SQLITE_OK ){
  53424. p->rc = rc;
  53425. }
  53426. }
  53427. }
  53428. }
  53429. /*
  53430. ** Restart the backup process. This is called when the pager layer
  53431. ** detects that the database has been modified by an external database
  53432. ** connection. In this case there is no way of knowing which of the
  53433. ** pages that have been copied into the destination database are still
  53434. ** valid and which are not, so the entire process needs to be restarted.
  53435. **
  53436. ** It is assumed that the mutex associated with the BtShared object
  53437. ** corresponding to the source database is held when this function is
  53438. ** called.
  53439. */
  53440. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  53441. sqlite3_backup *p; /* Iterator variable */
  53442. for(p=pBackup; p; p=p->pNext){
  53443. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  53444. p->iNext = 1;
  53445. }
  53446. }
  53447. #ifndef SQLITE_OMIT_VACUUM
  53448. /*
  53449. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  53450. ** must be active for both files.
  53451. **
  53452. ** The size of file pTo may be reduced by this operation. If anything
  53453. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  53454. ** transaction is committed before returning.
  53455. */
  53456. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  53457. int rc;
  53458. sqlite3_file *pFd; /* File descriptor for database pTo */
  53459. sqlite3_backup b;
  53460. sqlite3BtreeEnter(pTo);
  53461. sqlite3BtreeEnter(pFrom);
  53462. assert( sqlite3BtreeIsInTrans(pTo) );
  53463. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  53464. if( pFd->pMethods ){
  53465. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  53466. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  53467. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  53468. if( rc ) goto copy_finished;
  53469. }
  53470. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  53471. ** to 0. This is used by the implementations of sqlite3_backup_step()
  53472. ** and sqlite3_backup_finish() to detect that they are being called
  53473. ** from this function, not directly by the user.
  53474. */
  53475. memset(&b, 0, sizeof(b));
  53476. b.pSrcDb = pFrom->db;
  53477. b.pSrc = pFrom;
  53478. b.pDest = pTo;
  53479. b.iNext = 1;
  53480. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  53481. ** file. By passing this as the number of pages to copy to
  53482. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  53483. ** within a single call (unless an error occurs). The assert() statement
  53484. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  53485. ** or an error code.
  53486. */
  53487. sqlite3_backup_step(&b, 0x7FFFFFFF);
  53488. assert( b.rc!=SQLITE_OK );
  53489. rc = sqlite3_backup_finish(&b);
  53490. if( rc==SQLITE_OK ){
  53491. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  53492. }else{
  53493. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  53494. }
  53495. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  53496. copy_finished:
  53497. sqlite3BtreeLeave(pFrom);
  53498. sqlite3BtreeLeave(pTo);
  53499. return rc;
  53500. }
  53501. #endif /* SQLITE_OMIT_VACUUM */
  53502. /************** End of backup.c **********************************************/
  53503. /************** Begin file vdbemem.c *****************************************/
  53504. /*
  53505. ** 2004 May 26
  53506. **
  53507. ** The author disclaims copyright to this source code. In place of
  53508. ** a legal notice, here is a blessing:
  53509. **
  53510. ** May you do good and not evil.
  53511. ** May you find forgiveness for yourself and forgive others.
  53512. ** May you share freely, never taking more than you give.
  53513. **
  53514. *************************************************************************
  53515. **
  53516. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  53517. ** stores a single value in the VDBE. Mem is an opaque structure visible
  53518. ** only within the VDBE. Interface routines refer to a Mem using the
  53519. ** name sqlite_value
  53520. */
  53521. /*
  53522. ** If pMem is an object with a valid string representation, this routine
  53523. ** ensures the internal encoding for the string representation is
  53524. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  53525. **
  53526. ** If pMem is not a string object, or the encoding of the string
  53527. ** representation is already stored using the requested encoding, then this
  53528. ** routine is a no-op.
  53529. **
  53530. ** SQLITE_OK is returned if the conversion is successful (or not required).
  53531. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  53532. ** between formats.
  53533. */
  53534. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  53535. int rc;
  53536. assert( (pMem->flags&MEM_RowSet)==0 );
  53537. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  53538. || desiredEnc==SQLITE_UTF16BE );
  53539. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  53540. return SQLITE_OK;
  53541. }
  53542. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53543. #ifdef SQLITE_OMIT_UTF16
  53544. return SQLITE_ERROR;
  53545. #else
  53546. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  53547. ** then the encoding of the value may not have changed.
  53548. */
  53549. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  53550. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  53551. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  53552. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  53553. return rc;
  53554. #endif
  53555. }
  53556. /*
  53557. ** Make sure pMem->z points to a writable allocation of at least
  53558. ** n bytes.
  53559. **
  53560. ** If the third argument passed to this function is true, then memory
  53561. ** cell pMem must contain a string or blob. In this case the content is
  53562. ** preserved. Otherwise, if the third parameter to this function is false,
  53563. ** any current string or blob value may be discarded.
  53564. **
  53565. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  53566. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  53567. ** not set, Mem.n is zeroed.
  53568. */
  53569. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  53570. assert( 1 >=
  53571. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  53572. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  53573. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  53574. ((pMem->flags&MEM_Static) ? 1 : 0)
  53575. );
  53576. assert( (pMem->flags&MEM_RowSet)==0 );
  53577. /* If the preserve flag is set to true, then the memory cell must already
  53578. ** contain a valid string or blob value. */
  53579. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  53580. if( n<32 ) n = 32;
  53581. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  53582. if( preserve && pMem->z==pMem->zMalloc ){
  53583. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  53584. preserve = 0;
  53585. }else{
  53586. sqlite3DbFree(pMem->db, pMem->zMalloc);
  53587. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  53588. }
  53589. }
  53590. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  53591. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  53592. }
  53593. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  53594. assert( pMem->xDel!=SQLITE_DYNAMIC );
  53595. pMem->xDel((void *)(pMem->z));
  53596. }
  53597. pMem->z = pMem->zMalloc;
  53598. if( pMem->z==0 ){
  53599. pMem->flags = MEM_Null;
  53600. }else{
  53601. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  53602. }
  53603. pMem->xDel = 0;
  53604. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  53605. }
  53606. /*
  53607. ** Make the given Mem object MEM_Dyn. In other words, make it so
  53608. ** that any TEXT or BLOB content is stored in memory obtained from
  53609. ** malloc(). In this way, we know that the memory is safe to be
  53610. ** overwritten or altered.
  53611. **
  53612. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  53613. */
  53614. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  53615. int f;
  53616. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53617. assert( (pMem->flags&MEM_RowSet)==0 );
  53618. ExpandBlob(pMem);
  53619. f = pMem->flags;
  53620. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  53621. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  53622. return SQLITE_NOMEM;
  53623. }
  53624. pMem->z[pMem->n] = 0;
  53625. pMem->z[pMem->n+1] = 0;
  53626. pMem->flags |= MEM_Term;
  53627. #ifdef SQLITE_DEBUG
  53628. pMem->pScopyFrom = 0;
  53629. #endif
  53630. }
  53631. return SQLITE_OK;
  53632. }
  53633. /*
  53634. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  53635. ** blob stored in dynamically allocated space.
  53636. */
  53637. #ifndef SQLITE_OMIT_INCRBLOB
  53638. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  53639. if( pMem->flags & MEM_Zero ){
  53640. int nByte;
  53641. assert( pMem->flags&MEM_Blob );
  53642. assert( (pMem->flags&MEM_RowSet)==0 );
  53643. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53644. /* Set nByte to the number of bytes required to store the expanded blob. */
  53645. nByte = pMem->n + pMem->u.nZero;
  53646. if( nByte<=0 ){
  53647. nByte = 1;
  53648. }
  53649. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  53650. return SQLITE_NOMEM;
  53651. }
  53652. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  53653. pMem->n += pMem->u.nZero;
  53654. pMem->flags &= ~(MEM_Zero|MEM_Term);
  53655. }
  53656. return SQLITE_OK;
  53657. }
  53658. #endif
  53659. /*
  53660. ** Make sure the given Mem is \u0000 terminated.
  53661. */
  53662. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  53663. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53664. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  53665. return SQLITE_OK; /* Nothing to do */
  53666. }
  53667. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  53668. return SQLITE_NOMEM;
  53669. }
  53670. pMem->z[pMem->n] = 0;
  53671. pMem->z[pMem->n+1] = 0;
  53672. pMem->flags |= MEM_Term;
  53673. return SQLITE_OK;
  53674. }
  53675. /*
  53676. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  53677. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  53678. ** is a no-op.
  53679. **
  53680. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  53681. **
  53682. ** A MEM_Null value will never be passed to this function. This function is
  53683. ** used for converting values to text for returning to the user (i.e. via
  53684. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  53685. ** keys are strings. In the former case a NULL pointer is returned the
  53686. ** user and the later is an internal programming error.
  53687. */
  53688. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  53689. int rc = SQLITE_OK;
  53690. int fg = pMem->flags;
  53691. const int nByte = 32;
  53692. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53693. assert( !(fg&MEM_Zero) );
  53694. assert( !(fg&(MEM_Str|MEM_Blob)) );
  53695. assert( fg&(MEM_Int|MEM_Real) );
  53696. assert( (pMem->flags&MEM_RowSet)==0 );
  53697. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53698. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  53699. return SQLITE_NOMEM;
  53700. }
  53701. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  53702. ** string representation of the value. Then, if the required encoding
  53703. ** is UTF-16le or UTF-16be do a translation.
  53704. **
  53705. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  53706. */
  53707. if( fg & MEM_Int ){
  53708. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  53709. }else{
  53710. assert( fg & MEM_Real );
  53711. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  53712. }
  53713. pMem->n = sqlite3Strlen30(pMem->z);
  53714. pMem->enc = SQLITE_UTF8;
  53715. pMem->flags |= MEM_Str|MEM_Term;
  53716. sqlite3VdbeChangeEncoding(pMem, enc);
  53717. return rc;
  53718. }
  53719. /*
  53720. ** Memory cell pMem contains the context of an aggregate function.
  53721. ** This routine calls the finalize method for that function. The
  53722. ** result of the aggregate is stored back into pMem.
  53723. **
  53724. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  53725. ** otherwise.
  53726. */
  53727. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  53728. int rc = SQLITE_OK;
  53729. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  53730. sqlite3_context ctx;
  53731. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  53732. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53733. memset(&ctx, 0, sizeof(ctx));
  53734. ctx.s.flags = MEM_Null;
  53735. ctx.s.db = pMem->db;
  53736. ctx.pMem = pMem;
  53737. ctx.pFunc = pFunc;
  53738. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  53739. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  53740. sqlite3DbFree(pMem->db, pMem->zMalloc);
  53741. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  53742. rc = ctx.isError;
  53743. }
  53744. return rc;
  53745. }
  53746. /*
  53747. ** If the memory cell contains a string value that must be freed by
  53748. ** invoking an external callback, free it now. Calling this function
  53749. ** does not free any Mem.zMalloc buffer.
  53750. */
  53751. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  53752. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  53753. if( p->flags&MEM_Agg ){
  53754. sqlite3VdbeMemFinalize(p, p->u.pDef);
  53755. assert( (p->flags & MEM_Agg)==0 );
  53756. sqlite3VdbeMemRelease(p);
  53757. }else if( p->flags&MEM_Dyn && p->xDel ){
  53758. assert( (p->flags&MEM_RowSet)==0 );
  53759. assert( p->xDel!=SQLITE_DYNAMIC );
  53760. p->xDel((void *)p->z);
  53761. p->xDel = 0;
  53762. }else if( p->flags&MEM_RowSet ){
  53763. sqlite3RowSetClear(p->u.pRowSet);
  53764. }else if( p->flags&MEM_Frame ){
  53765. sqlite3VdbeMemSetNull(p);
  53766. }
  53767. }
  53768. /*
  53769. ** Release any memory held by the Mem. This may leave the Mem in an
  53770. ** inconsistent state, for example with (Mem.z==0) and
  53771. ** (Mem.type==SQLITE_TEXT).
  53772. */
  53773. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  53774. VdbeMemRelease(p);
  53775. sqlite3DbFree(p->db, p->zMalloc);
  53776. p->z = 0;
  53777. p->zMalloc = 0;
  53778. p->xDel = 0;
  53779. }
  53780. /*
  53781. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  53782. ** If the double is too large, return 0x8000000000000000.
  53783. **
  53784. ** Most systems appear to do this simply by assigning
  53785. ** variables and without the extra range tests. But
  53786. ** there are reports that windows throws an expection
  53787. ** if the floating point value is out of range. (See ticket #2880.)
  53788. ** Because we do not completely understand the problem, we will
  53789. ** take the conservative approach and always do range tests
  53790. ** before attempting the conversion.
  53791. */
  53792. static i64 doubleToInt64(double r){
  53793. #ifdef SQLITE_OMIT_FLOATING_POINT
  53794. /* When floating-point is omitted, double and int64 are the same thing */
  53795. return r;
  53796. #else
  53797. /*
  53798. ** Many compilers we encounter do not define constants for the
  53799. ** minimum and maximum 64-bit integers, or they define them
  53800. ** inconsistently. And many do not understand the "LL" notation.
  53801. ** So we define our own static constants here using nothing
  53802. ** larger than a 32-bit integer constant.
  53803. */
  53804. static const i64 maxInt = LARGEST_INT64;
  53805. static const i64 minInt = SMALLEST_INT64;
  53806. if( r<(double)minInt ){
  53807. return minInt;
  53808. }else if( r>(double)maxInt ){
  53809. /* minInt is correct here - not maxInt. It turns out that assigning
  53810. ** a very large positive number to an integer results in a very large
  53811. ** negative integer. This makes no sense, but it is what x86 hardware
  53812. ** does so for compatibility we will do the same in software. */
  53813. return minInt;
  53814. }else{
  53815. return (i64)r;
  53816. }
  53817. #endif
  53818. }
  53819. /*
  53820. ** Return some kind of integer value which is the best we can do
  53821. ** at representing the value that *pMem describes as an integer.
  53822. ** If pMem is an integer, then the value is exact. If pMem is
  53823. ** a floating-point then the value returned is the integer part.
  53824. ** If pMem is a string or blob, then we make an attempt to convert
  53825. ** it into a integer and return that. If pMem represents an
  53826. ** an SQL-NULL value, return 0.
  53827. **
  53828. ** If pMem represents a string value, its encoding might be changed.
  53829. */
  53830. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  53831. int flags;
  53832. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53833. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53834. flags = pMem->flags;
  53835. if( flags & MEM_Int ){
  53836. return pMem->u.i;
  53837. }else if( flags & MEM_Real ){
  53838. return doubleToInt64(pMem->r);
  53839. }else if( flags & (MEM_Str|MEM_Blob) ){
  53840. i64 value = 0;
  53841. assert( pMem->z || pMem->n==0 );
  53842. testcase( pMem->z==0 );
  53843. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  53844. return value;
  53845. }else{
  53846. return 0;
  53847. }
  53848. }
  53849. /*
  53850. ** Return the best representation of pMem that we can get into a
  53851. ** double. If pMem is already a double or an integer, return its
  53852. ** value. If it is a string or blob, try to convert it to a double.
  53853. ** If it is a NULL, return 0.0.
  53854. */
  53855. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  53856. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53857. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53858. if( pMem->flags & MEM_Real ){
  53859. return pMem->r;
  53860. }else if( pMem->flags & MEM_Int ){
  53861. return (double)pMem->u.i;
  53862. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  53863. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  53864. double val = (double)0;
  53865. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  53866. return val;
  53867. }else{
  53868. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  53869. return (double)0;
  53870. }
  53871. }
  53872. /*
  53873. ** The MEM structure is already a MEM_Real. Try to also make it a
  53874. ** MEM_Int if we can.
  53875. */
  53876. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  53877. assert( pMem->flags & MEM_Real );
  53878. assert( (pMem->flags & MEM_RowSet)==0 );
  53879. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53880. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53881. pMem->u.i = doubleToInt64(pMem->r);
  53882. /* Only mark the value as an integer if
  53883. **
  53884. ** (1) the round-trip conversion real->int->real is a no-op, and
  53885. ** (2) The integer is neither the largest nor the smallest
  53886. ** possible integer (ticket #3922)
  53887. **
  53888. ** The second and third terms in the following conditional enforces
  53889. ** the second condition under the assumption that addition overflow causes
  53890. ** values to wrap around. On x86 hardware, the third term is always
  53891. ** true and could be omitted. But we leave it in because other
  53892. ** architectures might behave differently.
  53893. */
  53894. if( pMem->r==(double)pMem->u.i
  53895. && pMem->u.i>SMALLEST_INT64
  53896. #if defined(__i486__) || defined(__x86_64__)
  53897. && ALWAYS(pMem->u.i<LARGEST_INT64)
  53898. #else
  53899. && pMem->u.i<LARGEST_INT64
  53900. #endif
  53901. ){
  53902. pMem->flags |= MEM_Int;
  53903. }
  53904. }
  53905. /*
  53906. ** Convert pMem to type integer. Invalidate any prior representations.
  53907. */
  53908. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  53909. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53910. assert( (pMem->flags & MEM_RowSet)==0 );
  53911. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53912. pMem->u.i = sqlite3VdbeIntValue(pMem);
  53913. MemSetTypeFlag(pMem, MEM_Int);
  53914. return SQLITE_OK;
  53915. }
  53916. /*
  53917. ** Convert pMem so that it is of type MEM_Real.
  53918. ** Invalidate any prior representations.
  53919. */
  53920. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  53921. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53922. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  53923. pMem->r = sqlite3VdbeRealValue(pMem);
  53924. MemSetTypeFlag(pMem, MEM_Real);
  53925. return SQLITE_OK;
  53926. }
  53927. /*
  53928. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  53929. ** Invalidate any prior representations.
  53930. **
  53931. ** Every effort is made to force the conversion, even if the input
  53932. ** is a string that does not look completely like a number. Convert
  53933. ** as much of the string as we can and ignore the rest.
  53934. */
  53935. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  53936. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  53937. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  53938. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  53939. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  53940. MemSetTypeFlag(pMem, MEM_Int);
  53941. }else{
  53942. pMem->r = sqlite3VdbeRealValue(pMem);
  53943. MemSetTypeFlag(pMem, MEM_Real);
  53944. sqlite3VdbeIntegerAffinity(pMem);
  53945. }
  53946. }
  53947. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  53948. pMem->flags &= ~(MEM_Str|MEM_Blob);
  53949. return SQLITE_OK;
  53950. }
  53951. /*
  53952. ** Delete any previous value and set the value stored in *pMem to NULL.
  53953. */
  53954. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  53955. if( pMem->flags & MEM_Frame ){
  53956. VdbeFrame *pFrame = pMem->u.pFrame;
  53957. pFrame->pParent = pFrame->v->pDelFrame;
  53958. pFrame->v->pDelFrame = pFrame;
  53959. }
  53960. if( pMem->flags & MEM_RowSet ){
  53961. sqlite3RowSetClear(pMem->u.pRowSet);
  53962. }
  53963. MemSetTypeFlag(pMem, MEM_Null);
  53964. pMem->type = SQLITE_NULL;
  53965. }
  53966. /*
  53967. ** Delete any previous value and set the value to be a BLOB of length
  53968. ** n containing all zeros.
  53969. */
  53970. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  53971. sqlite3VdbeMemRelease(pMem);
  53972. pMem->flags = MEM_Blob|MEM_Zero;
  53973. pMem->type = SQLITE_BLOB;
  53974. pMem->n = 0;
  53975. if( n<0 ) n = 0;
  53976. pMem->u.nZero = n;
  53977. pMem->enc = SQLITE_UTF8;
  53978. #ifdef SQLITE_OMIT_INCRBLOB
  53979. sqlite3VdbeMemGrow(pMem, n, 0);
  53980. if( pMem->z ){
  53981. pMem->n = n;
  53982. memset(pMem->z, 0, n);
  53983. }
  53984. #endif
  53985. }
  53986. /*
  53987. ** Delete any previous value and set the value stored in *pMem to val,
  53988. ** manifest type INTEGER.
  53989. */
  53990. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  53991. sqlite3VdbeMemRelease(pMem);
  53992. pMem->u.i = val;
  53993. pMem->flags = MEM_Int;
  53994. pMem->type = SQLITE_INTEGER;
  53995. }
  53996. #ifndef SQLITE_OMIT_FLOATING_POINT
  53997. /*
  53998. ** Delete any previous value and set the value stored in *pMem to val,
  53999. ** manifest type REAL.
  54000. */
  54001. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  54002. if( sqlite3IsNaN(val) ){
  54003. sqlite3VdbeMemSetNull(pMem);
  54004. }else{
  54005. sqlite3VdbeMemRelease(pMem);
  54006. pMem->r = val;
  54007. pMem->flags = MEM_Real;
  54008. pMem->type = SQLITE_FLOAT;
  54009. }
  54010. }
  54011. #endif
  54012. /*
  54013. ** Delete any previous value and set the value of pMem to be an
  54014. ** empty boolean index.
  54015. */
  54016. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  54017. sqlite3 *db = pMem->db;
  54018. assert( db!=0 );
  54019. assert( (pMem->flags & MEM_RowSet)==0 );
  54020. sqlite3VdbeMemRelease(pMem);
  54021. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  54022. if( db->mallocFailed ){
  54023. pMem->flags = MEM_Null;
  54024. }else{
  54025. assert( pMem->zMalloc );
  54026. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  54027. sqlite3DbMallocSize(db, pMem->zMalloc));
  54028. assert( pMem->u.pRowSet!=0 );
  54029. pMem->flags = MEM_RowSet;
  54030. }
  54031. }
  54032. /*
  54033. ** Return true if the Mem object contains a TEXT or BLOB that is
  54034. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  54035. */
  54036. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  54037. assert( p->db!=0 );
  54038. if( p->flags & (MEM_Str|MEM_Blob) ){
  54039. int n = p->n;
  54040. if( p->flags & MEM_Zero ){
  54041. n += p->u.nZero;
  54042. }
  54043. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  54044. }
  54045. return 0;
  54046. }
  54047. #ifdef SQLITE_DEBUG
  54048. /*
  54049. ** This routine prepares a memory cell for modication by breaking
  54050. ** its link to a shallow copy and by marking any current shallow
  54051. ** copies of this cell as invalid.
  54052. **
  54053. ** This is used for testing and debugging only - to make sure shallow
  54054. ** copies are not misused.
  54055. */
  54056. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  54057. int i;
  54058. Mem *pX;
  54059. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  54060. if( pX->pScopyFrom==pMem ){
  54061. pX->flags |= MEM_Invalid;
  54062. pX->pScopyFrom = 0;
  54063. }
  54064. }
  54065. pMem->pScopyFrom = 0;
  54066. }
  54067. #endif /* SQLITE_DEBUG */
  54068. /*
  54069. ** Size of struct Mem not including the Mem.zMalloc member.
  54070. */
  54071. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  54072. /*
  54073. ** Make an shallow copy of pFrom into pTo. Prior contents of
  54074. ** pTo are freed. The pFrom->z field is not duplicated. If
  54075. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  54076. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  54077. */
  54078. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  54079. assert( (pFrom->flags & MEM_RowSet)==0 );
  54080. VdbeMemRelease(pTo);
  54081. memcpy(pTo, pFrom, MEMCELLSIZE);
  54082. pTo->xDel = 0;
  54083. if( (pFrom->flags&MEM_Static)==0 ){
  54084. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  54085. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  54086. pTo->flags |= srcType;
  54087. }
  54088. }
  54089. /*
  54090. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  54091. ** freed before the copy is made.
  54092. */
  54093. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  54094. int rc = SQLITE_OK;
  54095. assert( (pFrom->flags & MEM_RowSet)==0 );
  54096. VdbeMemRelease(pTo);
  54097. memcpy(pTo, pFrom, MEMCELLSIZE);
  54098. pTo->flags &= ~MEM_Dyn;
  54099. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  54100. if( 0==(pFrom->flags&MEM_Static) ){
  54101. pTo->flags |= MEM_Ephem;
  54102. rc = sqlite3VdbeMemMakeWriteable(pTo);
  54103. }
  54104. }
  54105. return rc;
  54106. }
  54107. /*
  54108. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  54109. ** freed. If pFrom contains ephemeral data, a copy is made.
  54110. **
  54111. ** pFrom contains an SQL NULL when this routine returns.
  54112. */
  54113. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  54114. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  54115. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  54116. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  54117. sqlite3VdbeMemRelease(pTo);
  54118. memcpy(pTo, pFrom, sizeof(Mem));
  54119. pFrom->flags = MEM_Null;
  54120. pFrom->xDel = 0;
  54121. pFrom->zMalloc = 0;
  54122. }
  54123. /*
  54124. ** Change the value of a Mem to be a string or a BLOB.
  54125. **
  54126. ** The memory management strategy depends on the value of the xDel
  54127. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  54128. ** string is copied into a (possibly existing) buffer managed by the
  54129. ** Mem structure. Otherwise, any existing buffer is freed and the
  54130. ** pointer copied.
  54131. **
  54132. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  54133. ** size limit) then no memory allocation occurs. If the string can be
  54134. ** stored without allocating memory, then it is. If a memory allocation
  54135. ** is required to store the string, then value of pMem is unchanged. In
  54136. ** either case, SQLITE_TOOBIG is returned.
  54137. */
  54138. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  54139. Mem *pMem, /* Memory cell to set to string value */
  54140. const char *z, /* String pointer */
  54141. int n, /* Bytes in string, or negative */
  54142. u8 enc, /* Encoding of z. 0 for BLOBs */
  54143. void (*xDel)(void*) /* Destructor function */
  54144. ){
  54145. int nByte = n; /* New value for pMem->n */
  54146. int iLimit; /* Maximum allowed string or blob size */
  54147. u16 flags = 0; /* New value for pMem->flags */
  54148. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  54149. assert( (pMem->flags & MEM_RowSet)==0 );
  54150. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  54151. if( !z ){
  54152. sqlite3VdbeMemSetNull(pMem);
  54153. return SQLITE_OK;
  54154. }
  54155. if( pMem->db ){
  54156. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  54157. }else{
  54158. iLimit = SQLITE_MAX_LENGTH;
  54159. }
  54160. flags = (enc==0?MEM_Blob:MEM_Str);
  54161. if( nByte<0 ){
  54162. assert( enc!=0 );
  54163. if( enc==SQLITE_UTF8 ){
  54164. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  54165. }else{
  54166. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  54167. }
  54168. flags |= MEM_Term;
  54169. }
  54170. /* The following block sets the new values of Mem.z and Mem.xDel. It
  54171. ** also sets a flag in local variable "flags" to indicate the memory
  54172. ** management (one of MEM_Dyn or MEM_Static).
  54173. */
  54174. if( xDel==SQLITE_TRANSIENT ){
  54175. int nAlloc = nByte;
  54176. if( flags&MEM_Term ){
  54177. nAlloc += (enc==SQLITE_UTF8?1:2);
  54178. }
  54179. if( nByte>iLimit ){
  54180. return SQLITE_TOOBIG;
  54181. }
  54182. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  54183. return SQLITE_NOMEM;
  54184. }
  54185. memcpy(pMem->z, z, nAlloc);
  54186. }else if( xDel==SQLITE_DYNAMIC ){
  54187. sqlite3VdbeMemRelease(pMem);
  54188. pMem->zMalloc = pMem->z = (char *)z;
  54189. pMem->xDel = 0;
  54190. }else{
  54191. sqlite3VdbeMemRelease(pMem);
  54192. pMem->z = (char *)z;
  54193. pMem->xDel = xDel;
  54194. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  54195. }
  54196. pMem->n = nByte;
  54197. pMem->flags = flags;
  54198. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  54199. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  54200. #ifndef SQLITE_OMIT_UTF16
  54201. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  54202. return SQLITE_NOMEM;
  54203. }
  54204. #endif
  54205. if( nByte>iLimit ){
  54206. return SQLITE_TOOBIG;
  54207. }
  54208. return SQLITE_OK;
  54209. }
  54210. /*
  54211. ** Compare the values contained by the two memory cells, returning
  54212. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  54213. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  54214. ** and reals) sorted numerically, followed by text ordered by the collating
  54215. ** sequence pColl and finally blob's ordered by memcmp().
  54216. **
  54217. ** Two NULL values are considered equal by this function.
  54218. */
  54219. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  54220. int rc;
  54221. int f1, f2;
  54222. int combined_flags;
  54223. f1 = pMem1->flags;
  54224. f2 = pMem2->flags;
  54225. combined_flags = f1|f2;
  54226. assert( (combined_flags & MEM_RowSet)==0 );
  54227. /* If one value is NULL, it is less than the other. If both values
  54228. ** are NULL, return 0.
  54229. */
  54230. if( combined_flags&MEM_Null ){
  54231. return (f2&MEM_Null) - (f1&MEM_Null);
  54232. }
  54233. /* If one value is a number and the other is not, the number is less.
  54234. ** If both are numbers, compare as reals if one is a real, or as integers
  54235. ** if both values are integers.
  54236. */
  54237. if( combined_flags&(MEM_Int|MEM_Real) ){
  54238. if( !(f1&(MEM_Int|MEM_Real)) ){
  54239. return 1;
  54240. }
  54241. if( !(f2&(MEM_Int|MEM_Real)) ){
  54242. return -1;
  54243. }
  54244. if( (f1 & f2 & MEM_Int)==0 ){
  54245. double r1, r2;
  54246. if( (f1&MEM_Real)==0 ){
  54247. r1 = (double)pMem1->u.i;
  54248. }else{
  54249. r1 = pMem1->r;
  54250. }
  54251. if( (f2&MEM_Real)==0 ){
  54252. r2 = (double)pMem2->u.i;
  54253. }else{
  54254. r2 = pMem2->r;
  54255. }
  54256. if( r1<r2 ) return -1;
  54257. if( r1>r2 ) return 1;
  54258. return 0;
  54259. }else{
  54260. assert( f1&MEM_Int );
  54261. assert( f2&MEM_Int );
  54262. if( pMem1->u.i < pMem2->u.i ) return -1;
  54263. if( pMem1->u.i > pMem2->u.i ) return 1;
  54264. return 0;
  54265. }
  54266. }
  54267. /* If one value is a string and the other is a blob, the string is less.
  54268. ** If both are strings, compare using the collating functions.
  54269. */
  54270. if( combined_flags&MEM_Str ){
  54271. if( (f1 & MEM_Str)==0 ){
  54272. return 1;
  54273. }
  54274. if( (f2 & MEM_Str)==0 ){
  54275. return -1;
  54276. }
  54277. assert( pMem1->enc==pMem2->enc );
  54278. assert( pMem1->enc==SQLITE_UTF8 ||
  54279. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  54280. /* The collation sequence must be defined at this point, even if
  54281. ** the user deletes the collation sequence after the vdbe program is
  54282. ** compiled (this was not always the case).
  54283. */
  54284. assert( !pColl || pColl->xCmp );
  54285. if( pColl ){
  54286. if( pMem1->enc==pColl->enc ){
  54287. /* The strings are already in the correct encoding. Call the
  54288. ** comparison function directly */
  54289. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  54290. }else{
  54291. const void *v1, *v2;
  54292. int n1, n2;
  54293. Mem c1;
  54294. Mem c2;
  54295. memset(&c1, 0, sizeof(c1));
  54296. memset(&c2, 0, sizeof(c2));
  54297. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  54298. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  54299. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  54300. n1 = v1==0 ? 0 : c1.n;
  54301. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  54302. n2 = v2==0 ? 0 : c2.n;
  54303. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  54304. sqlite3VdbeMemRelease(&c1);
  54305. sqlite3VdbeMemRelease(&c2);
  54306. return rc;
  54307. }
  54308. }
  54309. /* If a NULL pointer was passed as the collate function, fall through
  54310. ** to the blob case and use memcmp(). */
  54311. }
  54312. /* Both values must be blobs. Compare using memcmp(). */
  54313. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  54314. if( rc==0 ){
  54315. rc = pMem1->n - pMem2->n;
  54316. }
  54317. return rc;
  54318. }
  54319. /*
  54320. ** Move data out of a btree key or data field and into a Mem structure.
  54321. ** The data or key is taken from the entry that pCur is currently pointing
  54322. ** to. offset and amt determine what portion of the data or key to retrieve.
  54323. ** key is true to get the key or false to get data. The result is written
  54324. ** into the pMem element.
  54325. **
  54326. ** The pMem structure is assumed to be uninitialized. Any prior content
  54327. ** is overwritten without being freed.
  54328. **
  54329. ** If this routine fails for any reason (malloc returns NULL or unable
  54330. ** to read from the disk) then the pMem is left in an inconsistent state.
  54331. */
  54332. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  54333. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  54334. int offset, /* Offset from the start of data to return bytes from. */
  54335. int amt, /* Number of bytes to return. */
  54336. int key, /* If true, retrieve from the btree key, not data. */
  54337. Mem *pMem /* OUT: Return data in this Mem structure. */
  54338. ){
  54339. char *zData; /* Data from the btree layer */
  54340. int available = 0; /* Number of bytes available on the local btree page */
  54341. int rc = SQLITE_OK; /* Return code */
  54342. assert( sqlite3BtreeCursorIsValid(pCur) );
  54343. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  54344. ** that both the BtShared and database handle mutexes are held. */
  54345. assert( (pMem->flags & MEM_RowSet)==0 );
  54346. if( key ){
  54347. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  54348. }else{
  54349. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  54350. }
  54351. assert( zData!=0 );
  54352. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  54353. sqlite3VdbeMemRelease(pMem);
  54354. pMem->z = &zData[offset];
  54355. pMem->flags = MEM_Blob|MEM_Ephem;
  54356. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  54357. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  54358. pMem->enc = 0;
  54359. pMem->type = SQLITE_BLOB;
  54360. if( key ){
  54361. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  54362. }else{
  54363. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  54364. }
  54365. pMem->z[amt] = 0;
  54366. pMem->z[amt+1] = 0;
  54367. if( rc!=SQLITE_OK ){
  54368. sqlite3VdbeMemRelease(pMem);
  54369. }
  54370. }
  54371. pMem->n = amt;
  54372. return rc;
  54373. }
  54374. /* This function is only available internally, it is not part of the
  54375. ** external API. It works in a similar way to sqlite3_value_text(),
  54376. ** except the data returned is in the encoding specified by the second
  54377. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  54378. ** SQLITE_UTF8.
  54379. **
  54380. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  54381. ** If that is the case, then the result must be aligned on an even byte
  54382. ** boundary.
  54383. */
  54384. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  54385. if( !pVal ) return 0;
  54386. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  54387. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  54388. assert( (pVal->flags & MEM_RowSet)==0 );
  54389. if( pVal->flags&MEM_Null ){
  54390. return 0;
  54391. }
  54392. assert( (MEM_Blob>>3) == MEM_Str );
  54393. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  54394. ExpandBlob(pVal);
  54395. if( pVal->flags&MEM_Str ){
  54396. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  54397. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  54398. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  54399. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  54400. return 0;
  54401. }
  54402. }
  54403. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  54404. }else{
  54405. assert( (pVal->flags&MEM_Blob)==0 );
  54406. sqlite3VdbeMemStringify(pVal, enc);
  54407. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  54408. }
  54409. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  54410. || pVal->db->mallocFailed );
  54411. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  54412. return pVal->z;
  54413. }else{
  54414. return 0;
  54415. }
  54416. }
  54417. /*
  54418. ** Create a new sqlite3_value object.
  54419. */
  54420. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  54421. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  54422. if( p ){
  54423. p->flags = MEM_Null;
  54424. p->type = SQLITE_NULL;
  54425. p->db = db;
  54426. }
  54427. return p;
  54428. }
  54429. /*
  54430. ** Create a new sqlite3_value object, containing the value of pExpr.
  54431. **
  54432. ** This only works for very simple expressions that consist of one constant
  54433. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  54434. ** be converted directly into a value, then the value is allocated and
  54435. ** a pointer written to *ppVal. The caller is responsible for deallocating
  54436. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  54437. ** cannot be converted to a value, then *ppVal is set to NULL.
  54438. */
  54439. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  54440. sqlite3 *db, /* The database connection */
  54441. Expr *pExpr, /* The expression to evaluate */
  54442. u8 enc, /* Encoding to use */
  54443. u8 affinity, /* Affinity to use */
  54444. sqlite3_value **ppVal /* Write the new value here */
  54445. ){
  54446. int op;
  54447. char *zVal = 0;
  54448. sqlite3_value *pVal = 0;
  54449. int negInt = 1;
  54450. const char *zNeg = "";
  54451. if( !pExpr ){
  54452. *ppVal = 0;
  54453. return SQLITE_OK;
  54454. }
  54455. op = pExpr->op;
  54456. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
  54457. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  54458. ** when SQLITE_ENABLE_STAT3 is omitted.
  54459. */
  54460. #ifdef SQLITE_ENABLE_STAT3
  54461. if( op==TK_REGISTER ) op = pExpr->op2;
  54462. #else
  54463. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  54464. #endif
  54465. /* Handle negative integers in a single step. This is needed in the
  54466. ** case when the value is -9223372036854775808.
  54467. */
  54468. if( op==TK_UMINUS
  54469. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  54470. pExpr = pExpr->pLeft;
  54471. op = pExpr->op;
  54472. negInt = -1;
  54473. zNeg = "-";
  54474. }
  54475. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  54476. pVal = sqlite3ValueNew(db);
  54477. if( pVal==0 ) goto no_mem;
  54478. if( ExprHasProperty(pExpr, EP_IntValue) ){
  54479. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  54480. }else{
  54481. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  54482. if( zVal==0 ) goto no_mem;
  54483. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  54484. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  54485. }
  54486. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  54487. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  54488. }else{
  54489. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  54490. }
  54491. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  54492. if( enc!=SQLITE_UTF8 ){
  54493. sqlite3VdbeChangeEncoding(pVal, enc);
  54494. }
  54495. }else if( op==TK_UMINUS ) {
  54496. /* This branch happens for multiple negative signs. Ex: -(-5) */
  54497. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
  54498. sqlite3VdbeMemNumerify(pVal);
  54499. if( pVal->u.i==SMALLEST_INT64 ){
  54500. pVal->flags &= MEM_Int;
  54501. pVal->flags |= MEM_Real;
  54502. pVal->r = (double)LARGEST_INT64;
  54503. }else{
  54504. pVal->u.i = -pVal->u.i;
  54505. }
  54506. pVal->r = -pVal->r;
  54507. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  54508. }
  54509. }else if( op==TK_NULL ){
  54510. pVal = sqlite3ValueNew(db);
  54511. if( pVal==0 ) goto no_mem;
  54512. }
  54513. #ifndef SQLITE_OMIT_BLOB_LITERAL
  54514. else if( op==TK_BLOB ){
  54515. int nVal;
  54516. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  54517. assert( pExpr->u.zToken[1]=='\'' );
  54518. pVal = sqlite3ValueNew(db);
  54519. if( !pVal ) goto no_mem;
  54520. zVal = &pExpr->u.zToken[2];
  54521. nVal = sqlite3Strlen30(zVal)-1;
  54522. assert( zVal[nVal]=='\'' );
  54523. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  54524. 0, SQLITE_DYNAMIC);
  54525. }
  54526. #endif
  54527. if( pVal ){
  54528. sqlite3VdbeMemStoreType(pVal);
  54529. }
  54530. *ppVal = pVal;
  54531. return SQLITE_OK;
  54532. no_mem:
  54533. db->mallocFailed = 1;
  54534. sqlite3DbFree(db, zVal);
  54535. sqlite3ValueFree(pVal);
  54536. *ppVal = 0;
  54537. return SQLITE_NOMEM;
  54538. }
  54539. /*
  54540. ** Change the string value of an sqlite3_value object
  54541. */
  54542. SQLITE_PRIVATE void sqlite3ValueSetStr(
  54543. sqlite3_value *v, /* Value to be set */
  54544. int n, /* Length of string z */
  54545. const void *z, /* Text of the new string */
  54546. u8 enc, /* Encoding to use */
  54547. void (*xDel)(void*) /* Destructor for the string */
  54548. ){
  54549. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  54550. }
  54551. /*
  54552. ** Free an sqlite3_value object
  54553. */
  54554. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  54555. if( !v ) return;
  54556. sqlite3VdbeMemRelease((Mem *)v);
  54557. sqlite3DbFree(((Mem*)v)->db, v);
  54558. }
  54559. /*
  54560. ** Return the number of bytes in the sqlite3_value object assuming
  54561. ** that it uses the encoding "enc"
  54562. */
  54563. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  54564. Mem *p = (Mem*)pVal;
  54565. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  54566. if( p->flags & MEM_Zero ){
  54567. return p->n + p->u.nZero;
  54568. }else{
  54569. return p->n;
  54570. }
  54571. }
  54572. return 0;
  54573. }
  54574. /************** End of vdbemem.c *********************************************/
  54575. /************** Begin file vdbeaux.c *****************************************/
  54576. /*
  54577. ** 2003 September 6
  54578. **
  54579. ** The author disclaims copyright to this source code. In place of
  54580. ** a legal notice, here is a blessing:
  54581. **
  54582. ** May you do good and not evil.
  54583. ** May you find forgiveness for yourself and forgive others.
  54584. ** May you share freely, never taking more than you give.
  54585. **
  54586. *************************************************************************
  54587. ** This file contains code used for creating, destroying, and populating
  54588. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  54589. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  54590. ** But that file was getting too big so this subroutines were split out.
  54591. */
  54592. /*
  54593. ** When debugging the code generator in a symbolic debugger, one can
  54594. ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
  54595. ** as they are added to the instruction stream.
  54596. */
  54597. #ifdef SQLITE_DEBUG
  54598. SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
  54599. #endif
  54600. /*
  54601. ** Create a new virtual database engine.
  54602. */
  54603. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  54604. Vdbe *p;
  54605. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  54606. if( p==0 ) return 0;
  54607. p->db = db;
  54608. if( db->pVdbe ){
  54609. db->pVdbe->pPrev = p;
  54610. }
  54611. p->pNext = db->pVdbe;
  54612. p->pPrev = 0;
  54613. db->pVdbe = p;
  54614. p->magic = VDBE_MAGIC_INIT;
  54615. return p;
  54616. }
  54617. /*
  54618. ** Remember the SQL string for a prepared statement.
  54619. */
  54620. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  54621. assert( isPrepareV2==1 || isPrepareV2==0 );
  54622. if( p==0 ) return;
  54623. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  54624. if( !isPrepareV2 ) return;
  54625. #endif
  54626. assert( p->zSql==0 );
  54627. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  54628. p->isPrepareV2 = (u8)isPrepareV2;
  54629. }
  54630. /*
  54631. ** Return the SQL associated with a prepared statement
  54632. */
  54633. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  54634. Vdbe *p = (Vdbe *)pStmt;
  54635. return (p && p->isPrepareV2) ? p->zSql : 0;
  54636. }
  54637. /*
  54638. ** Swap all content between two VDBE structures.
  54639. */
  54640. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  54641. Vdbe tmp, *pTmp;
  54642. char *zTmp;
  54643. tmp = *pA;
  54644. *pA = *pB;
  54645. *pB = tmp;
  54646. pTmp = pA->pNext;
  54647. pA->pNext = pB->pNext;
  54648. pB->pNext = pTmp;
  54649. pTmp = pA->pPrev;
  54650. pA->pPrev = pB->pPrev;
  54651. pB->pPrev = pTmp;
  54652. zTmp = pA->zSql;
  54653. pA->zSql = pB->zSql;
  54654. pB->zSql = zTmp;
  54655. pB->isPrepareV2 = pA->isPrepareV2;
  54656. }
  54657. #ifdef SQLITE_DEBUG
  54658. /*
  54659. ** Turn tracing on or off
  54660. */
  54661. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  54662. p->trace = trace;
  54663. }
  54664. #endif
  54665. /*
  54666. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  54667. ** it was.
  54668. **
  54669. ** If an out-of-memory error occurs while resizing the array, return
  54670. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  54671. ** unchanged (this is so that any opcodes already allocated can be
  54672. ** correctly deallocated along with the rest of the Vdbe).
  54673. */
  54674. static int growOpArray(Vdbe *p){
  54675. VdbeOp *pNew;
  54676. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  54677. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  54678. if( pNew ){
  54679. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  54680. p->aOp = pNew;
  54681. }
  54682. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  54683. }
  54684. /*
  54685. ** Add a new instruction to the list of instructions current in the
  54686. ** VDBE. Return the address of the new instruction.
  54687. **
  54688. ** Parameters:
  54689. **
  54690. ** p Pointer to the VDBE
  54691. **
  54692. ** op The opcode for this instruction
  54693. **
  54694. ** p1, p2, p3 Operands
  54695. **
  54696. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  54697. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  54698. ** operand.
  54699. */
  54700. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  54701. int i;
  54702. VdbeOp *pOp;
  54703. i = p->nOp;
  54704. assert( p->magic==VDBE_MAGIC_INIT );
  54705. assert( op>0 && op<0xff );
  54706. if( p->nOpAlloc<=i ){
  54707. if( growOpArray(p) ){
  54708. return 1;
  54709. }
  54710. }
  54711. p->nOp++;
  54712. pOp = &p->aOp[i];
  54713. pOp->opcode = (u8)op;
  54714. pOp->p5 = 0;
  54715. pOp->p1 = p1;
  54716. pOp->p2 = p2;
  54717. pOp->p3 = p3;
  54718. pOp->p4.p = 0;
  54719. pOp->p4type = P4_NOTUSED;
  54720. #ifdef SQLITE_DEBUG
  54721. pOp->zComment = 0;
  54722. if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  54723. #endif
  54724. #ifdef VDBE_PROFILE
  54725. pOp->cycles = 0;
  54726. pOp->cnt = 0;
  54727. #endif
  54728. return i;
  54729. }
  54730. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  54731. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  54732. }
  54733. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  54734. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  54735. }
  54736. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  54737. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  54738. }
  54739. /*
  54740. ** Add an opcode that includes the p4 value as a pointer.
  54741. */
  54742. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  54743. Vdbe *p, /* Add the opcode to this VM */
  54744. int op, /* The new opcode */
  54745. int p1, /* The P1 operand */
  54746. int p2, /* The P2 operand */
  54747. int p3, /* The P3 operand */
  54748. const char *zP4, /* The P4 operand */
  54749. int p4type /* P4 operand type */
  54750. ){
  54751. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  54752. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  54753. return addr;
  54754. }
  54755. /*
  54756. ** Add an OP_ParseSchema opcode. This routine is broken out from
  54757. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  54758. ** as having been used.
  54759. **
  54760. ** The zWhere string must have been obtained from sqlite3_malloc().
  54761. ** This routine will take ownership of the allocated memory.
  54762. */
  54763. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  54764. int j;
  54765. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  54766. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  54767. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  54768. }
  54769. /*
  54770. ** Add an opcode that includes the p4 value as an integer.
  54771. */
  54772. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  54773. Vdbe *p, /* Add the opcode to this VM */
  54774. int op, /* The new opcode */
  54775. int p1, /* The P1 operand */
  54776. int p2, /* The P2 operand */
  54777. int p3, /* The P3 operand */
  54778. int p4 /* The P4 operand as an integer */
  54779. ){
  54780. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  54781. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  54782. return addr;
  54783. }
  54784. /*
  54785. ** Create a new symbolic label for an instruction that has yet to be
  54786. ** coded. The symbolic label is really just a negative number. The
  54787. ** label can be used as the P2 value of an operation. Later, when
  54788. ** the label is resolved to a specific address, the VDBE will scan
  54789. ** through its operation list and change all values of P2 which match
  54790. ** the label into the resolved address.
  54791. **
  54792. ** The VDBE knows that a P2 value is a label because labels are
  54793. ** always negative and P2 values are suppose to be non-negative.
  54794. ** Hence, a negative P2 value is a label that has yet to be resolved.
  54795. **
  54796. ** Zero is returned if a malloc() fails.
  54797. */
  54798. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  54799. int i = p->nLabel++;
  54800. assert( p->magic==VDBE_MAGIC_INIT );
  54801. if( (i & (i-1))==0 ){
  54802. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  54803. (i*2+1)*sizeof(p->aLabel[0]));
  54804. }
  54805. if( p->aLabel ){
  54806. p->aLabel[i] = -1;
  54807. }
  54808. return -1-i;
  54809. }
  54810. /*
  54811. ** Resolve label "x" to be the address of the next instruction to
  54812. ** be inserted. The parameter "x" must have been obtained from
  54813. ** a prior call to sqlite3VdbeMakeLabel().
  54814. */
  54815. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  54816. int j = -1-x;
  54817. assert( p->magic==VDBE_MAGIC_INIT );
  54818. assert( j>=0 && j<p->nLabel );
  54819. if( p->aLabel ){
  54820. p->aLabel[j] = p->nOp;
  54821. }
  54822. }
  54823. /*
  54824. ** Mark the VDBE as one that can only be run one time.
  54825. */
  54826. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  54827. p->runOnlyOnce = 1;
  54828. }
  54829. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  54830. /*
  54831. ** The following type and function are used to iterate through all opcodes
  54832. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  54833. ** invoke directly or indirectly. It should be used as follows:
  54834. **
  54835. ** Op *pOp;
  54836. ** VdbeOpIter sIter;
  54837. **
  54838. ** memset(&sIter, 0, sizeof(sIter));
  54839. ** sIter.v = v; // v is of type Vdbe*
  54840. ** while( (pOp = opIterNext(&sIter)) ){
  54841. ** // Do something with pOp
  54842. ** }
  54843. ** sqlite3DbFree(v->db, sIter.apSub);
  54844. **
  54845. */
  54846. typedef struct VdbeOpIter VdbeOpIter;
  54847. struct VdbeOpIter {
  54848. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  54849. SubProgram **apSub; /* Array of subprograms */
  54850. int nSub; /* Number of entries in apSub */
  54851. int iAddr; /* Address of next instruction to return */
  54852. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  54853. };
  54854. static Op *opIterNext(VdbeOpIter *p){
  54855. Vdbe *v = p->v;
  54856. Op *pRet = 0;
  54857. Op *aOp;
  54858. int nOp;
  54859. if( p->iSub<=p->nSub ){
  54860. if( p->iSub==0 ){
  54861. aOp = v->aOp;
  54862. nOp = v->nOp;
  54863. }else{
  54864. aOp = p->apSub[p->iSub-1]->aOp;
  54865. nOp = p->apSub[p->iSub-1]->nOp;
  54866. }
  54867. assert( p->iAddr<nOp );
  54868. pRet = &aOp[p->iAddr];
  54869. p->iAddr++;
  54870. if( p->iAddr==nOp ){
  54871. p->iSub++;
  54872. p->iAddr = 0;
  54873. }
  54874. if( pRet->p4type==P4_SUBPROGRAM ){
  54875. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  54876. int j;
  54877. for(j=0; j<p->nSub; j++){
  54878. if( p->apSub[j]==pRet->p4.pProgram ) break;
  54879. }
  54880. if( j==p->nSub ){
  54881. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  54882. if( !p->apSub ){
  54883. pRet = 0;
  54884. }else{
  54885. p->apSub[p->nSub++] = pRet->p4.pProgram;
  54886. }
  54887. }
  54888. }
  54889. }
  54890. return pRet;
  54891. }
  54892. /*
  54893. ** Check if the program stored in the VM associated with pParse may
  54894. ** throw an ABORT exception (causing the statement, but not entire transaction
  54895. ** to be rolled back). This condition is true if the main program or any
  54896. ** sub-programs contains any of the following:
  54897. **
  54898. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  54899. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  54900. ** * OP_Destroy
  54901. ** * OP_VUpdate
  54902. ** * OP_VRename
  54903. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  54904. **
  54905. ** Then check that the value of Parse.mayAbort is true if an
  54906. ** ABORT may be thrown, or false otherwise. Return true if it does
  54907. ** match, or false otherwise. This function is intended to be used as
  54908. ** part of an assert statement in the compiler. Similar to:
  54909. **
  54910. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  54911. */
  54912. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  54913. int hasAbort = 0;
  54914. Op *pOp;
  54915. VdbeOpIter sIter;
  54916. memset(&sIter, 0, sizeof(sIter));
  54917. sIter.v = v;
  54918. while( (pOp = opIterNext(&sIter))!=0 ){
  54919. int opcode = pOp->opcode;
  54920. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  54921. #ifndef SQLITE_OMIT_FOREIGN_KEY
  54922. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  54923. #endif
  54924. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  54925. && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  54926. ){
  54927. hasAbort = 1;
  54928. break;
  54929. }
  54930. }
  54931. sqlite3DbFree(v->db, sIter.apSub);
  54932. /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
  54933. ** If malloc failed, then the while() loop above may not have iterated
  54934. ** through all opcodes and hasAbort may be set incorrectly. Return
  54935. ** true for this case to prevent the assert() in the callers frame
  54936. ** from failing. */
  54937. return ( v->db->mallocFailed || hasAbort==mayAbort );
  54938. }
  54939. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  54940. /*
  54941. ** Loop through the program looking for P2 values that are negative
  54942. ** on jump instructions. Each such value is a label. Resolve the
  54943. ** label by setting the P2 value to its correct non-zero value.
  54944. **
  54945. ** This routine is called once after all opcodes have been inserted.
  54946. **
  54947. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  54948. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  54949. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  54950. **
  54951. ** The Op.opflags field is set on all opcodes.
  54952. */
  54953. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  54954. int i;
  54955. int nMaxArgs = *pMaxFuncArgs;
  54956. Op *pOp;
  54957. int *aLabel = p->aLabel;
  54958. p->readOnly = 1;
  54959. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  54960. u8 opcode = pOp->opcode;
  54961. pOp->opflags = sqlite3OpcodeProperty[opcode];
  54962. if( opcode==OP_Function || opcode==OP_AggStep ){
  54963. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  54964. }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
  54965. p->readOnly = 0;
  54966. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54967. }else if( opcode==OP_VUpdate ){
  54968. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  54969. }else if( opcode==OP_VFilter ){
  54970. int n;
  54971. assert( p->nOp - i >= 3 );
  54972. assert( pOp[-1].opcode==OP_Integer );
  54973. n = pOp[-1].p1;
  54974. if( n>nMaxArgs ) nMaxArgs = n;
  54975. #endif
  54976. }else if( opcode==OP_Next || opcode==OP_SorterNext ){
  54977. pOp->p4.xAdvance = sqlite3BtreeNext;
  54978. pOp->p4type = P4_ADVANCE;
  54979. }else if( opcode==OP_Prev ){
  54980. pOp->p4.xAdvance = sqlite3BtreePrevious;
  54981. pOp->p4type = P4_ADVANCE;
  54982. }
  54983. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  54984. assert( -1-pOp->p2<p->nLabel );
  54985. pOp->p2 = aLabel[-1-pOp->p2];
  54986. }
  54987. }
  54988. sqlite3DbFree(p->db, p->aLabel);
  54989. p->aLabel = 0;
  54990. *pMaxFuncArgs = nMaxArgs;
  54991. }
  54992. /*
  54993. ** Return the address of the next instruction to be inserted.
  54994. */
  54995. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  54996. assert( p->magic==VDBE_MAGIC_INIT );
  54997. return p->nOp;
  54998. }
  54999. /*
  55000. ** This function returns a pointer to the array of opcodes associated with
  55001. ** the Vdbe passed as the first argument. It is the callers responsibility
  55002. ** to arrange for the returned array to be eventually freed using the
  55003. ** vdbeFreeOpArray() function.
  55004. **
  55005. ** Before returning, *pnOp is set to the number of entries in the returned
  55006. ** array. Also, *pnMaxArg is set to the larger of its current value and
  55007. ** the number of entries in the Vdbe.apArg[] array required to execute the
  55008. ** returned program.
  55009. */
  55010. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  55011. VdbeOp *aOp = p->aOp;
  55012. assert( aOp && !p->db->mallocFailed );
  55013. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  55014. assert( p->btreeMask==0 );
  55015. resolveP2Values(p, pnMaxArg);
  55016. *pnOp = p->nOp;
  55017. p->aOp = 0;
  55018. return aOp;
  55019. }
  55020. /*
  55021. ** Add a whole list of operations to the operation stack. Return the
  55022. ** address of the first operation added.
  55023. */
  55024. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  55025. int addr;
  55026. assert( p->magic==VDBE_MAGIC_INIT );
  55027. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  55028. return 0;
  55029. }
  55030. addr = p->nOp;
  55031. if( ALWAYS(nOp>0) ){
  55032. int i;
  55033. VdbeOpList const *pIn = aOp;
  55034. for(i=0; i<nOp; i++, pIn++){
  55035. int p2 = pIn->p2;
  55036. VdbeOp *pOut = &p->aOp[i+addr];
  55037. pOut->opcode = pIn->opcode;
  55038. pOut->p1 = pIn->p1;
  55039. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  55040. pOut->p2 = addr + ADDR(p2);
  55041. }else{
  55042. pOut->p2 = p2;
  55043. }
  55044. pOut->p3 = pIn->p3;
  55045. pOut->p4type = P4_NOTUSED;
  55046. pOut->p4.p = 0;
  55047. pOut->p5 = 0;
  55048. #ifdef SQLITE_DEBUG
  55049. pOut->zComment = 0;
  55050. if( sqlite3VdbeAddopTrace ){
  55051. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  55052. }
  55053. #endif
  55054. }
  55055. p->nOp += nOp;
  55056. }
  55057. return addr;
  55058. }
  55059. /*
  55060. ** Change the value of the P1 operand for a specific instruction.
  55061. ** This routine is useful when a large program is loaded from a
  55062. ** static array using sqlite3VdbeAddOpList but we want to make a
  55063. ** few minor changes to the program.
  55064. */
  55065. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  55066. assert( p!=0 );
  55067. if( ((u32)p->nOp)>addr ){
  55068. p->aOp[addr].p1 = val;
  55069. }
  55070. }
  55071. /*
  55072. ** Change the value of the P2 operand for a specific instruction.
  55073. ** This routine is useful for setting a jump destination.
  55074. */
  55075. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  55076. assert( p!=0 );
  55077. if( ((u32)p->nOp)>addr ){
  55078. p->aOp[addr].p2 = val;
  55079. }
  55080. }
  55081. /*
  55082. ** Change the value of the P3 operand for a specific instruction.
  55083. */
  55084. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  55085. assert( p!=0 );
  55086. if( ((u32)p->nOp)>addr ){
  55087. p->aOp[addr].p3 = val;
  55088. }
  55089. }
  55090. /*
  55091. ** Change the value of the P5 operand for the most recently
  55092. ** added operation.
  55093. */
  55094. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  55095. assert( p!=0 );
  55096. if( p->aOp ){
  55097. assert( p->nOp>0 );
  55098. p->aOp[p->nOp-1].p5 = val;
  55099. }
  55100. }
  55101. /*
  55102. ** Change the P2 operand of instruction addr so that it points to
  55103. ** the address of the next instruction to be coded.
  55104. */
  55105. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  55106. assert( addr>=0 || p->db->mallocFailed );
  55107. if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  55108. }
  55109. /*
  55110. ** If the input FuncDef structure is ephemeral, then free it. If
  55111. ** the FuncDef is not ephermal, then do nothing.
  55112. */
  55113. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  55114. if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
  55115. sqlite3DbFree(db, pDef);
  55116. }
  55117. }
  55118. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  55119. /*
  55120. ** Delete a P4 value if necessary.
  55121. */
  55122. static void freeP4(sqlite3 *db, int p4type, void *p4){
  55123. if( p4 ){
  55124. assert( db );
  55125. switch( p4type ){
  55126. case P4_REAL:
  55127. case P4_INT64:
  55128. case P4_DYNAMIC:
  55129. case P4_KEYINFO:
  55130. case P4_INTARRAY:
  55131. case P4_KEYINFO_HANDOFF: {
  55132. sqlite3DbFree(db, p4);
  55133. break;
  55134. }
  55135. case P4_MPRINTF: {
  55136. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  55137. break;
  55138. }
  55139. case P4_VDBEFUNC: {
  55140. VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
  55141. freeEphemeralFunction(db, pVdbeFunc->pFunc);
  55142. if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
  55143. sqlite3DbFree(db, pVdbeFunc);
  55144. break;
  55145. }
  55146. case P4_FUNCDEF: {
  55147. freeEphemeralFunction(db, (FuncDef*)p4);
  55148. break;
  55149. }
  55150. case P4_MEM: {
  55151. if( db->pnBytesFreed==0 ){
  55152. sqlite3ValueFree((sqlite3_value*)p4);
  55153. }else{
  55154. Mem *p = (Mem*)p4;
  55155. sqlite3DbFree(db, p->zMalloc);
  55156. sqlite3DbFree(db, p);
  55157. }
  55158. break;
  55159. }
  55160. case P4_VTAB : {
  55161. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  55162. break;
  55163. }
  55164. }
  55165. }
  55166. }
  55167. /*
  55168. ** Free the space allocated for aOp and any p4 values allocated for the
  55169. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  55170. ** nOp entries.
  55171. */
  55172. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  55173. if( aOp ){
  55174. Op *pOp;
  55175. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  55176. freeP4(db, pOp->p4type, pOp->p4.p);
  55177. #ifdef SQLITE_DEBUG
  55178. sqlite3DbFree(db, pOp->zComment);
  55179. #endif
  55180. }
  55181. }
  55182. sqlite3DbFree(db, aOp);
  55183. }
  55184. /*
  55185. ** Link the SubProgram object passed as the second argument into the linked
  55186. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  55187. ** objects when the VM is no longer required.
  55188. */
  55189. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  55190. p->pNext = pVdbe->pProgram;
  55191. pVdbe->pProgram = p;
  55192. }
  55193. /*
  55194. ** Change the opcode at addr into OP_Noop
  55195. */
  55196. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  55197. if( p->aOp ){
  55198. VdbeOp *pOp = &p->aOp[addr];
  55199. sqlite3 *db = p->db;
  55200. freeP4(db, pOp->p4type, pOp->p4.p);
  55201. memset(pOp, 0, sizeof(pOp[0]));
  55202. pOp->opcode = OP_Noop;
  55203. }
  55204. }
  55205. /*
  55206. ** Change the value of the P4 operand for a specific instruction.
  55207. ** This routine is useful when a large program is loaded from a
  55208. ** static array using sqlite3VdbeAddOpList but we want to make a
  55209. ** few minor changes to the program.
  55210. **
  55211. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  55212. ** the string is made into memory obtained from sqlite3_malloc().
  55213. ** A value of n==0 means copy bytes of zP4 up to and including the
  55214. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  55215. **
  55216. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  55217. ** A copy is made of the KeyInfo structure into memory obtained from
  55218. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  55219. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  55220. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  55221. ** caller should not free the allocation, it will be freed when the Vdbe is
  55222. ** finalized.
  55223. **
  55224. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  55225. ** to a string or structure that is guaranteed to exist for the lifetime of
  55226. ** the Vdbe. In these cases we can just copy the pointer.
  55227. **
  55228. ** If addr<0 then change P4 on the most recently inserted instruction.
  55229. */
  55230. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  55231. Op *pOp;
  55232. sqlite3 *db;
  55233. assert( p!=0 );
  55234. db = p->db;
  55235. assert( p->magic==VDBE_MAGIC_INIT );
  55236. if( p->aOp==0 || db->mallocFailed ){
  55237. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  55238. freeP4(db, n, (void*)*(char**)&zP4);
  55239. }
  55240. return;
  55241. }
  55242. assert( p->nOp>0 );
  55243. assert( addr<p->nOp );
  55244. if( addr<0 ){
  55245. addr = p->nOp - 1;
  55246. }
  55247. pOp = &p->aOp[addr];
  55248. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  55249. freeP4(db, pOp->p4type, pOp->p4.p);
  55250. pOp->p4.p = 0;
  55251. if( n==P4_INT32 ){
  55252. /* Note: this cast is safe, because the origin data point was an int
  55253. ** that was cast to a (const char *). */
  55254. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  55255. pOp->p4type = P4_INT32;
  55256. }else if( zP4==0 ){
  55257. pOp->p4.p = 0;
  55258. pOp->p4type = P4_NOTUSED;
  55259. }else if( n==P4_KEYINFO ){
  55260. KeyInfo *pKeyInfo;
  55261. int nField, nByte;
  55262. nField = ((KeyInfo*)zP4)->nField;
  55263. nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
  55264. pKeyInfo = sqlite3DbMallocRaw(0, nByte);
  55265. pOp->p4.pKeyInfo = pKeyInfo;
  55266. if( pKeyInfo ){
  55267. u8 *aSortOrder;
  55268. memcpy((char*)pKeyInfo, zP4, nByte - nField);
  55269. aSortOrder = pKeyInfo->aSortOrder;
  55270. assert( aSortOrder!=0 );
  55271. pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
  55272. memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
  55273. pOp->p4type = P4_KEYINFO;
  55274. }else{
  55275. p->db->mallocFailed = 1;
  55276. pOp->p4type = P4_NOTUSED;
  55277. }
  55278. }else if( n==P4_KEYINFO_HANDOFF ){
  55279. pOp->p4.p = (void*)zP4;
  55280. pOp->p4type = P4_KEYINFO;
  55281. }else if( n==P4_VTAB ){
  55282. pOp->p4.p = (void*)zP4;
  55283. pOp->p4type = P4_VTAB;
  55284. sqlite3VtabLock((VTable *)zP4);
  55285. assert( ((VTable *)zP4)->db==p->db );
  55286. }else if( n<0 ){
  55287. pOp->p4.p = (void*)zP4;
  55288. pOp->p4type = (signed char)n;
  55289. }else{
  55290. if( n==0 ) n = sqlite3Strlen30(zP4);
  55291. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  55292. pOp->p4type = P4_DYNAMIC;
  55293. }
  55294. }
  55295. #ifndef NDEBUG
  55296. /*
  55297. ** Change the comment on the most recently coded instruction. Or
  55298. ** insert a No-op and add the comment to that new instruction. This
  55299. ** makes the code easier to read during debugging. None of this happens
  55300. ** in a production build.
  55301. */
  55302. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  55303. assert( p->nOp>0 || p->aOp==0 );
  55304. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  55305. if( p->nOp ){
  55306. assert( p->aOp );
  55307. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  55308. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  55309. }
  55310. }
  55311. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  55312. va_list ap;
  55313. if( p ){
  55314. va_start(ap, zFormat);
  55315. vdbeVComment(p, zFormat, ap);
  55316. va_end(ap);
  55317. }
  55318. }
  55319. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  55320. va_list ap;
  55321. if( p ){
  55322. sqlite3VdbeAddOp0(p, OP_Noop);
  55323. va_start(ap, zFormat);
  55324. vdbeVComment(p, zFormat, ap);
  55325. va_end(ap);
  55326. }
  55327. }
  55328. #endif /* NDEBUG */
  55329. /*
  55330. ** Return the opcode for a given address. If the address is -1, then
  55331. ** return the most recently inserted opcode.
  55332. **
  55333. ** If a memory allocation error has occurred prior to the calling of this
  55334. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  55335. ** is readable but not writable, though it is cast to a writable value.
  55336. ** The return of a dummy opcode allows the call to continue functioning
  55337. ** after a OOM fault without having to check to see if the return from
  55338. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  55339. ** dummy will never be written to. This is verified by code inspection and
  55340. ** by running with Valgrind.
  55341. **
  55342. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  55343. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  55344. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  55345. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  55346. ** having to double-check to make sure that the result is non-negative. But
  55347. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  55348. ** check the value of p->nOp-1 before continuing.
  55349. */
  55350. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  55351. /* C89 specifies that the constant "dummy" will be initialized to all
  55352. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  55353. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  55354. assert( p->magic==VDBE_MAGIC_INIT );
  55355. if( addr<0 ){
  55356. #ifdef SQLITE_OMIT_TRACE
  55357. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  55358. #endif
  55359. addr = p->nOp - 1;
  55360. }
  55361. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  55362. if( p->db->mallocFailed ){
  55363. return (VdbeOp*)&dummy;
  55364. }else{
  55365. return &p->aOp[addr];
  55366. }
  55367. }
  55368. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  55369. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  55370. /*
  55371. ** Compute a string that describes the P4 parameter for an opcode.
  55372. ** Use zTemp for any required temporary buffer space.
  55373. */
  55374. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  55375. char *zP4 = zTemp;
  55376. assert( nTemp>=20 );
  55377. switch( pOp->p4type ){
  55378. case P4_KEYINFO_STATIC:
  55379. case P4_KEYINFO: {
  55380. int i, j;
  55381. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  55382. assert( pKeyInfo->aSortOrder!=0 );
  55383. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  55384. i = sqlite3Strlen30(zTemp);
  55385. for(j=0; j<pKeyInfo->nField; j++){
  55386. CollSeq *pColl = pKeyInfo->aColl[j];
  55387. const char *zColl = pColl ? pColl->zName : "nil";
  55388. int n = sqlite3Strlen30(zColl);
  55389. if( i+n>nTemp-6 ){
  55390. memcpy(&zTemp[i],",...",4);
  55391. break;
  55392. }
  55393. zTemp[i++] = ',';
  55394. if( pKeyInfo->aSortOrder[j] ){
  55395. zTemp[i++] = '-';
  55396. }
  55397. memcpy(&zTemp[i], zColl, n+1);
  55398. i += n;
  55399. }
  55400. zTemp[i++] = ')';
  55401. zTemp[i] = 0;
  55402. assert( i<nTemp );
  55403. break;
  55404. }
  55405. case P4_COLLSEQ: {
  55406. CollSeq *pColl = pOp->p4.pColl;
  55407. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  55408. break;
  55409. }
  55410. case P4_FUNCDEF: {
  55411. FuncDef *pDef = pOp->p4.pFunc;
  55412. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  55413. break;
  55414. }
  55415. case P4_INT64: {
  55416. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  55417. break;
  55418. }
  55419. case P4_INT32: {
  55420. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  55421. break;
  55422. }
  55423. case P4_REAL: {
  55424. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  55425. break;
  55426. }
  55427. case P4_MEM: {
  55428. Mem *pMem = pOp->p4.pMem;
  55429. if( pMem->flags & MEM_Str ){
  55430. zP4 = pMem->z;
  55431. }else if( pMem->flags & MEM_Int ){
  55432. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  55433. }else if( pMem->flags & MEM_Real ){
  55434. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  55435. }else if( pMem->flags & MEM_Null ){
  55436. sqlite3_snprintf(nTemp, zTemp, "NULL");
  55437. }else{
  55438. assert( pMem->flags & MEM_Blob );
  55439. zP4 = "(blob)";
  55440. }
  55441. break;
  55442. }
  55443. #ifndef SQLITE_OMIT_VIRTUALTABLE
  55444. case P4_VTAB: {
  55445. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  55446. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  55447. break;
  55448. }
  55449. #endif
  55450. case P4_INTARRAY: {
  55451. sqlite3_snprintf(nTemp, zTemp, "intarray");
  55452. break;
  55453. }
  55454. case P4_SUBPROGRAM: {
  55455. sqlite3_snprintf(nTemp, zTemp, "program");
  55456. break;
  55457. }
  55458. case P4_ADVANCE: {
  55459. zTemp[0] = 0;
  55460. break;
  55461. }
  55462. default: {
  55463. zP4 = pOp->p4.z;
  55464. if( zP4==0 ){
  55465. zP4 = zTemp;
  55466. zTemp[0] = 0;
  55467. }
  55468. }
  55469. }
  55470. assert( zP4!=0 );
  55471. return zP4;
  55472. }
  55473. #endif
  55474. /*
  55475. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  55476. **
  55477. ** The prepared statements need to know in advance the complete set of
  55478. ** attached databases that will be use. A mask of these databases
  55479. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  55480. ** p->btreeMask of databases that will require a lock.
  55481. */
  55482. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  55483. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  55484. assert( i<(int)sizeof(p->btreeMask)*8 );
  55485. p->btreeMask |= ((yDbMask)1)<<i;
  55486. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  55487. p->lockMask |= ((yDbMask)1)<<i;
  55488. }
  55489. }
  55490. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  55491. /*
  55492. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  55493. ** this routine obtains the mutex associated with each BtShared structure
  55494. ** that may be accessed by the VM passed as an argument. In doing so it also
  55495. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  55496. ** that the correct busy-handler callback is invoked if required.
  55497. **
  55498. ** If SQLite is not threadsafe but does support shared-cache mode, then
  55499. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  55500. ** of all of BtShared structures accessible via the database handle
  55501. ** associated with the VM.
  55502. **
  55503. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  55504. ** function is a no-op.
  55505. **
  55506. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  55507. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  55508. ** corresponding to btrees that use shared cache. Then the runtime of
  55509. ** this routine is N*N. But as N is rarely more than 1, this should not
  55510. ** be a problem.
  55511. */
  55512. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  55513. int i;
  55514. yDbMask mask;
  55515. sqlite3 *db;
  55516. Db *aDb;
  55517. int nDb;
  55518. if( p->lockMask==0 ) return; /* The common case */
  55519. db = p->db;
  55520. aDb = db->aDb;
  55521. nDb = db->nDb;
  55522. for(i=0, mask=1; i<nDb; i++, mask += mask){
  55523. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  55524. sqlite3BtreeEnter(aDb[i].pBt);
  55525. }
  55526. }
  55527. }
  55528. #endif
  55529. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  55530. /*
  55531. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  55532. */
  55533. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  55534. int i;
  55535. yDbMask mask;
  55536. sqlite3 *db;
  55537. Db *aDb;
  55538. int nDb;
  55539. if( p->lockMask==0 ) return; /* The common case */
  55540. db = p->db;
  55541. aDb = db->aDb;
  55542. nDb = db->nDb;
  55543. for(i=0, mask=1; i<nDb; i++, mask += mask){
  55544. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  55545. sqlite3BtreeLeave(aDb[i].pBt);
  55546. }
  55547. }
  55548. }
  55549. #endif
  55550. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  55551. /*
  55552. ** Print a single opcode. This routine is used for debugging only.
  55553. */
  55554. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  55555. char *zP4;
  55556. char zPtr[50];
  55557. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  55558. if( pOut==0 ) pOut = stdout;
  55559. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  55560. fprintf(pOut, zFormat1, pc,
  55561. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  55562. #ifdef SQLITE_DEBUG
  55563. pOp->zComment ? pOp->zComment : ""
  55564. #else
  55565. ""
  55566. #endif
  55567. );
  55568. fflush(pOut);
  55569. }
  55570. #endif
  55571. /*
  55572. ** Release an array of N Mem elements
  55573. */
  55574. static void releaseMemArray(Mem *p, int N){
  55575. if( p && N ){
  55576. Mem *pEnd;
  55577. sqlite3 *db = p->db;
  55578. u8 malloc_failed = db->mallocFailed;
  55579. if( db->pnBytesFreed ){
  55580. for(pEnd=&p[N]; p<pEnd; p++){
  55581. sqlite3DbFree(db, p->zMalloc);
  55582. }
  55583. return;
  55584. }
  55585. for(pEnd=&p[N]; p<pEnd; p++){
  55586. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  55587. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  55588. ** that takes advantage of the fact that the memory cell value is
  55589. ** being set to NULL after releasing any dynamic resources.
  55590. **
  55591. ** The justification for duplicating code is that according to
  55592. ** callgrind, this causes a certain test case to hit the CPU 4.7
  55593. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  55594. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  55595. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  55596. ** with no indexes using a single prepared INSERT statement, bind()
  55597. ** and reset(). Inserts are grouped into a transaction.
  55598. */
  55599. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  55600. sqlite3VdbeMemRelease(p);
  55601. }else if( p->zMalloc ){
  55602. sqlite3DbFree(db, p->zMalloc);
  55603. p->zMalloc = 0;
  55604. }
  55605. p->flags = MEM_Invalid;
  55606. }
  55607. db->mallocFailed = malloc_failed;
  55608. }
  55609. }
  55610. /*
  55611. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  55612. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  55613. */
  55614. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  55615. int i;
  55616. Mem *aMem = VdbeFrameMem(p);
  55617. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  55618. for(i=0; i<p->nChildCsr; i++){
  55619. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  55620. }
  55621. releaseMemArray(aMem, p->nChildMem);
  55622. sqlite3DbFree(p->v->db, p);
  55623. }
  55624. #ifndef SQLITE_OMIT_EXPLAIN
  55625. /*
  55626. ** Give a listing of the program in the virtual machine.
  55627. **
  55628. ** The interface is the same as sqlite3VdbeExec(). But instead of
  55629. ** running the code, it invokes the callback once for each instruction.
  55630. ** This feature is used to implement "EXPLAIN".
  55631. **
  55632. ** When p->explain==1, each instruction is listed. When
  55633. ** p->explain==2, only OP_Explain instructions are listed and these
  55634. ** are shown in a different format. p->explain==2 is used to implement
  55635. ** EXPLAIN QUERY PLAN.
  55636. **
  55637. ** When p->explain==1, first the main program is listed, then each of
  55638. ** the trigger subprograms are listed one by one.
  55639. */
  55640. SQLITE_PRIVATE int sqlite3VdbeList(
  55641. Vdbe *p /* The VDBE */
  55642. ){
  55643. int nRow; /* Stop when row count reaches this */
  55644. int nSub = 0; /* Number of sub-vdbes seen so far */
  55645. SubProgram **apSub = 0; /* Array of sub-vdbes */
  55646. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  55647. sqlite3 *db = p->db; /* The database connection */
  55648. int i; /* Loop counter */
  55649. int rc = SQLITE_OK; /* Return code */
  55650. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  55651. assert( p->explain );
  55652. assert( p->magic==VDBE_MAGIC_RUN );
  55653. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  55654. /* Even though this opcode does not use dynamic strings for
  55655. ** the result, result columns may become dynamic if the user calls
  55656. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  55657. */
  55658. releaseMemArray(pMem, 8);
  55659. p->pResultSet = 0;
  55660. if( p->rc==SQLITE_NOMEM ){
  55661. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  55662. ** sqlite3_column_text16() failed. */
  55663. db->mallocFailed = 1;
  55664. return SQLITE_ERROR;
  55665. }
  55666. /* When the number of output rows reaches nRow, that means the
  55667. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  55668. ** nRow is the sum of the number of rows in the main program, plus
  55669. ** the sum of the number of rows in all trigger subprograms encountered
  55670. ** so far. The nRow value will increase as new trigger subprograms are
  55671. ** encountered, but p->pc will eventually catch up to nRow.
  55672. */
  55673. nRow = p->nOp;
  55674. if( p->explain==1 ){
  55675. /* The first 8 memory cells are used for the result set. So we will
  55676. ** commandeer the 9th cell to use as storage for an array of pointers
  55677. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  55678. ** cells. */
  55679. assert( p->nMem>9 );
  55680. pSub = &p->aMem[9];
  55681. if( pSub->flags&MEM_Blob ){
  55682. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  55683. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  55684. nSub = pSub->n/sizeof(Vdbe*);
  55685. apSub = (SubProgram **)pSub->z;
  55686. }
  55687. for(i=0; i<nSub; i++){
  55688. nRow += apSub[i]->nOp;
  55689. }
  55690. }
  55691. do{
  55692. i = p->pc++;
  55693. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  55694. if( i>=nRow ){
  55695. p->rc = SQLITE_OK;
  55696. rc = SQLITE_DONE;
  55697. }else if( db->u1.isInterrupted ){
  55698. p->rc = SQLITE_INTERRUPT;
  55699. rc = SQLITE_ERROR;
  55700. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  55701. }else{
  55702. char *z;
  55703. Op *pOp;
  55704. if( i<p->nOp ){
  55705. /* The output line number is small enough that we are still in the
  55706. ** main program. */
  55707. pOp = &p->aOp[i];
  55708. }else{
  55709. /* We are currently listing subprograms. Figure out which one and
  55710. ** pick up the appropriate opcode. */
  55711. int j;
  55712. i -= p->nOp;
  55713. for(j=0; i>=apSub[j]->nOp; j++){
  55714. i -= apSub[j]->nOp;
  55715. }
  55716. pOp = &apSub[j]->aOp[i];
  55717. }
  55718. if( p->explain==1 ){
  55719. pMem->flags = MEM_Int;
  55720. pMem->type = SQLITE_INTEGER;
  55721. pMem->u.i = i; /* Program counter */
  55722. pMem++;
  55723. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  55724. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  55725. assert( pMem->z!=0 );
  55726. pMem->n = sqlite3Strlen30(pMem->z);
  55727. pMem->type = SQLITE_TEXT;
  55728. pMem->enc = SQLITE_UTF8;
  55729. pMem++;
  55730. /* When an OP_Program opcode is encounter (the only opcode that has
  55731. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  55732. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  55733. ** has not already been seen.
  55734. */
  55735. if( pOp->p4type==P4_SUBPROGRAM ){
  55736. int nByte = (nSub+1)*sizeof(SubProgram*);
  55737. int j;
  55738. for(j=0; j<nSub; j++){
  55739. if( apSub[j]==pOp->p4.pProgram ) break;
  55740. }
  55741. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  55742. apSub = (SubProgram **)pSub->z;
  55743. apSub[nSub++] = pOp->p4.pProgram;
  55744. pSub->flags |= MEM_Blob;
  55745. pSub->n = nSub*sizeof(SubProgram*);
  55746. }
  55747. }
  55748. }
  55749. pMem->flags = MEM_Int;
  55750. pMem->u.i = pOp->p1; /* P1 */
  55751. pMem->type = SQLITE_INTEGER;
  55752. pMem++;
  55753. pMem->flags = MEM_Int;
  55754. pMem->u.i = pOp->p2; /* P2 */
  55755. pMem->type = SQLITE_INTEGER;
  55756. pMem++;
  55757. pMem->flags = MEM_Int;
  55758. pMem->u.i = pOp->p3; /* P3 */
  55759. pMem->type = SQLITE_INTEGER;
  55760. pMem++;
  55761. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  55762. assert( p->db->mallocFailed );
  55763. return SQLITE_ERROR;
  55764. }
  55765. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  55766. z = displayP4(pOp, pMem->z, 32);
  55767. if( z!=pMem->z ){
  55768. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  55769. }else{
  55770. assert( pMem->z!=0 );
  55771. pMem->n = sqlite3Strlen30(pMem->z);
  55772. pMem->enc = SQLITE_UTF8;
  55773. }
  55774. pMem->type = SQLITE_TEXT;
  55775. pMem++;
  55776. if( p->explain==1 ){
  55777. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  55778. assert( p->db->mallocFailed );
  55779. return SQLITE_ERROR;
  55780. }
  55781. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  55782. pMem->n = 2;
  55783. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  55784. pMem->type = SQLITE_TEXT;
  55785. pMem->enc = SQLITE_UTF8;
  55786. pMem++;
  55787. #ifdef SQLITE_DEBUG
  55788. if( pOp->zComment ){
  55789. pMem->flags = MEM_Str|MEM_Term;
  55790. pMem->z = pOp->zComment;
  55791. pMem->n = sqlite3Strlen30(pMem->z);
  55792. pMem->enc = SQLITE_UTF8;
  55793. pMem->type = SQLITE_TEXT;
  55794. }else
  55795. #endif
  55796. {
  55797. pMem->flags = MEM_Null; /* Comment */
  55798. pMem->type = SQLITE_NULL;
  55799. }
  55800. }
  55801. p->nResColumn = 8 - 4*(p->explain-1);
  55802. p->pResultSet = &p->aMem[1];
  55803. p->rc = SQLITE_OK;
  55804. rc = SQLITE_ROW;
  55805. }
  55806. return rc;
  55807. }
  55808. #endif /* SQLITE_OMIT_EXPLAIN */
  55809. #ifdef SQLITE_DEBUG
  55810. /*
  55811. ** Print the SQL that was used to generate a VDBE program.
  55812. */
  55813. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  55814. int nOp = p->nOp;
  55815. VdbeOp *pOp;
  55816. if( nOp<1 ) return;
  55817. pOp = &p->aOp[0];
  55818. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  55819. const char *z = pOp->p4.z;
  55820. while( sqlite3Isspace(*z) ) z++;
  55821. printf("SQL: [%s]\n", z);
  55822. }
  55823. }
  55824. #endif
  55825. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  55826. /*
  55827. ** Print an IOTRACE message showing SQL content.
  55828. */
  55829. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  55830. int nOp = p->nOp;
  55831. VdbeOp *pOp;
  55832. if( sqlite3IoTrace==0 ) return;
  55833. if( nOp<1 ) return;
  55834. pOp = &p->aOp[0];
  55835. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  55836. int i, j;
  55837. char z[1000];
  55838. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  55839. for(i=0; sqlite3Isspace(z[i]); i++){}
  55840. for(j=0; z[i]; i++){
  55841. if( sqlite3Isspace(z[i]) ){
  55842. if( z[i-1]!=' ' ){
  55843. z[j++] = ' ';
  55844. }
  55845. }else{
  55846. z[j++] = z[i];
  55847. }
  55848. }
  55849. z[j] = 0;
  55850. sqlite3IoTrace("SQL %s\n", z);
  55851. }
  55852. }
  55853. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  55854. /*
  55855. ** Allocate space from a fixed size buffer and return a pointer to
  55856. ** that space. If insufficient space is available, return NULL.
  55857. **
  55858. ** The pBuf parameter is the initial value of a pointer which will
  55859. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  55860. ** NULL, it means that memory space has already been allocated and that
  55861. ** this routine should not allocate any new memory. When pBuf is not
  55862. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  55863. ** is NULL.
  55864. **
  55865. ** nByte is the number of bytes of space needed.
  55866. **
  55867. ** *ppFrom points to available space and pEnd points to the end of the
  55868. ** available space. When space is allocated, *ppFrom is advanced past
  55869. ** the end of the allocated space.
  55870. **
  55871. ** *pnByte is a counter of the number of bytes of space that have failed
  55872. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  55873. ** request, then increment *pnByte by the amount of the request.
  55874. */
  55875. static void *allocSpace(
  55876. void *pBuf, /* Where return pointer will be stored */
  55877. int nByte, /* Number of bytes to allocate */
  55878. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  55879. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  55880. int *pnByte /* If allocation cannot be made, increment *pnByte */
  55881. ){
  55882. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  55883. if( pBuf ) return pBuf;
  55884. nByte = ROUND8(nByte);
  55885. if( &(*ppFrom)[nByte] <= pEnd ){
  55886. pBuf = (void*)*ppFrom;
  55887. *ppFrom += nByte;
  55888. }else{
  55889. *pnByte += nByte;
  55890. }
  55891. return pBuf;
  55892. }
  55893. /*
  55894. ** Rewind the VDBE back to the beginning in preparation for
  55895. ** running it.
  55896. */
  55897. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  55898. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  55899. int i;
  55900. #endif
  55901. assert( p!=0 );
  55902. assert( p->magic==VDBE_MAGIC_INIT );
  55903. /* There should be at least one opcode.
  55904. */
  55905. assert( p->nOp>0 );
  55906. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  55907. p->magic = VDBE_MAGIC_RUN;
  55908. #ifdef SQLITE_DEBUG
  55909. for(i=1; i<p->nMem; i++){
  55910. assert( p->aMem[i].db==p->db );
  55911. }
  55912. #endif
  55913. p->pc = -1;
  55914. p->rc = SQLITE_OK;
  55915. p->errorAction = OE_Abort;
  55916. p->magic = VDBE_MAGIC_RUN;
  55917. p->nChange = 0;
  55918. p->cacheCtr = 1;
  55919. p->minWriteFileFormat = 255;
  55920. p->iStatement = 0;
  55921. p->nFkConstraint = 0;
  55922. #ifdef VDBE_PROFILE
  55923. for(i=0; i<p->nOp; i++){
  55924. p->aOp[i].cnt = 0;
  55925. p->aOp[i].cycles = 0;
  55926. }
  55927. #endif
  55928. }
  55929. /*
  55930. ** Prepare a virtual machine for execution for the first time after
  55931. ** creating the virtual machine. This involves things such
  55932. ** as allocating stack space and initializing the program counter.
  55933. ** After the VDBE has be prepped, it can be executed by one or more
  55934. ** calls to sqlite3VdbeExec().
  55935. **
  55936. ** This function may be called exact once on a each virtual machine.
  55937. ** After this routine is called the VM has been "packaged" and is ready
  55938. ** to run. After this routine is called, futher calls to
  55939. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  55940. ** the Vdbe from the Parse object that helped generate it so that the
  55941. ** the Vdbe becomes an independent entity and the Parse object can be
  55942. ** destroyed.
  55943. **
  55944. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  55945. ** to its initial state after it has been run.
  55946. */
  55947. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  55948. Vdbe *p, /* The VDBE */
  55949. Parse *pParse /* Parsing context */
  55950. ){
  55951. sqlite3 *db; /* The database connection */
  55952. int nVar; /* Number of parameters */
  55953. int nMem; /* Number of VM memory registers */
  55954. int nCursor; /* Number of cursors required */
  55955. int nArg; /* Number of arguments in subprograms */
  55956. int nOnce; /* Number of OP_Once instructions */
  55957. int n; /* Loop counter */
  55958. u8 *zCsr; /* Memory available for allocation */
  55959. u8 *zEnd; /* First byte past allocated memory */
  55960. int nByte; /* How much extra memory is needed */
  55961. assert( p!=0 );
  55962. assert( p->nOp>0 );
  55963. assert( pParse!=0 );
  55964. assert( p->magic==VDBE_MAGIC_INIT );
  55965. db = p->db;
  55966. assert( db->mallocFailed==0 );
  55967. nVar = pParse->nVar;
  55968. nMem = pParse->nMem;
  55969. nCursor = pParse->nTab;
  55970. nArg = pParse->nMaxArg;
  55971. nOnce = pParse->nOnce;
  55972. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  55973. /* For each cursor required, also allocate a memory cell. Memory
  55974. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  55975. ** the vdbe program. Instead they are used to allocate space for
  55976. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  55977. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  55978. ** stores the blob of memory associated with cursor 1, etc.
  55979. **
  55980. ** See also: allocateCursor().
  55981. */
  55982. nMem += nCursor;
  55983. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  55984. ** an array to marshal SQL function arguments in.
  55985. */
  55986. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  55987. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  55988. resolveP2Values(p, &nArg);
  55989. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  55990. if( pParse->explain && nMem<10 ){
  55991. nMem = 10;
  55992. }
  55993. memset(zCsr, 0, zEnd-zCsr);
  55994. zCsr += (zCsr - (u8*)0)&7;
  55995. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  55996. p->expired = 0;
  55997. /* Memory for registers, parameters, cursor, etc, is allocated in two
  55998. ** passes. On the first pass, we try to reuse unused space at the
  55999. ** end of the opcode array. If we are unable to satisfy all memory
  56000. ** requirements by reusing the opcode array tail, then the second
  56001. ** pass will fill in the rest using a fresh allocation.
  56002. **
  56003. ** This two-pass approach that reuses as much memory as possible from
  56004. ** the leftover space at the end of the opcode array can significantly
  56005. ** reduce the amount of memory held by a prepared statement.
  56006. */
  56007. do {
  56008. nByte = 0;
  56009. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  56010. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  56011. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  56012. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  56013. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  56014. &zCsr, zEnd, &nByte);
  56015. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  56016. if( nByte ){
  56017. p->pFree = sqlite3DbMallocZero(db, nByte);
  56018. }
  56019. zCsr = p->pFree;
  56020. zEnd = &zCsr[nByte];
  56021. }while( nByte && !db->mallocFailed );
  56022. p->nCursor = (u16)nCursor;
  56023. p->nOnceFlag = nOnce;
  56024. if( p->aVar ){
  56025. p->nVar = (ynVar)nVar;
  56026. for(n=0; n<nVar; n++){
  56027. p->aVar[n].flags = MEM_Null;
  56028. p->aVar[n].db = db;
  56029. }
  56030. }
  56031. if( p->azVar ){
  56032. p->nzVar = pParse->nzVar;
  56033. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  56034. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  56035. }
  56036. if( p->aMem ){
  56037. p->aMem--; /* aMem[] goes from 1..nMem */
  56038. p->nMem = nMem; /* not from 0..nMem-1 */
  56039. for(n=1; n<=nMem; n++){
  56040. p->aMem[n].flags = MEM_Invalid;
  56041. p->aMem[n].db = db;
  56042. }
  56043. }
  56044. p->explain = pParse->explain;
  56045. sqlite3VdbeRewind(p);
  56046. }
  56047. /*
  56048. ** Close a VDBE cursor and release all the resources that cursor
  56049. ** happens to hold.
  56050. */
  56051. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  56052. if( pCx==0 ){
  56053. return;
  56054. }
  56055. sqlite3VdbeSorterClose(p->db, pCx);
  56056. if( pCx->pBt ){
  56057. sqlite3BtreeClose(pCx->pBt);
  56058. /* The pCx->pCursor will be close automatically, if it exists, by
  56059. ** the call above. */
  56060. }else if( pCx->pCursor ){
  56061. sqlite3BtreeCloseCursor(pCx->pCursor);
  56062. }
  56063. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56064. if( pCx->pVtabCursor ){
  56065. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  56066. const sqlite3_module *pModule = pCx->pModule;
  56067. p->inVtabMethod = 1;
  56068. pModule->xClose(pVtabCursor);
  56069. p->inVtabMethod = 0;
  56070. }
  56071. #endif
  56072. }
  56073. /*
  56074. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  56075. ** is used, for example, when a trigger sub-program is halted to restore
  56076. ** control to the main program.
  56077. */
  56078. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  56079. Vdbe *v = pFrame->v;
  56080. v->aOnceFlag = pFrame->aOnceFlag;
  56081. v->nOnceFlag = pFrame->nOnceFlag;
  56082. v->aOp = pFrame->aOp;
  56083. v->nOp = pFrame->nOp;
  56084. v->aMem = pFrame->aMem;
  56085. v->nMem = pFrame->nMem;
  56086. v->apCsr = pFrame->apCsr;
  56087. v->nCursor = pFrame->nCursor;
  56088. v->db->lastRowid = pFrame->lastRowid;
  56089. v->nChange = pFrame->nChange;
  56090. return pFrame->pc;
  56091. }
  56092. /*
  56093. ** Close all cursors.
  56094. **
  56095. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  56096. ** cell array. This is necessary as the memory cell array may contain
  56097. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  56098. ** open cursors.
  56099. */
  56100. static void closeAllCursors(Vdbe *p){
  56101. if( p->pFrame ){
  56102. VdbeFrame *pFrame;
  56103. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  56104. sqlite3VdbeFrameRestore(pFrame);
  56105. }
  56106. p->pFrame = 0;
  56107. p->nFrame = 0;
  56108. if( p->apCsr ){
  56109. int i;
  56110. for(i=0; i<p->nCursor; i++){
  56111. VdbeCursor *pC = p->apCsr[i];
  56112. if( pC ){
  56113. sqlite3VdbeFreeCursor(p, pC);
  56114. p->apCsr[i] = 0;
  56115. }
  56116. }
  56117. }
  56118. if( p->aMem ){
  56119. releaseMemArray(&p->aMem[1], p->nMem);
  56120. }
  56121. while( p->pDelFrame ){
  56122. VdbeFrame *pDel = p->pDelFrame;
  56123. p->pDelFrame = pDel->pParent;
  56124. sqlite3VdbeFrameDelete(pDel);
  56125. }
  56126. }
  56127. /*
  56128. ** Clean up the VM after execution.
  56129. **
  56130. ** This routine will automatically close any cursors, lists, and/or
  56131. ** sorters that were left open. It also deletes the values of
  56132. ** variables in the aVar[] array.
  56133. */
  56134. static void Cleanup(Vdbe *p){
  56135. sqlite3 *db = p->db;
  56136. #ifdef SQLITE_DEBUG
  56137. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  56138. ** Vdbe.aMem[] arrays have already been cleaned up. */
  56139. int i;
  56140. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  56141. if( p->aMem ){
  56142. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  56143. }
  56144. #endif
  56145. sqlite3DbFree(db, p->zErrMsg);
  56146. p->zErrMsg = 0;
  56147. p->pResultSet = 0;
  56148. }
  56149. /*
  56150. ** Set the number of result columns that will be returned by this SQL
  56151. ** statement. This is now set at compile time, rather than during
  56152. ** execution of the vdbe program so that sqlite3_column_count() can
  56153. ** be called on an SQL statement before sqlite3_step().
  56154. */
  56155. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  56156. Mem *pColName;
  56157. int n;
  56158. sqlite3 *db = p->db;
  56159. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  56160. sqlite3DbFree(db, p->aColName);
  56161. n = nResColumn*COLNAME_N;
  56162. p->nResColumn = (u16)nResColumn;
  56163. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  56164. if( p->aColName==0 ) return;
  56165. while( n-- > 0 ){
  56166. pColName->flags = MEM_Null;
  56167. pColName->db = p->db;
  56168. pColName++;
  56169. }
  56170. }
  56171. /*
  56172. ** Set the name of the idx'th column to be returned by the SQL statement.
  56173. ** zName must be a pointer to a nul terminated string.
  56174. **
  56175. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  56176. **
  56177. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  56178. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  56179. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  56180. */
  56181. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  56182. Vdbe *p, /* Vdbe being configured */
  56183. int idx, /* Index of column zName applies to */
  56184. int var, /* One of the COLNAME_* constants */
  56185. const char *zName, /* Pointer to buffer containing name */
  56186. void (*xDel)(void*) /* Memory management strategy for zName */
  56187. ){
  56188. int rc;
  56189. Mem *pColName;
  56190. assert( idx<p->nResColumn );
  56191. assert( var<COLNAME_N );
  56192. if( p->db->mallocFailed ){
  56193. assert( !zName || xDel!=SQLITE_DYNAMIC );
  56194. return SQLITE_NOMEM;
  56195. }
  56196. assert( p->aColName!=0 );
  56197. pColName = &(p->aColName[idx+var*p->nResColumn]);
  56198. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  56199. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  56200. return rc;
  56201. }
  56202. /*
  56203. ** A read or write transaction may or may not be active on database handle
  56204. ** db. If a transaction is active, commit it. If there is a
  56205. ** write-transaction spanning more than one database file, this routine
  56206. ** takes care of the master journal trickery.
  56207. */
  56208. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  56209. int i;
  56210. int nTrans = 0; /* Number of databases with an active write-transaction */
  56211. int rc = SQLITE_OK;
  56212. int needXcommit = 0;
  56213. #ifdef SQLITE_OMIT_VIRTUALTABLE
  56214. /* With this option, sqlite3VtabSync() is defined to be simply
  56215. ** SQLITE_OK so p is not used.
  56216. */
  56217. UNUSED_PARAMETER(p);
  56218. #endif
  56219. /* Before doing anything else, call the xSync() callback for any
  56220. ** virtual module tables written in this transaction. This has to
  56221. ** be done before determining whether a master journal file is
  56222. ** required, as an xSync() callback may add an attached database
  56223. ** to the transaction.
  56224. */
  56225. rc = sqlite3VtabSync(db, &p->zErrMsg);
  56226. /* This loop determines (a) if the commit hook should be invoked and
  56227. ** (b) how many database files have open write transactions, not
  56228. ** including the temp database. (b) is important because if more than
  56229. ** one database file has an open write transaction, a master journal
  56230. ** file is required for an atomic commit.
  56231. */
  56232. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  56233. Btree *pBt = db->aDb[i].pBt;
  56234. if( sqlite3BtreeIsInTrans(pBt) ){
  56235. needXcommit = 1;
  56236. if( i!=1 ) nTrans++;
  56237. sqlite3BtreeEnter(pBt);
  56238. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  56239. sqlite3BtreeLeave(pBt);
  56240. }
  56241. }
  56242. if( rc!=SQLITE_OK ){
  56243. return rc;
  56244. }
  56245. /* If there are any write-transactions at all, invoke the commit hook */
  56246. if( needXcommit && db->xCommitCallback ){
  56247. rc = db->xCommitCallback(db->pCommitArg);
  56248. if( rc ){
  56249. return SQLITE_CONSTRAINT;
  56250. }
  56251. }
  56252. /* The simple case - no more than one database file (not counting the
  56253. ** TEMP database) has a transaction active. There is no need for the
  56254. ** master-journal.
  56255. **
  56256. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  56257. ** string, it means the main database is :memory: or a temp file. In
  56258. ** that case we do not support atomic multi-file commits, so use the
  56259. ** simple case then too.
  56260. */
  56261. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  56262. || nTrans<=1
  56263. ){
  56264. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  56265. Btree *pBt = db->aDb[i].pBt;
  56266. if( pBt ){
  56267. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  56268. }
  56269. }
  56270. /* Do the commit only if all databases successfully complete phase 1.
  56271. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  56272. ** IO error while deleting or truncating a journal file. It is unlikely,
  56273. ** but could happen. In this case abandon processing and return the error.
  56274. */
  56275. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  56276. Btree *pBt = db->aDb[i].pBt;
  56277. if( pBt ){
  56278. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  56279. }
  56280. }
  56281. if( rc==SQLITE_OK ){
  56282. sqlite3VtabCommit(db);
  56283. }
  56284. }
  56285. /* The complex case - There is a multi-file write-transaction active.
  56286. ** This requires a master journal file to ensure the transaction is
  56287. ** committed atomicly.
  56288. */
  56289. #ifndef SQLITE_OMIT_DISKIO
  56290. else{
  56291. sqlite3_vfs *pVfs = db->pVfs;
  56292. int needSync = 0;
  56293. char *zMaster = 0; /* File-name for the master journal */
  56294. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  56295. sqlite3_file *pMaster = 0;
  56296. i64 offset = 0;
  56297. int res;
  56298. int retryCount = 0;
  56299. int nMainFile;
  56300. /* Select a master journal file name */
  56301. nMainFile = sqlite3Strlen30(zMainFile);
  56302. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  56303. if( zMaster==0 ) return SQLITE_NOMEM;
  56304. do {
  56305. u32 iRandom;
  56306. if( retryCount ){
  56307. if( retryCount>100 ){
  56308. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  56309. sqlite3OsDelete(pVfs, zMaster, 0);
  56310. break;
  56311. }else if( retryCount==1 ){
  56312. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  56313. }
  56314. }
  56315. retryCount++;
  56316. sqlite3_randomness(sizeof(iRandom), &iRandom);
  56317. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  56318. (iRandom>>8)&0xffffff, iRandom&0xff);
  56319. /* The antipenultimate character of the master journal name must
  56320. ** be "9" to avoid name collisions when using 8+3 filenames. */
  56321. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  56322. sqlite3FileSuffix3(zMainFile, zMaster);
  56323. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  56324. }while( rc==SQLITE_OK && res );
  56325. if( rc==SQLITE_OK ){
  56326. /* Open the master journal. */
  56327. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  56328. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  56329. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  56330. );
  56331. }
  56332. if( rc!=SQLITE_OK ){
  56333. sqlite3DbFree(db, zMaster);
  56334. return rc;
  56335. }
  56336. /* Write the name of each database file in the transaction into the new
  56337. ** master journal file. If an error occurs at this point close
  56338. ** and delete the master journal file. All the individual journal files
  56339. ** still have 'null' as the master journal pointer, so they will roll
  56340. ** back independently if a failure occurs.
  56341. */
  56342. for(i=0; i<db->nDb; i++){
  56343. Btree *pBt = db->aDb[i].pBt;
  56344. if( sqlite3BtreeIsInTrans(pBt) ){
  56345. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  56346. if( zFile==0 ){
  56347. continue; /* Ignore TEMP and :memory: databases */
  56348. }
  56349. assert( zFile[0]!=0 );
  56350. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  56351. needSync = 1;
  56352. }
  56353. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  56354. offset += sqlite3Strlen30(zFile)+1;
  56355. if( rc!=SQLITE_OK ){
  56356. sqlite3OsCloseFree(pMaster);
  56357. sqlite3OsDelete(pVfs, zMaster, 0);
  56358. sqlite3DbFree(db, zMaster);
  56359. return rc;
  56360. }
  56361. }
  56362. }
  56363. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  56364. ** flag is set this is not required.
  56365. */
  56366. if( needSync
  56367. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  56368. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  56369. ){
  56370. sqlite3OsCloseFree(pMaster);
  56371. sqlite3OsDelete(pVfs, zMaster, 0);
  56372. sqlite3DbFree(db, zMaster);
  56373. return rc;
  56374. }
  56375. /* Sync all the db files involved in the transaction. The same call
  56376. ** sets the master journal pointer in each individual journal. If
  56377. ** an error occurs here, do not delete the master journal file.
  56378. **
  56379. ** If the error occurs during the first call to
  56380. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  56381. ** master journal file will be orphaned. But we cannot delete it,
  56382. ** in case the master journal file name was written into the journal
  56383. ** file before the failure occurred.
  56384. */
  56385. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  56386. Btree *pBt = db->aDb[i].pBt;
  56387. if( pBt ){
  56388. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  56389. }
  56390. }
  56391. sqlite3OsCloseFree(pMaster);
  56392. assert( rc!=SQLITE_BUSY );
  56393. if( rc!=SQLITE_OK ){
  56394. sqlite3DbFree(db, zMaster);
  56395. return rc;
  56396. }
  56397. /* Delete the master journal file. This commits the transaction. After
  56398. ** doing this the directory is synced again before any individual
  56399. ** transaction files are deleted.
  56400. */
  56401. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  56402. sqlite3DbFree(db, zMaster);
  56403. zMaster = 0;
  56404. if( rc ){
  56405. return rc;
  56406. }
  56407. /* All files and directories have already been synced, so the following
  56408. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  56409. ** deleting or truncating journals. If something goes wrong while
  56410. ** this is happening we don't really care. The integrity of the
  56411. ** transaction is already guaranteed, but some stray 'cold' journals
  56412. ** may be lying around. Returning an error code won't help matters.
  56413. */
  56414. disable_simulated_io_errors();
  56415. sqlite3BeginBenignMalloc();
  56416. for(i=0; i<db->nDb; i++){
  56417. Btree *pBt = db->aDb[i].pBt;
  56418. if( pBt ){
  56419. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  56420. }
  56421. }
  56422. sqlite3EndBenignMalloc();
  56423. enable_simulated_io_errors();
  56424. sqlite3VtabCommit(db);
  56425. }
  56426. #endif
  56427. return rc;
  56428. }
  56429. /*
  56430. ** This routine checks that the sqlite3.activeVdbeCnt count variable
  56431. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  56432. ** currently active. An assertion fails if the two counts do not match.
  56433. ** This is an internal self-check only - it is not an essential processing
  56434. ** step.
  56435. **
  56436. ** This is a no-op if NDEBUG is defined.
  56437. */
  56438. #ifndef NDEBUG
  56439. static void checkActiveVdbeCnt(sqlite3 *db){
  56440. Vdbe *p;
  56441. int cnt = 0;
  56442. int nWrite = 0;
  56443. p = db->pVdbe;
  56444. while( p ){
  56445. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  56446. cnt++;
  56447. if( p->readOnly==0 ) nWrite++;
  56448. }
  56449. p = p->pNext;
  56450. }
  56451. assert( cnt==db->activeVdbeCnt );
  56452. assert( nWrite==db->writeVdbeCnt );
  56453. }
  56454. #else
  56455. #define checkActiveVdbeCnt(x)
  56456. #endif
  56457. /*
  56458. ** If the Vdbe passed as the first argument opened a statement-transaction,
  56459. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  56460. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  56461. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  56462. ** statement transaction is commtted.
  56463. **
  56464. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  56465. ** Otherwise SQLITE_OK.
  56466. */
  56467. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  56468. sqlite3 *const db = p->db;
  56469. int rc = SQLITE_OK;
  56470. /* If p->iStatement is greater than zero, then this Vdbe opened a
  56471. ** statement transaction that should be closed here. The only exception
  56472. ** is that an IO error may have occured, causing an emergency rollback.
  56473. ** In this case (db->nStatement==0), and there is nothing to do.
  56474. */
  56475. if( db->nStatement && p->iStatement ){
  56476. int i;
  56477. const int iSavepoint = p->iStatement-1;
  56478. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  56479. assert( db->nStatement>0 );
  56480. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  56481. for(i=0; i<db->nDb; i++){
  56482. int rc2 = SQLITE_OK;
  56483. Btree *pBt = db->aDb[i].pBt;
  56484. if( pBt ){
  56485. if( eOp==SAVEPOINT_ROLLBACK ){
  56486. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  56487. }
  56488. if( rc2==SQLITE_OK ){
  56489. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  56490. }
  56491. if( rc==SQLITE_OK ){
  56492. rc = rc2;
  56493. }
  56494. }
  56495. }
  56496. db->nStatement--;
  56497. p->iStatement = 0;
  56498. if( rc==SQLITE_OK ){
  56499. if( eOp==SAVEPOINT_ROLLBACK ){
  56500. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  56501. }
  56502. if( rc==SQLITE_OK ){
  56503. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  56504. }
  56505. }
  56506. /* If the statement transaction is being rolled back, also restore the
  56507. ** database handles deferred constraint counter to the value it had when
  56508. ** the statement transaction was opened. */
  56509. if( eOp==SAVEPOINT_ROLLBACK ){
  56510. db->nDeferredCons = p->nStmtDefCons;
  56511. }
  56512. }
  56513. return rc;
  56514. }
  56515. /*
  56516. ** This function is called when a transaction opened by the database
  56517. ** handle associated with the VM passed as an argument is about to be
  56518. ** committed. If there are outstanding deferred foreign key constraint
  56519. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  56520. **
  56521. ** If there are outstanding FK violations and this function returns
  56522. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
  56523. ** an error message to it. Then return SQLITE_ERROR.
  56524. */
  56525. #ifndef SQLITE_OMIT_FOREIGN_KEY
  56526. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  56527. sqlite3 *db = p->db;
  56528. if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
  56529. p->rc = SQLITE_CONSTRAINT;
  56530. p->errorAction = OE_Abort;
  56531. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  56532. return SQLITE_ERROR;
  56533. }
  56534. return SQLITE_OK;
  56535. }
  56536. #endif
  56537. /*
  56538. ** This routine is called the when a VDBE tries to halt. If the VDBE
  56539. ** has made changes and is in autocommit mode, then commit those
  56540. ** changes. If a rollback is needed, then do the rollback.
  56541. **
  56542. ** This routine is the only way to move the state of a VM from
  56543. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  56544. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  56545. **
  56546. ** Return an error code. If the commit could not complete because of
  56547. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  56548. ** means the close did not happen and needs to be repeated.
  56549. */
  56550. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  56551. int rc; /* Used to store transient return codes */
  56552. sqlite3 *db = p->db;
  56553. /* This function contains the logic that determines if a statement or
  56554. ** transaction will be committed or rolled back as a result of the
  56555. ** execution of this virtual machine.
  56556. **
  56557. ** If any of the following errors occur:
  56558. **
  56559. ** SQLITE_NOMEM
  56560. ** SQLITE_IOERR
  56561. ** SQLITE_FULL
  56562. ** SQLITE_INTERRUPT
  56563. **
  56564. ** Then the internal cache might have been left in an inconsistent
  56565. ** state. We need to rollback the statement transaction, if there is
  56566. ** one, or the complete transaction if there is no statement transaction.
  56567. */
  56568. if( p->db->mallocFailed ){
  56569. p->rc = SQLITE_NOMEM;
  56570. }
  56571. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  56572. closeAllCursors(p);
  56573. if( p->magic!=VDBE_MAGIC_RUN ){
  56574. return SQLITE_OK;
  56575. }
  56576. checkActiveVdbeCnt(db);
  56577. /* No commit or rollback needed if the program never started */
  56578. if( p->pc>=0 ){
  56579. int mrc; /* Primary error code from p->rc */
  56580. int eStatementOp = 0;
  56581. int isSpecialError; /* Set to true if a 'special' error */
  56582. /* Lock all btrees used by the statement */
  56583. sqlite3VdbeEnter(p);
  56584. /* Check for one of the special errors */
  56585. mrc = p->rc & 0xff;
  56586. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  56587. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  56588. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  56589. if( isSpecialError ){
  56590. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  56591. ** no rollback is necessary. Otherwise, at least a savepoint
  56592. ** transaction must be rolled back to restore the database to a
  56593. ** consistent state.
  56594. **
  56595. ** Even if the statement is read-only, it is important to perform
  56596. ** a statement or transaction rollback operation. If the error
  56597. ** occured while writing to the journal, sub-journal or database
  56598. ** file as part of an effort to free up cache space (see function
  56599. ** pagerStress() in pager.c), the rollback is required to restore
  56600. ** the pager to a consistent state.
  56601. */
  56602. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  56603. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  56604. eStatementOp = SAVEPOINT_ROLLBACK;
  56605. }else{
  56606. /* We are forced to roll back the active transaction. Before doing
  56607. ** so, abort any other statements this handle currently has active.
  56608. */
  56609. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  56610. sqlite3CloseSavepoints(db);
  56611. db->autoCommit = 1;
  56612. }
  56613. }
  56614. }
  56615. /* Check for immediate foreign key violations. */
  56616. if( p->rc==SQLITE_OK ){
  56617. sqlite3VdbeCheckFk(p, 0);
  56618. }
  56619. /* If the auto-commit flag is set and this is the only active writer
  56620. ** VM, then we do either a commit or rollback of the current transaction.
  56621. **
  56622. ** Note: This block also runs if one of the special errors handled
  56623. ** above has occurred.
  56624. */
  56625. if( !sqlite3VtabInSync(db)
  56626. && db->autoCommit
  56627. && db->writeVdbeCnt==(p->readOnly==0)
  56628. ){
  56629. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  56630. rc = sqlite3VdbeCheckFk(p, 1);
  56631. if( rc!=SQLITE_OK ){
  56632. if( NEVER(p->readOnly) ){
  56633. sqlite3VdbeLeave(p);
  56634. return SQLITE_ERROR;
  56635. }
  56636. rc = SQLITE_CONSTRAINT;
  56637. }else{
  56638. /* The auto-commit flag is true, the vdbe program was successful
  56639. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  56640. ** key constraints to hold up the transaction. This means a commit
  56641. ** is required. */
  56642. rc = vdbeCommit(db, p);
  56643. }
  56644. if( rc==SQLITE_BUSY && p->readOnly ){
  56645. sqlite3VdbeLeave(p);
  56646. return SQLITE_BUSY;
  56647. }else if( rc!=SQLITE_OK ){
  56648. p->rc = rc;
  56649. sqlite3RollbackAll(db, SQLITE_OK);
  56650. }else{
  56651. db->nDeferredCons = 0;
  56652. sqlite3CommitInternalChanges(db);
  56653. }
  56654. }else{
  56655. sqlite3RollbackAll(db, SQLITE_OK);
  56656. }
  56657. db->nStatement = 0;
  56658. }else if( eStatementOp==0 ){
  56659. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  56660. eStatementOp = SAVEPOINT_RELEASE;
  56661. }else if( p->errorAction==OE_Abort ){
  56662. eStatementOp = SAVEPOINT_ROLLBACK;
  56663. }else{
  56664. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  56665. sqlite3CloseSavepoints(db);
  56666. db->autoCommit = 1;
  56667. }
  56668. }
  56669. /* If eStatementOp is non-zero, then a statement transaction needs to
  56670. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  56671. ** do so. If this operation returns an error, and the current statement
  56672. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  56673. ** current statement error code.
  56674. */
  56675. if( eStatementOp ){
  56676. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  56677. if( rc ){
  56678. if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
  56679. p->rc = rc;
  56680. sqlite3DbFree(db, p->zErrMsg);
  56681. p->zErrMsg = 0;
  56682. }
  56683. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  56684. sqlite3CloseSavepoints(db);
  56685. db->autoCommit = 1;
  56686. }
  56687. }
  56688. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  56689. ** has been rolled back, update the database connection change-counter.
  56690. */
  56691. if( p->changeCntOn ){
  56692. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  56693. sqlite3VdbeSetChanges(db, p->nChange);
  56694. }else{
  56695. sqlite3VdbeSetChanges(db, 0);
  56696. }
  56697. p->nChange = 0;
  56698. }
  56699. /* Release the locks */
  56700. sqlite3VdbeLeave(p);
  56701. }
  56702. /* We have successfully halted and closed the VM. Record this fact. */
  56703. if( p->pc>=0 ){
  56704. db->activeVdbeCnt--;
  56705. if( !p->readOnly ){
  56706. db->writeVdbeCnt--;
  56707. }
  56708. assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  56709. }
  56710. p->magic = VDBE_MAGIC_HALT;
  56711. checkActiveVdbeCnt(db);
  56712. if( p->db->mallocFailed ){
  56713. p->rc = SQLITE_NOMEM;
  56714. }
  56715. /* If the auto-commit flag is set to true, then any locks that were held
  56716. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  56717. ** to invoke any required unlock-notify callbacks.
  56718. */
  56719. if( db->autoCommit ){
  56720. sqlite3ConnectionUnlocked(db);
  56721. }
  56722. assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
  56723. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  56724. }
  56725. /*
  56726. ** Each VDBE holds the result of the most recent sqlite3_step() call
  56727. ** in p->rc. This routine sets that result back to SQLITE_OK.
  56728. */
  56729. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  56730. p->rc = SQLITE_OK;
  56731. }
  56732. /*
  56733. ** Copy the error code and error message belonging to the VDBE passed
  56734. ** as the first argument to its database handle (so that they will be
  56735. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  56736. **
  56737. ** This function does not clear the VDBE error code or message, just
  56738. ** copies them to the database handle.
  56739. */
  56740. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  56741. sqlite3 *db = p->db;
  56742. int rc = p->rc;
  56743. if( p->zErrMsg ){
  56744. u8 mallocFailed = db->mallocFailed;
  56745. sqlite3BeginBenignMalloc();
  56746. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  56747. sqlite3EndBenignMalloc();
  56748. db->mallocFailed = mallocFailed;
  56749. db->errCode = rc;
  56750. }else{
  56751. sqlite3Error(db, rc, 0);
  56752. }
  56753. return rc;
  56754. }
  56755. #ifdef SQLITE_ENABLE_SQLLOG
  56756. /*
  56757. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  56758. ** invoke it.
  56759. */
  56760. static void vdbeInvokeSqllog(Vdbe *v){
  56761. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  56762. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  56763. assert( v->db->init.busy==0 );
  56764. if( zExpanded ){
  56765. sqlite3GlobalConfig.xSqllog(
  56766. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  56767. );
  56768. sqlite3DbFree(v->db, zExpanded);
  56769. }
  56770. }
  56771. }
  56772. #else
  56773. # define vdbeInvokeSqllog(x)
  56774. #endif
  56775. /*
  56776. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  56777. ** Write any error messages into *pzErrMsg. Return the result code.
  56778. **
  56779. ** After this routine is run, the VDBE should be ready to be executed
  56780. ** again.
  56781. **
  56782. ** To look at it another way, this routine resets the state of the
  56783. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  56784. ** VDBE_MAGIC_INIT.
  56785. */
  56786. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  56787. sqlite3 *db;
  56788. db = p->db;
  56789. /* If the VM did not run to completion or if it encountered an
  56790. ** error, then it might not have been halted properly. So halt
  56791. ** it now.
  56792. */
  56793. sqlite3VdbeHalt(p);
  56794. /* If the VDBE has be run even partially, then transfer the error code
  56795. ** and error message from the VDBE into the main database structure. But
  56796. ** if the VDBE has just been set to run but has not actually executed any
  56797. ** instructions yet, leave the main database error information unchanged.
  56798. */
  56799. if( p->pc>=0 ){
  56800. vdbeInvokeSqllog(p);
  56801. sqlite3VdbeTransferError(p);
  56802. sqlite3DbFree(db, p->zErrMsg);
  56803. p->zErrMsg = 0;
  56804. if( p->runOnlyOnce ) p->expired = 1;
  56805. }else if( p->rc && p->expired ){
  56806. /* The expired flag was set on the VDBE before the first call
  56807. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  56808. ** called), set the database error in this case as well.
  56809. */
  56810. sqlite3Error(db, p->rc, 0);
  56811. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  56812. sqlite3DbFree(db, p->zErrMsg);
  56813. p->zErrMsg = 0;
  56814. }
  56815. /* Reclaim all memory used by the VDBE
  56816. */
  56817. Cleanup(p);
  56818. /* Save profiling information from this VDBE run.
  56819. */
  56820. #ifdef VDBE_PROFILE
  56821. {
  56822. FILE *out = fopen("vdbe_profile.out", "a");
  56823. if( out ){
  56824. int i;
  56825. fprintf(out, "---- ");
  56826. for(i=0; i<p->nOp; i++){
  56827. fprintf(out, "%02x", p->aOp[i].opcode);
  56828. }
  56829. fprintf(out, "\n");
  56830. for(i=0; i<p->nOp; i++){
  56831. fprintf(out, "%6d %10lld %8lld ",
  56832. p->aOp[i].cnt,
  56833. p->aOp[i].cycles,
  56834. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  56835. );
  56836. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  56837. }
  56838. fclose(out);
  56839. }
  56840. }
  56841. #endif
  56842. p->magic = VDBE_MAGIC_INIT;
  56843. return p->rc & db->errMask;
  56844. }
  56845. /*
  56846. ** Clean up and delete a VDBE after execution. Return an integer which is
  56847. ** the result code. Write any error message text into *pzErrMsg.
  56848. */
  56849. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  56850. int rc = SQLITE_OK;
  56851. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  56852. rc = sqlite3VdbeReset(p);
  56853. assert( (rc & p->db->errMask)==rc );
  56854. }
  56855. sqlite3VdbeDelete(p);
  56856. return rc;
  56857. }
  56858. /*
  56859. ** Call the destructor for each auxdata entry in pVdbeFunc for which
  56860. ** the corresponding bit in mask is clear. Auxdata entries beyond 31
  56861. ** are always destroyed. To destroy all auxdata entries, call this
  56862. ** routine with mask==0.
  56863. */
  56864. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  56865. int i;
  56866. for(i=0; i<pVdbeFunc->nAux; i++){
  56867. struct AuxData *pAux = &pVdbeFunc->apAux[i];
  56868. if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
  56869. if( pAux->xDelete ){
  56870. pAux->xDelete(pAux->pAux);
  56871. }
  56872. pAux->pAux = 0;
  56873. }
  56874. }
  56875. }
  56876. /*
  56877. ** Free all memory associated with the Vdbe passed as the second argument,
  56878. ** except for object itself, which is preserved.
  56879. **
  56880. ** The difference between this function and sqlite3VdbeDelete() is that
  56881. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  56882. ** the database connection and frees the object itself.
  56883. */
  56884. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  56885. SubProgram *pSub, *pNext;
  56886. int i;
  56887. assert( p->db==0 || p->db==db );
  56888. releaseMemArray(p->aVar, p->nVar);
  56889. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  56890. for(pSub=p->pProgram; pSub; pSub=pNext){
  56891. pNext = pSub->pNext;
  56892. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  56893. sqlite3DbFree(db, pSub);
  56894. }
  56895. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  56896. vdbeFreeOpArray(db, p->aOp, p->nOp);
  56897. sqlite3DbFree(db, p->aLabel);
  56898. sqlite3DbFree(db, p->aColName);
  56899. sqlite3DbFree(db, p->zSql);
  56900. sqlite3DbFree(db, p->pFree);
  56901. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  56902. sqlite3_free(p->zExplain);
  56903. sqlite3DbFree(db, p->pExplain);
  56904. #endif
  56905. }
  56906. /*
  56907. ** Delete an entire VDBE.
  56908. */
  56909. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  56910. sqlite3 *db;
  56911. if( NEVER(p==0) ) return;
  56912. db = p->db;
  56913. assert( sqlite3_mutex_held(db->mutex) );
  56914. sqlite3VdbeClearObject(db, p);
  56915. if( p->pPrev ){
  56916. p->pPrev->pNext = p->pNext;
  56917. }else{
  56918. assert( db->pVdbe==p );
  56919. db->pVdbe = p->pNext;
  56920. }
  56921. if( p->pNext ){
  56922. p->pNext->pPrev = p->pPrev;
  56923. }
  56924. p->magic = VDBE_MAGIC_DEAD;
  56925. p->db = 0;
  56926. sqlite3DbFree(db, p);
  56927. }
  56928. /*
  56929. ** Make sure the cursor p is ready to read or write the row to which it
  56930. ** was last positioned. Return an error code if an OOM fault or I/O error
  56931. ** prevents us from positioning the cursor to its correct position.
  56932. **
  56933. ** If a MoveTo operation is pending on the given cursor, then do that
  56934. ** MoveTo now. If no move is pending, check to see if the row has been
  56935. ** deleted out from under the cursor and if it has, mark the row as
  56936. ** a NULL row.
  56937. **
  56938. ** If the cursor is already pointing to the correct row and that row has
  56939. ** not been deleted out from under the cursor, then this routine is a no-op.
  56940. */
  56941. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  56942. if( p->deferredMoveto ){
  56943. int res, rc;
  56944. #ifdef SQLITE_TEST
  56945. extern int sqlite3_search_count;
  56946. #endif
  56947. assert( p->isTable );
  56948. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  56949. if( rc ) return rc;
  56950. p->lastRowid = p->movetoTarget;
  56951. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  56952. p->rowidIsValid = 1;
  56953. #ifdef SQLITE_TEST
  56954. sqlite3_search_count++;
  56955. #endif
  56956. p->deferredMoveto = 0;
  56957. p->cacheStatus = CACHE_STALE;
  56958. }else if( ALWAYS(p->pCursor) ){
  56959. int hasMoved;
  56960. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  56961. if( rc ) return rc;
  56962. if( hasMoved ){
  56963. p->cacheStatus = CACHE_STALE;
  56964. p->nullRow = 1;
  56965. }
  56966. }
  56967. return SQLITE_OK;
  56968. }
  56969. /*
  56970. ** The following functions:
  56971. **
  56972. ** sqlite3VdbeSerialType()
  56973. ** sqlite3VdbeSerialTypeLen()
  56974. ** sqlite3VdbeSerialLen()
  56975. ** sqlite3VdbeSerialPut()
  56976. ** sqlite3VdbeSerialGet()
  56977. **
  56978. ** encapsulate the code that serializes values for storage in SQLite
  56979. ** data and index records. Each serialized value consists of a
  56980. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  56981. ** integer, stored as a varint.
  56982. **
  56983. ** In an SQLite index record, the serial type is stored directly before
  56984. ** the blob of data that it corresponds to. In a table record, all serial
  56985. ** types are stored at the start of the record, and the blobs of data at
  56986. ** the end. Hence these functions allow the caller to handle the
  56987. ** serial-type and data blob seperately.
  56988. **
  56989. ** The following table describes the various storage classes for data:
  56990. **
  56991. ** serial type bytes of data type
  56992. ** -------------- --------------- ---------------
  56993. ** 0 0 NULL
  56994. ** 1 1 signed integer
  56995. ** 2 2 signed integer
  56996. ** 3 3 signed integer
  56997. ** 4 4 signed integer
  56998. ** 5 6 signed integer
  56999. ** 6 8 signed integer
  57000. ** 7 8 IEEE float
  57001. ** 8 0 Integer constant 0
  57002. ** 9 0 Integer constant 1
  57003. ** 10,11 reserved for expansion
  57004. ** N>=12 and even (N-12)/2 BLOB
  57005. ** N>=13 and odd (N-13)/2 text
  57006. **
  57007. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  57008. ** of SQLite will not understand those serial types.
  57009. */
  57010. /*
  57011. ** Return the serial-type for the value stored in pMem.
  57012. */
  57013. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  57014. int flags = pMem->flags;
  57015. int n;
  57016. if( flags&MEM_Null ){
  57017. return 0;
  57018. }
  57019. if( flags&MEM_Int ){
  57020. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  57021. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  57022. i64 i = pMem->u.i;
  57023. u64 u;
  57024. if( i<0 ){
  57025. if( i<(-MAX_6BYTE) ) return 6;
  57026. /* Previous test prevents: u = -(-9223372036854775808) */
  57027. u = -i;
  57028. }else{
  57029. u = i;
  57030. }
  57031. if( u<=127 ){
  57032. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  57033. }
  57034. if( u<=32767 ) return 2;
  57035. if( u<=8388607 ) return 3;
  57036. if( u<=2147483647 ) return 4;
  57037. if( u<=MAX_6BYTE ) return 5;
  57038. return 6;
  57039. }
  57040. if( flags&MEM_Real ){
  57041. return 7;
  57042. }
  57043. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  57044. n = pMem->n;
  57045. if( flags & MEM_Zero ){
  57046. n += pMem->u.nZero;
  57047. }
  57048. assert( n>=0 );
  57049. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  57050. }
  57051. /*
  57052. ** Return the length of the data corresponding to the supplied serial-type.
  57053. */
  57054. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  57055. if( serial_type>=12 ){
  57056. return (serial_type-12)/2;
  57057. }else{
  57058. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  57059. return aSize[serial_type];
  57060. }
  57061. }
  57062. /*
  57063. ** If we are on an architecture with mixed-endian floating
  57064. ** points (ex: ARM7) then swap the lower 4 bytes with the
  57065. ** upper 4 bytes. Return the result.
  57066. **
  57067. ** For most architectures, this is a no-op.
  57068. **
  57069. ** (later): It is reported to me that the mixed-endian problem
  57070. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  57071. ** that early versions of GCC stored the two words of a 64-bit
  57072. ** float in the wrong order. And that error has been propagated
  57073. ** ever since. The blame is not necessarily with GCC, though.
  57074. ** GCC might have just copying the problem from a prior compiler.
  57075. ** I am also told that newer versions of GCC that follow a different
  57076. ** ABI get the byte order right.
  57077. **
  57078. ** Developers using SQLite on an ARM7 should compile and run their
  57079. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  57080. ** enabled, some asserts below will ensure that the byte order of
  57081. ** floating point values is correct.
  57082. **
  57083. ** (2007-08-30) Frank van Vugt has studied this problem closely
  57084. ** and has send his findings to the SQLite developers. Frank
  57085. ** writes that some Linux kernels offer floating point hardware
  57086. ** emulation that uses only 32-bit mantissas instead of a full
  57087. ** 48-bits as required by the IEEE standard. (This is the
  57088. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  57089. ** byte swapping becomes very complicated. To avoid problems,
  57090. ** the necessary byte swapping is carried out using a 64-bit integer
  57091. ** rather than a 64-bit float. Frank assures us that the code here
  57092. ** works for him. We, the developers, have no way to independently
  57093. ** verify this, but Frank seems to know what he is talking about
  57094. ** so we trust him.
  57095. */
  57096. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  57097. static u64 floatSwap(u64 in){
  57098. union {
  57099. u64 r;
  57100. u32 i[2];
  57101. } u;
  57102. u32 t;
  57103. u.r = in;
  57104. t = u.i[0];
  57105. u.i[0] = u.i[1];
  57106. u.i[1] = t;
  57107. return u.r;
  57108. }
  57109. # define swapMixedEndianFloat(X) X = floatSwap(X)
  57110. #else
  57111. # define swapMixedEndianFloat(X)
  57112. #endif
  57113. /*
  57114. ** Write the serialized data blob for the value stored in pMem into
  57115. ** buf. It is assumed that the caller has allocated sufficient space.
  57116. ** Return the number of bytes written.
  57117. **
  57118. ** nBuf is the amount of space left in buf[]. nBuf must always be
  57119. ** large enough to hold the entire field. Except, if the field is
  57120. ** a blob with a zero-filled tail, then buf[] might be just the right
  57121. ** size to hold everything except for the zero-filled tail. If buf[]
  57122. ** is only big enough to hold the non-zero prefix, then only write that
  57123. ** prefix into buf[]. But if buf[] is large enough to hold both the
  57124. ** prefix and the tail then write the prefix and set the tail to all
  57125. ** zeros.
  57126. **
  57127. ** Return the number of bytes actually written into buf[]. The number
  57128. ** of bytes in the zero-filled tail is included in the return value only
  57129. ** if those bytes were zeroed in buf[].
  57130. */
  57131. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  57132. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  57133. u32 len;
  57134. /* Integer and Real */
  57135. if( serial_type<=7 && serial_type>0 ){
  57136. u64 v;
  57137. u32 i;
  57138. if( serial_type==7 ){
  57139. assert( sizeof(v)==sizeof(pMem->r) );
  57140. memcpy(&v, &pMem->r, sizeof(v));
  57141. swapMixedEndianFloat(v);
  57142. }else{
  57143. v = pMem->u.i;
  57144. }
  57145. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  57146. assert( len<=(u32)nBuf );
  57147. while( i-- ){
  57148. buf[i] = (u8)(v&0xFF);
  57149. v >>= 8;
  57150. }
  57151. return len;
  57152. }
  57153. /* String or blob */
  57154. if( serial_type>=12 ){
  57155. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  57156. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  57157. assert( pMem->n<=nBuf );
  57158. len = pMem->n;
  57159. memcpy(buf, pMem->z, len);
  57160. if( pMem->flags & MEM_Zero ){
  57161. len += pMem->u.nZero;
  57162. assert( nBuf>=0 );
  57163. if( len > (u32)nBuf ){
  57164. len = (u32)nBuf;
  57165. }
  57166. memset(&buf[pMem->n], 0, len-pMem->n);
  57167. }
  57168. return len;
  57169. }
  57170. /* NULL or constants 0 or 1 */
  57171. return 0;
  57172. }
  57173. /*
  57174. ** Deserialize the data blob pointed to by buf as serial type serial_type
  57175. ** and store the result in pMem. Return the number of bytes read.
  57176. */
  57177. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  57178. const unsigned char *buf, /* Buffer to deserialize from */
  57179. u32 serial_type, /* Serial type to deserialize */
  57180. Mem *pMem /* Memory cell to write value into */
  57181. ){
  57182. switch( serial_type ){
  57183. case 10: /* Reserved for future use */
  57184. case 11: /* Reserved for future use */
  57185. case 0: { /* NULL */
  57186. pMem->flags = MEM_Null;
  57187. break;
  57188. }
  57189. case 1: { /* 1-byte signed integer */
  57190. pMem->u.i = (signed char)buf[0];
  57191. pMem->flags = MEM_Int;
  57192. return 1;
  57193. }
  57194. case 2: { /* 2-byte signed integer */
  57195. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  57196. pMem->flags = MEM_Int;
  57197. return 2;
  57198. }
  57199. case 3: { /* 3-byte signed integer */
  57200. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  57201. pMem->flags = MEM_Int;
  57202. return 3;
  57203. }
  57204. case 4: { /* 4-byte signed integer */
  57205. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  57206. pMem->flags = MEM_Int;
  57207. return 4;
  57208. }
  57209. case 5: { /* 6-byte signed integer */
  57210. u64 x = (((signed char)buf[0])<<8) | buf[1];
  57211. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  57212. x = (x<<32) | y;
  57213. pMem->u.i = *(i64*)&x;
  57214. pMem->flags = MEM_Int;
  57215. return 6;
  57216. }
  57217. case 6: /* 8-byte signed integer */
  57218. case 7: { /* IEEE floating point */
  57219. u64 x;
  57220. u32 y;
  57221. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  57222. /* Verify that integers and floating point values use the same
  57223. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  57224. ** defined that 64-bit floating point values really are mixed
  57225. ** endian.
  57226. */
  57227. static const u64 t1 = ((u64)0x3ff00000)<<32;
  57228. static const double r1 = 1.0;
  57229. u64 t2 = t1;
  57230. swapMixedEndianFloat(t2);
  57231. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  57232. #endif
  57233. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  57234. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  57235. x = (x<<32) | y;
  57236. if( serial_type==6 ){
  57237. pMem->u.i = *(i64*)&x;
  57238. pMem->flags = MEM_Int;
  57239. }else{
  57240. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  57241. swapMixedEndianFloat(x);
  57242. memcpy(&pMem->r, &x, sizeof(x));
  57243. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  57244. }
  57245. return 8;
  57246. }
  57247. case 8: /* Integer 0 */
  57248. case 9: { /* Integer 1 */
  57249. pMem->u.i = serial_type-8;
  57250. pMem->flags = MEM_Int;
  57251. return 0;
  57252. }
  57253. default: {
  57254. u32 len = (serial_type-12)/2;
  57255. pMem->z = (char *)buf;
  57256. pMem->n = len;
  57257. pMem->xDel = 0;
  57258. if( serial_type&0x01 ){
  57259. pMem->flags = MEM_Str | MEM_Ephem;
  57260. }else{
  57261. pMem->flags = MEM_Blob | MEM_Ephem;
  57262. }
  57263. return len;
  57264. }
  57265. }
  57266. return 0;
  57267. }
  57268. /*
  57269. ** This routine is used to allocate sufficient space for an UnpackedRecord
  57270. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  57271. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  57272. **
  57273. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  57274. ** the unaligned buffer passed via the second and third arguments (presumably
  57275. ** stack space). If the former, then *ppFree is set to a pointer that should
  57276. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  57277. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  57278. ** before returning.
  57279. **
  57280. ** If an OOM error occurs, NULL is returned.
  57281. */
  57282. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  57283. KeyInfo *pKeyInfo, /* Description of the record */
  57284. char *pSpace, /* Unaligned space available */
  57285. int szSpace, /* Size of pSpace[] in bytes */
  57286. char **ppFree /* OUT: Caller should free this pointer */
  57287. ){
  57288. UnpackedRecord *p; /* Unpacked record to return */
  57289. int nOff; /* Increment pSpace by nOff to align it */
  57290. int nByte; /* Number of bytes required for *p */
  57291. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  57292. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  57293. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  57294. */
  57295. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  57296. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  57297. if( nByte>szSpace+nOff ){
  57298. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  57299. *ppFree = (char *)p;
  57300. if( !p ) return 0;
  57301. }else{
  57302. p = (UnpackedRecord*)&pSpace[nOff];
  57303. *ppFree = 0;
  57304. }
  57305. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  57306. assert( pKeyInfo->aSortOrder!=0 );
  57307. p->pKeyInfo = pKeyInfo;
  57308. p->nField = pKeyInfo->nField + 1;
  57309. return p;
  57310. }
  57311. /*
  57312. ** Given the nKey-byte encoding of a record in pKey[], populate the
  57313. ** UnpackedRecord structure indicated by the fourth argument with the
  57314. ** contents of the decoded record.
  57315. */
  57316. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  57317. KeyInfo *pKeyInfo, /* Information about the record format */
  57318. int nKey, /* Size of the binary record */
  57319. const void *pKey, /* The binary record */
  57320. UnpackedRecord *p /* Populate this structure before returning. */
  57321. ){
  57322. const unsigned char *aKey = (const unsigned char *)pKey;
  57323. int d;
  57324. u32 idx; /* Offset in aKey[] to read from */
  57325. u16 u; /* Unsigned loop counter */
  57326. u32 szHdr;
  57327. Mem *pMem = p->aMem;
  57328. p->flags = 0;
  57329. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57330. idx = getVarint32(aKey, szHdr);
  57331. d = szHdr;
  57332. u = 0;
  57333. while( idx<szHdr && u<p->nField && d<=nKey ){
  57334. u32 serial_type;
  57335. idx += getVarint32(&aKey[idx], serial_type);
  57336. pMem->enc = pKeyInfo->enc;
  57337. pMem->db = pKeyInfo->db;
  57338. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  57339. pMem->zMalloc = 0;
  57340. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  57341. pMem++;
  57342. u++;
  57343. }
  57344. assert( u<=pKeyInfo->nField + 1 );
  57345. p->nField = u;
  57346. }
  57347. /*
  57348. ** This function compares the two table rows or index records
  57349. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  57350. ** or positive integer if key1 is less than, equal to or
  57351. ** greater than key2. The {nKey1, pKey1} key must be a blob
  57352. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  57353. ** key must be a parsed key such as obtained from
  57354. ** sqlite3VdbeParseRecord.
  57355. **
  57356. ** Key1 and Key2 do not have to contain the same number of fields.
  57357. ** The key with fewer fields is usually compares less than the
  57358. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  57359. ** and the common prefixes are equal, then key1 is less than key2.
  57360. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  57361. ** equal, then the keys are considered to be equal and
  57362. ** the parts beyond the common prefix are ignored.
  57363. */
  57364. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  57365. int nKey1, const void *pKey1, /* Left key */
  57366. UnpackedRecord *pPKey2 /* Right key */
  57367. ){
  57368. int d1; /* Offset into aKey[] of next data element */
  57369. u32 idx1; /* Offset into aKey[] of next header element */
  57370. u32 szHdr1; /* Number of bytes in header */
  57371. int i = 0;
  57372. int nField;
  57373. int rc = 0;
  57374. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  57375. KeyInfo *pKeyInfo;
  57376. Mem mem1;
  57377. pKeyInfo = pPKey2->pKeyInfo;
  57378. mem1.enc = pKeyInfo->enc;
  57379. mem1.db = pKeyInfo->db;
  57380. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  57381. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  57382. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  57383. ** We could initialize it, as shown here, to silence those complaints.
  57384. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  57385. ** the unnecessary initialization has a measurable negative performance
  57386. ** impact, since this routine is a very high runner. And so, we choose
  57387. ** to ignore the compiler warnings and leave this variable uninitialized.
  57388. */
  57389. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  57390. idx1 = getVarint32(aKey1, szHdr1);
  57391. d1 = szHdr1;
  57392. nField = pKeyInfo->nField;
  57393. assert( pKeyInfo->aSortOrder!=0 );
  57394. while( idx1<szHdr1 && i<pPKey2->nField ){
  57395. u32 serial_type1;
  57396. /* Read the serial types for the next element in each key. */
  57397. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  57398. if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  57399. /* Extract the values to be compared.
  57400. */
  57401. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  57402. /* Do the comparison
  57403. */
  57404. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  57405. i<nField ? pKeyInfo->aColl[i] : 0);
  57406. if( rc!=0 ){
  57407. assert( mem1.zMalloc==0 ); /* See comment below */
  57408. /* Invert the result if we are using DESC sort order. */
  57409. if( i<nField && pKeyInfo->aSortOrder[i] ){
  57410. rc = -rc;
  57411. }
  57412. /* If the PREFIX_SEARCH flag is set and all fields except the final
  57413. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  57414. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  57415. ** This is used by the OP_IsUnique opcode.
  57416. */
  57417. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  57418. assert( idx1==szHdr1 && rc );
  57419. assert( mem1.flags & MEM_Int );
  57420. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  57421. pPKey2->rowid = mem1.u.i;
  57422. }
  57423. return rc;
  57424. }
  57425. i++;
  57426. }
  57427. /* No memory allocation is ever used on mem1. Prove this using
  57428. ** the following assert(). If the assert() fails, it indicates a
  57429. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  57430. */
  57431. assert( mem1.zMalloc==0 );
  57432. /* rc==0 here means that one of the keys ran out of fields and
  57433. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  57434. ** flag is set, then break the tie by treating key2 as larger.
  57435. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  57436. ** are considered to be equal. Otherwise, the longer key is the
  57437. ** larger. As it happens, the pPKey2 will always be the longer
  57438. ** if there is a difference.
  57439. */
  57440. assert( rc==0 );
  57441. if( pPKey2->flags & UNPACKED_INCRKEY ){
  57442. rc = -1;
  57443. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  57444. /* Leave rc==0 */
  57445. }else if( idx1<szHdr1 ){
  57446. rc = 1;
  57447. }
  57448. return rc;
  57449. }
  57450. /*
  57451. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  57452. ** Read the rowid (the last field in the record) and store it in *rowid.
  57453. ** Return SQLITE_OK if everything works, or an error code otherwise.
  57454. **
  57455. ** pCur might be pointing to text obtained from a corrupt database file.
  57456. ** So the content cannot be trusted. Do appropriate checks on the content.
  57457. */
  57458. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  57459. i64 nCellKey = 0;
  57460. int rc;
  57461. u32 szHdr; /* Size of the header */
  57462. u32 typeRowid; /* Serial type of the rowid */
  57463. u32 lenRowid; /* Size of the rowid */
  57464. Mem m, v;
  57465. UNUSED_PARAMETER(db);
  57466. /* Get the size of the index entry. Only indices entries of less
  57467. ** than 2GiB are support - anything large must be database corruption.
  57468. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  57469. ** this code can safely assume that nCellKey is 32-bits
  57470. */
  57471. assert( sqlite3BtreeCursorIsValid(pCur) );
  57472. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  57473. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  57474. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  57475. /* Read in the complete content of the index entry */
  57476. memset(&m, 0, sizeof(m));
  57477. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  57478. if( rc ){
  57479. return rc;
  57480. }
  57481. /* The index entry must begin with a header size */
  57482. (void)getVarint32((u8*)m.z, szHdr);
  57483. testcase( szHdr==3 );
  57484. testcase( szHdr==m.n );
  57485. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  57486. goto idx_rowid_corruption;
  57487. }
  57488. /* The last field of the index should be an integer - the ROWID.
  57489. ** Verify that the last entry really is an integer. */
  57490. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  57491. testcase( typeRowid==1 );
  57492. testcase( typeRowid==2 );
  57493. testcase( typeRowid==3 );
  57494. testcase( typeRowid==4 );
  57495. testcase( typeRowid==5 );
  57496. testcase( typeRowid==6 );
  57497. testcase( typeRowid==8 );
  57498. testcase( typeRowid==9 );
  57499. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  57500. goto idx_rowid_corruption;
  57501. }
  57502. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  57503. testcase( (u32)m.n==szHdr+lenRowid );
  57504. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  57505. goto idx_rowid_corruption;
  57506. }
  57507. /* Fetch the integer off the end of the index record */
  57508. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  57509. *rowid = v.u.i;
  57510. sqlite3VdbeMemRelease(&m);
  57511. return SQLITE_OK;
  57512. /* Jump here if database corruption is detected after m has been
  57513. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  57514. idx_rowid_corruption:
  57515. testcase( m.zMalloc!=0 );
  57516. sqlite3VdbeMemRelease(&m);
  57517. return SQLITE_CORRUPT_BKPT;
  57518. }
  57519. /*
  57520. ** Compare the key of the index entry that cursor pC is pointing to against
  57521. ** the key string in pUnpacked. Write into *pRes a number
  57522. ** that is negative, zero, or positive if pC is less than, equal to,
  57523. ** or greater than pUnpacked. Return SQLITE_OK on success.
  57524. **
  57525. ** pUnpacked is either created without a rowid or is truncated so that it
  57526. ** omits the rowid at the end. The rowid at the end of the index entry
  57527. ** is ignored as well. Hence, this routine only compares the prefixes
  57528. ** of the keys prior to the final rowid, not the entire key.
  57529. */
  57530. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  57531. VdbeCursor *pC, /* The cursor to compare against */
  57532. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  57533. int *res /* Write the comparison result here */
  57534. ){
  57535. i64 nCellKey = 0;
  57536. int rc;
  57537. BtCursor *pCur = pC->pCursor;
  57538. Mem m;
  57539. assert( sqlite3BtreeCursorIsValid(pCur) );
  57540. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  57541. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  57542. /* nCellKey will always be between 0 and 0xffffffff because of the say
  57543. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  57544. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  57545. *res = 0;
  57546. return SQLITE_CORRUPT_BKPT;
  57547. }
  57548. memset(&m, 0, sizeof(m));
  57549. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  57550. if( rc ){
  57551. return rc;
  57552. }
  57553. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  57554. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  57555. sqlite3VdbeMemRelease(&m);
  57556. return SQLITE_OK;
  57557. }
  57558. /*
  57559. ** This routine sets the value to be returned by subsequent calls to
  57560. ** sqlite3_changes() on the database handle 'db'.
  57561. */
  57562. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  57563. assert( sqlite3_mutex_held(db->mutex) );
  57564. db->nChange = nChange;
  57565. db->nTotalChange += nChange;
  57566. }
  57567. /*
  57568. ** Set a flag in the vdbe to update the change counter when it is finalised
  57569. ** or reset.
  57570. */
  57571. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  57572. v->changeCntOn = 1;
  57573. }
  57574. /*
  57575. ** Mark every prepared statement associated with a database connection
  57576. ** as expired.
  57577. **
  57578. ** An expired statement means that recompilation of the statement is
  57579. ** recommend. Statements expire when things happen that make their
  57580. ** programs obsolete. Removing user-defined functions or collating
  57581. ** sequences, or changing an authorization function are the types of
  57582. ** things that make prepared statements obsolete.
  57583. */
  57584. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  57585. Vdbe *p;
  57586. for(p = db->pVdbe; p; p=p->pNext){
  57587. p->expired = 1;
  57588. }
  57589. }
  57590. /*
  57591. ** Return the database associated with the Vdbe.
  57592. */
  57593. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  57594. return v->db;
  57595. }
  57596. /*
  57597. ** Return a pointer to an sqlite3_value structure containing the value bound
  57598. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  57599. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  57600. ** constants) to the value before returning it.
  57601. **
  57602. ** The returned value must be freed by the caller using sqlite3ValueFree().
  57603. */
  57604. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
  57605. assert( iVar>0 );
  57606. if( v ){
  57607. Mem *pMem = &v->aVar[iVar-1];
  57608. if( 0==(pMem->flags & MEM_Null) ){
  57609. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  57610. if( pRet ){
  57611. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  57612. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  57613. sqlite3VdbeMemStoreType((Mem *)pRet);
  57614. }
  57615. return pRet;
  57616. }
  57617. }
  57618. return 0;
  57619. }
  57620. /*
  57621. ** Configure SQL variable iVar so that binding a new value to it signals
  57622. ** to sqlite3_reoptimize() that re-preparing the statement may result
  57623. ** in a better query plan.
  57624. */
  57625. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  57626. assert( iVar>0 );
  57627. if( iVar>32 ){
  57628. v->expmask = 0xffffffff;
  57629. }else{
  57630. v->expmask |= ((u32)1 << (iVar-1));
  57631. }
  57632. }
  57633. /************** End of vdbeaux.c *********************************************/
  57634. /************** Begin file vdbeapi.c *****************************************/
  57635. /*
  57636. ** 2004 May 26
  57637. **
  57638. ** The author disclaims copyright to this source code. In place of
  57639. ** a legal notice, here is a blessing:
  57640. **
  57641. ** May you do good and not evil.
  57642. ** May you find forgiveness for yourself and forgive others.
  57643. ** May you share freely, never taking more than you give.
  57644. **
  57645. *************************************************************************
  57646. **
  57647. ** This file contains code use to implement APIs that are part of the
  57648. ** VDBE.
  57649. */
  57650. #ifndef SQLITE_OMIT_DEPRECATED
  57651. /*
  57652. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  57653. ** to be recompiled. A statement needs to be recompiled whenever the
  57654. ** execution environment changes in a way that would alter the program
  57655. ** that sqlite3_prepare() generates. For example, if new functions or
  57656. ** collating sequences are registered or if an authorizer function is
  57657. ** added or changed.
  57658. */
  57659. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  57660. Vdbe *p = (Vdbe*)pStmt;
  57661. return p==0 || p->expired;
  57662. }
  57663. #endif
  57664. /*
  57665. ** Check on a Vdbe to make sure it has not been finalized. Log
  57666. ** an error and return true if it has been finalized (or is otherwise
  57667. ** invalid). Return false if it is ok.
  57668. */
  57669. static int vdbeSafety(Vdbe *p){
  57670. if( p->db==0 ){
  57671. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  57672. return 1;
  57673. }else{
  57674. return 0;
  57675. }
  57676. }
  57677. static int vdbeSafetyNotNull(Vdbe *p){
  57678. if( p==0 ){
  57679. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  57680. return 1;
  57681. }else{
  57682. return vdbeSafety(p);
  57683. }
  57684. }
  57685. /*
  57686. ** The following routine destroys a virtual machine that is created by
  57687. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  57688. ** success/failure code that describes the result of executing the virtual
  57689. ** machine.
  57690. **
  57691. ** This routine sets the error code and string returned by
  57692. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  57693. */
  57694. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  57695. int rc;
  57696. if( pStmt==0 ){
  57697. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  57698. ** pointer is a harmless no-op. */
  57699. rc = SQLITE_OK;
  57700. }else{
  57701. Vdbe *v = (Vdbe*)pStmt;
  57702. sqlite3 *db = v->db;
  57703. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  57704. sqlite3_mutex_enter(db->mutex);
  57705. rc = sqlite3VdbeFinalize(v);
  57706. rc = sqlite3ApiExit(db, rc);
  57707. sqlite3LeaveMutexAndCloseZombie(db);
  57708. }
  57709. return rc;
  57710. }
  57711. /*
  57712. ** Terminate the current execution of an SQL statement and reset it
  57713. ** back to its starting state so that it can be reused. A success code from
  57714. ** the prior execution is returned.
  57715. **
  57716. ** This routine sets the error code and string returned by
  57717. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  57718. */
  57719. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  57720. int rc;
  57721. if( pStmt==0 ){
  57722. rc = SQLITE_OK;
  57723. }else{
  57724. Vdbe *v = (Vdbe*)pStmt;
  57725. sqlite3_mutex_enter(v->db->mutex);
  57726. rc = sqlite3VdbeReset(v);
  57727. sqlite3VdbeRewind(v);
  57728. assert( (rc & (v->db->errMask))==rc );
  57729. rc = sqlite3ApiExit(v->db, rc);
  57730. sqlite3_mutex_leave(v->db->mutex);
  57731. }
  57732. return rc;
  57733. }
  57734. /*
  57735. ** Set all the parameters in the compiled SQL statement to NULL.
  57736. */
  57737. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  57738. int i;
  57739. int rc = SQLITE_OK;
  57740. Vdbe *p = (Vdbe*)pStmt;
  57741. #if SQLITE_THREADSAFE
  57742. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  57743. #endif
  57744. sqlite3_mutex_enter(mutex);
  57745. for(i=0; i<p->nVar; i++){
  57746. sqlite3VdbeMemRelease(&p->aVar[i]);
  57747. p->aVar[i].flags = MEM_Null;
  57748. }
  57749. if( p->isPrepareV2 && p->expmask ){
  57750. p->expired = 1;
  57751. }
  57752. sqlite3_mutex_leave(mutex);
  57753. return rc;
  57754. }
  57755. /**************************** sqlite3_value_ *******************************
  57756. ** The following routines extract information from a Mem or sqlite3_value
  57757. ** structure.
  57758. */
  57759. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  57760. Mem *p = (Mem*)pVal;
  57761. if( p->flags & (MEM_Blob|MEM_Str) ){
  57762. sqlite3VdbeMemExpandBlob(p);
  57763. p->flags &= ~MEM_Str;
  57764. p->flags |= MEM_Blob;
  57765. return p->n ? p->z : 0;
  57766. }else{
  57767. return sqlite3_value_text(pVal);
  57768. }
  57769. }
  57770. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  57771. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  57772. }
  57773. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  57774. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  57775. }
  57776. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  57777. return sqlite3VdbeRealValue((Mem*)pVal);
  57778. }
  57779. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  57780. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  57781. }
  57782. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  57783. return sqlite3VdbeIntValue((Mem*)pVal);
  57784. }
  57785. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  57786. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  57787. }
  57788. #ifndef SQLITE_OMIT_UTF16
  57789. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  57790. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  57791. }
  57792. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  57793. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  57794. }
  57795. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  57796. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  57797. }
  57798. #endif /* SQLITE_OMIT_UTF16 */
  57799. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  57800. return pVal->type;
  57801. }
  57802. /**************************** sqlite3_result_ *******************************
  57803. ** The following routines are used by user-defined functions to specify
  57804. ** the function result.
  57805. **
  57806. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  57807. ** result as a string or blob but if the string or blob is too large, it
  57808. ** then sets the error code to SQLITE_TOOBIG
  57809. */
  57810. static void setResultStrOrError(
  57811. sqlite3_context *pCtx, /* Function context */
  57812. const char *z, /* String pointer */
  57813. int n, /* Bytes in string, or negative */
  57814. u8 enc, /* Encoding of z. 0 for BLOBs */
  57815. void (*xDel)(void*) /* Destructor function */
  57816. ){
  57817. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  57818. sqlite3_result_error_toobig(pCtx);
  57819. }
  57820. }
  57821. SQLITE_API void sqlite3_result_blob(
  57822. sqlite3_context *pCtx,
  57823. const void *z,
  57824. int n,
  57825. void (*xDel)(void *)
  57826. ){
  57827. assert( n>=0 );
  57828. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57829. setResultStrOrError(pCtx, z, n, 0, xDel);
  57830. }
  57831. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  57832. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57833. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  57834. }
  57835. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  57836. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57837. pCtx->isError = SQLITE_ERROR;
  57838. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  57839. }
  57840. #ifndef SQLITE_OMIT_UTF16
  57841. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  57842. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57843. pCtx->isError = SQLITE_ERROR;
  57844. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  57845. }
  57846. #endif
  57847. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  57848. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57849. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  57850. }
  57851. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  57852. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57853. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  57854. }
  57855. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  57856. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57857. sqlite3VdbeMemSetNull(&pCtx->s);
  57858. }
  57859. SQLITE_API void sqlite3_result_text(
  57860. sqlite3_context *pCtx,
  57861. const char *z,
  57862. int n,
  57863. void (*xDel)(void *)
  57864. ){
  57865. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57866. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  57867. }
  57868. #ifndef SQLITE_OMIT_UTF16
  57869. SQLITE_API void sqlite3_result_text16(
  57870. sqlite3_context *pCtx,
  57871. const void *z,
  57872. int n,
  57873. void (*xDel)(void *)
  57874. ){
  57875. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57876. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  57877. }
  57878. SQLITE_API void sqlite3_result_text16be(
  57879. sqlite3_context *pCtx,
  57880. const void *z,
  57881. int n,
  57882. void (*xDel)(void *)
  57883. ){
  57884. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57885. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  57886. }
  57887. SQLITE_API void sqlite3_result_text16le(
  57888. sqlite3_context *pCtx,
  57889. const void *z,
  57890. int n,
  57891. void (*xDel)(void *)
  57892. ){
  57893. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57894. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  57895. }
  57896. #endif /* SQLITE_OMIT_UTF16 */
  57897. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  57898. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57899. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  57900. }
  57901. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  57902. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57903. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  57904. }
  57905. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  57906. pCtx->isError = errCode;
  57907. if( pCtx->s.flags & MEM_Null ){
  57908. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  57909. SQLITE_UTF8, SQLITE_STATIC);
  57910. }
  57911. }
  57912. /* Force an SQLITE_TOOBIG error. */
  57913. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  57914. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57915. pCtx->isError = SQLITE_TOOBIG;
  57916. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  57917. SQLITE_UTF8, SQLITE_STATIC);
  57918. }
  57919. /* An SQLITE_NOMEM error. */
  57920. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  57921. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  57922. sqlite3VdbeMemSetNull(&pCtx->s);
  57923. pCtx->isError = SQLITE_NOMEM;
  57924. pCtx->s.db->mallocFailed = 1;
  57925. }
  57926. /*
  57927. ** This function is called after a transaction has been committed. It
  57928. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  57929. */
  57930. static int doWalCallbacks(sqlite3 *db){
  57931. int rc = SQLITE_OK;
  57932. #ifndef SQLITE_OMIT_WAL
  57933. int i;
  57934. for(i=0; i<db->nDb; i++){
  57935. Btree *pBt = db->aDb[i].pBt;
  57936. if( pBt ){
  57937. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  57938. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  57939. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  57940. }
  57941. }
  57942. }
  57943. #endif
  57944. return rc;
  57945. }
  57946. /*
  57947. ** Execute the statement pStmt, either until a row of data is ready, the
  57948. ** statement is completely executed or an error occurs.
  57949. **
  57950. ** This routine implements the bulk of the logic behind the sqlite_step()
  57951. ** API. The only thing omitted is the automatic recompile if a
  57952. ** schema change has occurred. That detail is handled by the
  57953. ** outer sqlite3_step() wrapper procedure.
  57954. */
  57955. static int sqlite3Step(Vdbe *p){
  57956. sqlite3 *db;
  57957. int rc;
  57958. assert(p);
  57959. if( p->magic!=VDBE_MAGIC_RUN ){
  57960. /* We used to require that sqlite3_reset() be called before retrying
  57961. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  57962. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  57963. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  57964. ** This "automatic-reset" change is not technically an incompatibility,
  57965. ** since any application that receives an SQLITE_MISUSE is broken by
  57966. ** definition.
  57967. **
  57968. ** Nevertheless, some published applications that were originally written
  57969. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  57970. ** returns, and those were broken by the automatic-reset change. As a
  57971. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  57972. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  57973. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  57974. ** or SQLITE_BUSY error.
  57975. */
  57976. #ifdef SQLITE_OMIT_AUTORESET
  57977. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  57978. sqlite3_reset((sqlite3_stmt*)p);
  57979. }else{
  57980. return SQLITE_MISUSE_BKPT;
  57981. }
  57982. #else
  57983. sqlite3_reset((sqlite3_stmt*)p);
  57984. #endif
  57985. }
  57986. /* Check that malloc() has not failed. If it has, return early. */
  57987. db = p->db;
  57988. if( db->mallocFailed ){
  57989. p->rc = SQLITE_NOMEM;
  57990. return SQLITE_NOMEM;
  57991. }
  57992. if( p->pc<=0 && p->expired ){
  57993. p->rc = SQLITE_SCHEMA;
  57994. rc = SQLITE_ERROR;
  57995. goto end_of_step;
  57996. }
  57997. if( p->pc<0 ){
  57998. /* If there are no other statements currently running, then
  57999. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  58000. ** from interrupting a statement that has not yet started.
  58001. */
  58002. if( db->activeVdbeCnt==0 ){
  58003. db->u1.isInterrupted = 0;
  58004. }
  58005. assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
  58006. #ifndef SQLITE_OMIT_TRACE
  58007. if( db->xProfile && !db->init.busy ){
  58008. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  58009. }
  58010. #endif
  58011. db->activeVdbeCnt++;
  58012. if( p->readOnly==0 ) db->writeVdbeCnt++;
  58013. p->pc = 0;
  58014. }
  58015. #ifndef SQLITE_OMIT_EXPLAIN
  58016. if( p->explain ){
  58017. rc = sqlite3VdbeList(p);
  58018. }else
  58019. #endif /* SQLITE_OMIT_EXPLAIN */
  58020. {
  58021. db->vdbeExecCnt++;
  58022. rc = sqlite3VdbeExec(p);
  58023. db->vdbeExecCnt--;
  58024. }
  58025. #ifndef SQLITE_OMIT_TRACE
  58026. /* Invoke the profile callback if there is one
  58027. */
  58028. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  58029. sqlite3_int64 iNow;
  58030. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  58031. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  58032. }
  58033. #endif
  58034. if( rc==SQLITE_DONE ){
  58035. assert( p->rc==SQLITE_OK );
  58036. p->rc = doWalCallbacks(db);
  58037. if( p->rc!=SQLITE_OK ){
  58038. rc = SQLITE_ERROR;
  58039. }
  58040. }
  58041. db->errCode = rc;
  58042. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  58043. p->rc = SQLITE_NOMEM;
  58044. }
  58045. end_of_step:
  58046. /* At this point local variable rc holds the value that should be
  58047. ** returned if this statement was compiled using the legacy
  58048. ** sqlite3_prepare() interface. According to the docs, this can only
  58049. ** be one of the values in the first assert() below. Variable p->rc
  58050. ** contains the value that would be returned if sqlite3_finalize()
  58051. ** were called on statement p.
  58052. */
  58053. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  58054. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  58055. );
  58056. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  58057. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  58058. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  58059. ** error has occured, then return the error code in p->rc to the
  58060. ** caller. Set the error code in the database handle to the same value.
  58061. */
  58062. rc = sqlite3VdbeTransferError(p);
  58063. }
  58064. return (rc&db->errMask);
  58065. }
  58066. /*
  58067. ** The maximum number of times that a statement will try to reparse
  58068. ** itself before giving up and returning SQLITE_SCHEMA.
  58069. */
  58070. #ifndef SQLITE_MAX_SCHEMA_RETRY
  58071. # define SQLITE_MAX_SCHEMA_RETRY 5
  58072. #endif
  58073. /*
  58074. ** This is the top-level implementation of sqlite3_step(). Call
  58075. ** sqlite3Step() to do most of the work. If a schema error occurs,
  58076. ** call sqlite3Reprepare() and try again.
  58077. */
  58078. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  58079. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  58080. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  58081. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  58082. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  58083. sqlite3 *db; /* The database connection */
  58084. if( vdbeSafetyNotNull(v) ){
  58085. return SQLITE_MISUSE_BKPT;
  58086. }
  58087. db = v->db;
  58088. sqlite3_mutex_enter(db->mutex);
  58089. v->doingRerun = 0;
  58090. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  58091. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  58092. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  58093. sqlite3_reset(pStmt);
  58094. v->doingRerun = 1;
  58095. assert( v->expired==0 );
  58096. }
  58097. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  58098. /* This case occurs after failing to recompile an sql statement.
  58099. ** The error message from the SQL compiler has already been loaded
  58100. ** into the database handle. This block copies the error message
  58101. ** from the database handle into the statement and sets the statement
  58102. ** program counter to 0 to ensure that when the statement is
  58103. ** finalized or reset the parser error message is available via
  58104. ** sqlite3_errmsg() and sqlite3_errcode().
  58105. */
  58106. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  58107. sqlite3DbFree(db, v->zErrMsg);
  58108. if( !db->mallocFailed ){
  58109. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  58110. v->rc = rc2;
  58111. } else {
  58112. v->zErrMsg = 0;
  58113. v->rc = rc = SQLITE_NOMEM;
  58114. }
  58115. }
  58116. rc = sqlite3ApiExit(db, rc);
  58117. sqlite3_mutex_leave(db->mutex);
  58118. return rc;
  58119. }
  58120. /*
  58121. ** Extract the user data from a sqlite3_context structure and return a
  58122. ** pointer to it.
  58123. */
  58124. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  58125. assert( p && p->pFunc );
  58126. return p->pFunc->pUserData;
  58127. }
  58128. /*
  58129. ** Extract the user data from a sqlite3_context structure and return a
  58130. ** pointer to it.
  58131. **
  58132. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  58133. ** returns a copy of the pointer to the database connection (the 1st
  58134. ** parameter) of the sqlite3_create_function() and
  58135. ** sqlite3_create_function16() routines that originally registered the
  58136. ** application defined function.
  58137. */
  58138. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  58139. assert( p && p->pFunc );
  58140. return p->s.db;
  58141. }
  58142. /*
  58143. ** The following is the implementation of an SQL function that always
  58144. ** fails with an error message stating that the function is used in the
  58145. ** wrong context. The sqlite3_overload_function() API might construct
  58146. ** SQL function that use this routine so that the functions will exist
  58147. ** for name resolution but are actually overloaded by the xFindFunction
  58148. ** method of virtual tables.
  58149. */
  58150. SQLITE_PRIVATE void sqlite3InvalidFunction(
  58151. sqlite3_context *context, /* The function calling context */
  58152. int NotUsed, /* Number of arguments to the function */
  58153. sqlite3_value **NotUsed2 /* Value of each argument */
  58154. ){
  58155. const char *zName = context->pFunc->zName;
  58156. char *zErr;
  58157. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  58158. zErr = sqlite3_mprintf(
  58159. "unable to use function %s in the requested context", zName);
  58160. sqlite3_result_error(context, zErr, -1);
  58161. sqlite3_free(zErr);
  58162. }
  58163. /*
  58164. ** Allocate or return the aggregate context for a user function. A new
  58165. ** context is allocated on the first call. Subsequent calls return the
  58166. ** same context that was returned on prior calls.
  58167. */
  58168. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  58169. Mem *pMem;
  58170. assert( p && p->pFunc && p->pFunc->xStep );
  58171. assert( sqlite3_mutex_held(p->s.db->mutex) );
  58172. pMem = p->pMem;
  58173. testcase( nByte<0 );
  58174. if( (pMem->flags & MEM_Agg)==0 ){
  58175. if( nByte<=0 ){
  58176. sqlite3VdbeMemReleaseExternal(pMem);
  58177. pMem->flags = MEM_Null;
  58178. pMem->z = 0;
  58179. }else{
  58180. sqlite3VdbeMemGrow(pMem, nByte, 0);
  58181. pMem->flags = MEM_Agg;
  58182. pMem->u.pDef = p->pFunc;
  58183. if( pMem->z ){
  58184. memset(pMem->z, 0, nByte);
  58185. }
  58186. }
  58187. }
  58188. return (void*)pMem->z;
  58189. }
  58190. /*
  58191. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  58192. ** the user-function defined by pCtx.
  58193. */
  58194. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  58195. VdbeFunc *pVdbeFunc;
  58196. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  58197. pVdbeFunc = pCtx->pVdbeFunc;
  58198. if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
  58199. return 0;
  58200. }
  58201. return pVdbeFunc->apAux[iArg].pAux;
  58202. }
  58203. /*
  58204. ** Set the auxilary data pointer and delete function, for the iArg'th
  58205. ** argument to the user-function defined by pCtx. Any previous value is
  58206. ** deleted by calling the delete function specified when it was set.
  58207. */
  58208. SQLITE_API void sqlite3_set_auxdata(
  58209. sqlite3_context *pCtx,
  58210. int iArg,
  58211. void *pAux,
  58212. void (*xDelete)(void*)
  58213. ){
  58214. struct AuxData *pAuxData;
  58215. VdbeFunc *pVdbeFunc;
  58216. if( iArg<0 ) goto failed;
  58217. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  58218. pVdbeFunc = pCtx->pVdbeFunc;
  58219. if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
  58220. int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
  58221. int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
  58222. pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
  58223. if( !pVdbeFunc ){
  58224. goto failed;
  58225. }
  58226. pCtx->pVdbeFunc = pVdbeFunc;
  58227. memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
  58228. pVdbeFunc->nAux = iArg+1;
  58229. pVdbeFunc->pFunc = pCtx->pFunc;
  58230. }
  58231. pAuxData = &pVdbeFunc->apAux[iArg];
  58232. if( pAuxData->pAux && pAuxData->xDelete ){
  58233. pAuxData->xDelete(pAuxData->pAux);
  58234. }
  58235. pAuxData->pAux = pAux;
  58236. pAuxData->xDelete = xDelete;
  58237. return;
  58238. failed:
  58239. if( xDelete ){
  58240. xDelete(pAux);
  58241. }
  58242. }
  58243. #ifndef SQLITE_OMIT_DEPRECATED
  58244. /*
  58245. ** Return the number of times the Step function of a aggregate has been
  58246. ** called.
  58247. **
  58248. ** This function is deprecated. Do not use it for new code. It is
  58249. ** provide only to avoid breaking legacy code. New aggregate function
  58250. ** implementations should keep their own counts within their aggregate
  58251. ** context.
  58252. */
  58253. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  58254. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  58255. return p->pMem->n;
  58256. }
  58257. #endif
  58258. /*
  58259. ** Return the number of columns in the result set for the statement pStmt.
  58260. */
  58261. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  58262. Vdbe *pVm = (Vdbe *)pStmt;
  58263. return pVm ? pVm->nResColumn : 0;
  58264. }
  58265. /*
  58266. ** Return the number of values available from the current row of the
  58267. ** currently executing statement pStmt.
  58268. */
  58269. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  58270. Vdbe *pVm = (Vdbe *)pStmt;
  58271. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  58272. return pVm->nResColumn;
  58273. }
  58274. /*
  58275. ** Check to see if column iCol of the given statement is valid. If
  58276. ** it is, return a pointer to the Mem for the value of that column.
  58277. ** If iCol is not valid, return a pointer to a Mem which has a value
  58278. ** of NULL.
  58279. */
  58280. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  58281. Vdbe *pVm;
  58282. Mem *pOut;
  58283. pVm = (Vdbe *)pStmt;
  58284. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  58285. sqlite3_mutex_enter(pVm->db->mutex);
  58286. pOut = &pVm->pResultSet[i];
  58287. }else{
  58288. /* If the value passed as the second argument is out of range, return
  58289. ** a pointer to the following static Mem object which contains the
  58290. ** value SQL NULL. Even though the Mem structure contains an element
  58291. ** of type i64, on certain architectures (x86) with certain compiler
  58292. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  58293. ** instead of an 8-byte one. This all works fine, except that when
  58294. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  58295. ** that a Mem structure is located on an 8-byte boundary. To prevent
  58296. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  58297. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  58298. ** __attribute__((aligned(8))) macro. */
  58299. static const Mem nullMem
  58300. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  58301. __attribute__((aligned(8)))
  58302. #endif
  58303. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  58304. #ifdef SQLITE_DEBUG
  58305. 0, 0, /* pScopyFrom, pFiller */
  58306. #endif
  58307. 0, 0 };
  58308. if( pVm && ALWAYS(pVm->db) ){
  58309. sqlite3_mutex_enter(pVm->db->mutex);
  58310. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  58311. }
  58312. pOut = (Mem*)&nullMem;
  58313. }
  58314. return pOut;
  58315. }
  58316. /*
  58317. ** This function is called after invoking an sqlite3_value_XXX function on a
  58318. ** column value (i.e. a value returned by evaluating an SQL expression in the
  58319. ** select list of a SELECT statement) that may cause a malloc() failure. If
  58320. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  58321. ** code of statement pStmt set to SQLITE_NOMEM.
  58322. **
  58323. ** Specifically, this is called from within:
  58324. **
  58325. ** sqlite3_column_int()
  58326. ** sqlite3_column_int64()
  58327. ** sqlite3_column_text()
  58328. ** sqlite3_column_text16()
  58329. ** sqlite3_column_real()
  58330. ** sqlite3_column_bytes()
  58331. ** sqlite3_column_bytes16()
  58332. ** sqiite3_column_blob()
  58333. */
  58334. static void columnMallocFailure(sqlite3_stmt *pStmt)
  58335. {
  58336. /* If malloc() failed during an encoding conversion within an
  58337. ** sqlite3_column_XXX API, then set the return code of the statement to
  58338. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  58339. ** and _finalize() will return NOMEM.
  58340. */
  58341. Vdbe *p = (Vdbe *)pStmt;
  58342. if( p ){
  58343. p->rc = sqlite3ApiExit(p->db, p->rc);
  58344. sqlite3_mutex_leave(p->db->mutex);
  58345. }
  58346. }
  58347. /**************************** sqlite3_column_ *******************************
  58348. ** The following routines are used to access elements of the current row
  58349. ** in the result set.
  58350. */
  58351. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  58352. const void *val;
  58353. val = sqlite3_value_blob( columnMem(pStmt,i) );
  58354. /* Even though there is no encoding conversion, value_blob() might
  58355. ** need to call malloc() to expand the result of a zeroblob()
  58356. ** expression.
  58357. */
  58358. columnMallocFailure(pStmt);
  58359. return val;
  58360. }
  58361. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  58362. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  58363. columnMallocFailure(pStmt);
  58364. return val;
  58365. }
  58366. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  58367. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  58368. columnMallocFailure(pStmt);
  58369. return val;
  58370. }
  58371. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  58372. double val = sqlite3_value_double( columnMem(pStmt,i) );
  58373. columnMallocFailure(pStmt);
  58374. return val;
  58375. }
  58376. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  58377. int val = sqlite3_value_int( columnMem(pStmt,i) );
  58378. columnMallocFailure(pStmt);
  58379. return val;
  58380. }
  58381. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  58382. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  58383. columnMallocFailure(pStmt);
  58384. return val;
  58385. }
  58386. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  58387. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  58388. columnMallocFailure(pStmt);
  58389. return val;
  58390. }
  58391. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  58392. Mem *pOut = columnMem(pStmt, i);
  58393. if( pOut->flags&MEM_Static ){
  58394. pOut->flags &= ~MEM_Static;
  58395. pOut->flags |= MEM_Ephem;
  58396. }
  58397. columnMallocFailure(pStmt);
  58398. return (sqlite3_value *)pOut;
  58399. }
  58400. #ifndef SQLITE_OMIT_UTF16
  58401. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  58402. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  58403. columnMallocFailure(pStmt);
  58404. return val;
  58405. }
  58406. #endif /* SQLITE_OMIT_UTF16 */
  58407. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  58408. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  58409. columnMallocFailure(pStmt);
  58410. return iType;
  58411. }
  58412. /* The following function is experimental and subject to change or
  58413. ** removal */
  58414. /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
  58415. ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
  58416. **}
  58417. */
  58418. /*
  58419. ** Convert the N-th element of pStmt->pColName[] into a string using
  58420. ** xFunc() then return that string. If N is out of range, return 0.
  58421. **
  58422. ** There are up to 5 names for each column. useType determines which
  58423. ** name is returned. Here are the names:
  58424. **
  58425. ** 0 The column name as it should be displayed for output
  58426. ** 1 The datatype name for the column
  58427. ** 2 The name of the database that the column derives from
  58428. ** 3 The name of the table that the column derives from
  58429. ** 4 The name of the table column that the result column derives from
  58430. **
  58431. ** If the result is not a simple column reference (if it is an expression
  58432. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  58433. */
  58434. static const void *columnName(
  58435. sqlite3_stmt *pStmt,
  58436. int N,
  58437. const void *(*xFunc)(Mem*),
  58438. int useType
  58439. ){
  58440. const void *ret = 0;
  58441. Vdbe *p = (Vdbe *)pStmt;
  58442. int n;
  58443. sqlite3 *db = p->db;
  58444. assert( db!=0 );
  58445. n = sqlite3_column_count(pStmt);
  58446. if( N<n && N>=0 ){
  58447. N += useType*n;
  58448. sqlite3_mutex_enter(db->mutex);
  58449. assert( db->mallocFailed==0 );
  58450. ret = xFunc(&p->aColName[N]);
  58451. /* A malloc may have failed inside of the xFunc() call. If this
  58452. ** is the case, clear the mallocFailed flag and return NULL.
  58453. */
  58454. if( db->mallocFailed ){
  58455. db->mallocFailed = 0;
  58456. ret = 0;
  58457. }
  58458. sqlite3_mutex_leave(db->mutex);
  58459. }
  58460. return ret;
  58461. }
  58462. /*
  58463. ** Return the name of the Nth column of the result set returned by SQL
  58464. ** statement pStmt.
  58465. */
  58466. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  58467. return columnName(
  58468. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  58469. }
  58470. #ifndef SQLITE_OMIT_UTF16
  58471. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  58472. return columnName(
  58473. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  58474. }
  58475. #endif
  58476. /*
  58477. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  58478. ** not define OMIT_DECLTYPE.
  58479. */
  58480. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  58481. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  58482. and SQLITE_ENABLE_COLUMN_METADATA"
  58483. #endif
  58484. #ifndef SQLITE_OMIT_DECLTYPE
  58485. /*
  58486. ** Return the column declaration type (if applicable) of the 'i'th column
  58487. ** of the result set of SQL statement pStmt.
  58488. */
  58489. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  58490. return columnName(
  58491. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  58492. }
  58493. #ifndef SQLITE_OMIT_UTF16
  58494. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  58495. return columnName(
  58496. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  58497. }
  58498. #endif /* SQLITE_OMIT_UTF16 */
  58499. #endif /* SQLITE_OMIT_DECLTYPE */
  58500. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  58501. /*
  58502. ** Return the name of the database from which a result column derives.
  58503. ** NULL is returned if the result column is an expression or constant or
  58504. ** anything else which is not an unabiguous reference to a database column.
  58505. */
  58506. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  58507. return columnName(
  58508. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  58509. }
  58510. #ifndef SQLITE_OMIT_UTF16
  58511. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  58512. return columnName(
  58513. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  58514. }
  58515. #endif /* SQLITE_OMIT_UTF16 */
  58516. /*
  58517. ** Return the name of the table from which a result column derives.
  58518. ** NULL is returned if the result column is an expression or constant or
  58519. ** anything else which is not an unabiguous reference to a database column.
  58520. */
  58521. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  58522. return columnName(
  58523. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  58524. }
  58525. #ifndef SQLITE_OMIT_UTF16
  58526. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  58527. return columnName(
  58528. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  58529. }
  58530. #endif /* SQLITE_OMIT_UTF16 */
  58531. /*
  58532. ** Return the name of the table column from which a result column derives.
  58533. ** NULL is returned if the result column is an expression or constant or
  58534. ** anything else which is not an unabiguous reference to a database column.
  58535. */
  58536. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  58537. return columnName(
  58538. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  58539. }
  58540. #ifndef SQLITE_OMIT_UTF16
  58541. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  58542. return columnName(
  58543. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  58544. }
  58545. #endif /* SQLITE_OMIT_UTF16 */
  58546. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  58547. /******************************* sqlite3_bind_ ***************************
  58548. **
  58549. ** Routines used to attach values to wildcards in a compiled SQL statement.
  58550. */
  58551. /*
  58552. ** Unbind the value bound to variable i in virtual machine p. This is the
  58553. ** the same as binding a NULL value to the column. If the "i" parameter is
  58554. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  58555. **
  58556. ** A successful evaluation of this routine acquires the mutex on p.
  58557. ** the mutex is released if any kind of error occurs.
  58558. **
  58559. ** The error code stored in database p->db is overwritten with the return
  58560. ** value in any case.
  58561. */
  58562. static int vdbeUnbind(Vdbe *p, int i){
  58563. Mem *pVar;
  58564. if( vdbeSafetyNotNull(p) ){
  58565. return SQLITE_MISUSE_BKPT;
  58566. }
  58567. sqlite3_mutex_enter(p->db->mutex);
  58568. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  58569. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  58570. sqlite3_mutex_leave(p->db->mutex);
  58571. sqlite3_log(SQLITE_MISUSE,
  58572. "bind on a busy prepared statement: [%s]", p->zSql);
  58573. return SQLITE_MISUSE_BKPT;
  58574. }
  58575. if( i<1 || i>p->nVar ){
  58576. sqlite3Error(p->db, SQLITE_RANGE, 0);
  58577. sqlite3_mutex_leave(p->db->mutex);
  58578. return SQLITE_RANGE;
  58579. }
  58580. i--;
  58581. pVar = &p->aVar[i];
  58582. sqlite3VdbeMemRelease(pVar);
  58583. pVar->flags = MEM_Null;
  58584. sqlite3Error(p->db, SQLITE_OK, 0);
  58585. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  58586. ** binding a new value to this variable invalidates the current query plan.
  58587. **
  58588. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  58589. ** parameter in the WHERE clause might influence the choice of query plan
  58590. ** for a statement, then the statement will be automatically recompiled,
  58591. ** as if there had been a schema change, on the first sqlite3_step() call
  58592. ** following any change to the bindings of that parameter.
  58593. */
  58594. if( p->isPrepareV2 &&
  58595. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  58596. ){
  58597. p->expired = 1;
  58598. }
  58599. return SQLITE_OK;
  58600. }
  58601. /*
  58602. ** Bind a text or BLOB value.
  58603. */
  58604. static int bindText(
  58605. sqlite3_stmt *pStmt, /* The statement to bind against */
  58606. int i, /* Index of the parameter to bind */
  58607. const void *zData, /* Pointer to the data to be bound */
  58608. int nData, /* Number of bytes of data to be bound */
  58609. void (*xDel)(void*), /* Destructor for the data */
  58610. u8 encoding /* Encoding for the data */
  58611. ){
  58612. Vdbe *p = (Vdbe *)pStmt;
  58613. Mem *pVar;
  58614. int rc;
  58615. rc = vdbeUnbind(p, i);
  58616. if( rc==SQLITE_OK ){
  58617. if( zData!=0 ){
  58618. pVar = &p->aVar[i-1];
  58619. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  58620. if( rc==SQLITE_OK && encoding!=0 ){
  58621. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  58622. }
  58623. sqlite3Error(p->db, rc, 0);
  58624. rc = sqlite3ApiExit(p->db, rc);
  58625. }
  58626. sqlite3_mutex_leave(p->db->mutex);
  58627. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  58628. xDel((void*)zData);
  58629. }
  58630. return rc;
  58631. }
  58632. /*
  58633. ** Bind a blob value to an SQL statement variable.
  58634. */
  58635. SQLITE_API int sqlite3_bind_blob(
  58636. sqlite3_stmt *pStmt,
  58637. int i,
  58638. const void *zData,
  58639. int nData,
  58640. void (*xDel)(void*)
  58641. ){
  58642. return bindText(pStmt, i, zData, nData, xDel, 0);
  58643. }
  58644. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  58645. int rc;
  58646. Vdbe *p = (Vdbe *)pStmt;
  58647. rc = vdbeUnbind(p, i);
  58648. if( rc==SQLITE_OK ){
  58649. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  58650. sqlite3_mutex_leave(p->db->mutex);
  58651. }
  58652. return rc;
  58653. }
  58654. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  58655. return sqlite3_bind_int64(p, i, (i64)iValue);
  58656. }
  58657. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  58658. int rc;
  58659. Vdbe *p = (Vdbe *)pStmt;
  58660. rc = vdbeUnbind(p, i);
  58661. if( rc==SQLITE_OK ){
  58662. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  58663. sqlite3_mutex_leave(p->db->mutex);
  58664. }
  58665. return rc;
  58666. }
  58667. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  58668. int rc;
  58669. Vdbe *p = (Vdbe*)pStmt;
  58670. rc = vdbeUnbind(p, i);
  58671. if( rc==SQLITE_OK ){
  58672. sqlite3_mutex_leave(p->db->mutex);
  58673. }
  58674. return rc;
  58675. }
  58676. SQLITE_API int sqlite3_bind_text(
  58677. sqlite3_stmt *pStmt,
  58678. int i,
  58679. const char *zData,
  58680. int nData,
  58681. void (*xDel)(void*)
  58682. ){
  58683. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  58684. }
  58685. #ifndef SQLITE_OMIT_UTF16
  58686. SQLITE_API int sqlite3_bind_text16(
  58687. sqlite3_stmt *pStmt,
  58688. int i,
  58689. const void *zData,
  58690. int nData,
  58691. void (*xDel)(void*)
  58692. ){
  58693. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  58694. }
  58695. #endif /* SQLITE_OMIT_UTF16 */
  58696. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  58697. int rc;
  58698. switch( pValue->type ){
  58699. case SQLITE_INTEGER: {
  58700. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  58701. break;
  58702. }
  58703. case SQLITE_FLOAT: {
  58704. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  58705. break;
  58706. }
  58707. case SQLITE_BLOB: {
  58708. if( pValue->flags & MEM_Zero ){
  58709. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  58710. }else{
  58711. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  58712. }
  58713. break;
  58714. }
  58715. case SQLITE_TEXT: {
  58716. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  58717. pValue->enc);
  58718. break;
  58719. }
  58720. default: {
  58721. rc = sqlite3_bind_null(pStmt, i);
  58722. break;
  58723. }
  58724. }
  58725. return rc;
  58726. }
  58727. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  58728. int rc;
  58729. Vdbe *p = (Vdbe *)pStmt;
  58730. rc = vdbeUnbind(p, i);
  58731. if( rc==SQLITE_OK ){
  58732. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  58733. sqlite3_mutex_leave(p->db->mutex);
  58734. }
  58735. return rc;
  58736. }
  58737. /*
  58738. ** Return the number of wildcards that can be potentially bound to.
  58739. ** This routine is added to support DBD::SQLite.
  58740. */
  58741. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  58742. Vdbe *p = (Vdbe*)pStmt;
  58743. return p ? p->nVar : 0;
  58744. }
  58745. /*
  58746. ** Return the name of a wildcard parameter. Return NULL if the index
  58747. ** is out of range or if the wildcard is unnamed.
  58748. **
  58749. ** The result is always UTF-8.
  58750. */
  58751. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  58752. Vdbe *p = (Vdbe*)pStmt;
  58753. if( p==0 || i<1 || i>p->nzVar ){
  58754. return 0;
  58755. }
  58756. return p->azVar[i-1];
  58757. }
  58758. /*
  58759. ** Given a wildcard parameter name, return the index of the variable
  58760. ** with that name. If there is no variable with the given name,
  58761. ** return 0.
  58762. */
  58763. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  58764. int i;
  58765. if( p==0 ){
  58766. return 0;
  58767. }
  58768. if( zName ){
  58769. for(i=0; i<p->nzVar; i++){
  58770. const char *z = p->azVar[i];
  58771. if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
  58772. return i+1;
  58773. }
  58774. }
  58775. }
  58776. return 0;
  58777. }
  58778. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  58779. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  58780. }
  58781. /*
  58782. ** Transfer all bindings from the first statement over to the second.
  58783. */
  58784. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  58785. Vdbe *pFrom = (Vdbe*)pFromStmt;
  58786. Vdbe *pTo = (Vdbe*)pToStmt;
  58787. int i;
  58788. assert( pTo->db==pFrom->db );
  58789. assert( pTo->nVar==pFrom->nVar );
  58790. sqlite3_mutex_enter(pTo->db->mutex);
  58791. for(i=0; i<pFrom->nVar; i++){
  58792. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  58793. }
  58794. sqlite3_mutex_leave(pTo->db->mutex);
  58795. return SQLITE_OK;
  58796. }
  58797. #ifndef SQLITE_OMIT_DEPRECATED
  58798. /*
  58799. ** Deprecated external interface. Internal/core SQLite code
  58800. ** should call sqlite3TransferBindings.
  58801. **
  58802. ** Is is misuse to call this routine with statements from different
  58803. ** database connections. But as this is a deprecated interface, we
  58804. ** will not bother to check for that condition.
  58805. **
  58806. ** If the two statements contain a different number of bindings, then
  58807. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  58808. ** SQLITE_OK is returned.
  58809. */
  58810. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  58811. Vdbe *pFrom = (Vdbe*)pFromStmt;
  58812. Vdbe *pTo = (Vdbe*)pToStmt;
  58813. if( pFrom->nVar!=pTo->nVar ){
  58814. return SQLITE_ERROR;
  58815. }
  58816. if( pTo->isPrepareV2 && pTo->expmask ){
  58817. pTo->expired = 1;
  58818. }
  58819. if( pFrom->isPrepareV2 && pFrom->expmask ){
  58820. pFrom->expired = 1;
  58821. }
  58822. return sqlite3TransferBindings(pFromStmt, pToStmt);
  58823. }
  58824. #endif
  58825. /*
  58826. ** Return the sqlite3* database handle to which the prepared statement given
  58827. ** in the argument belongs. This is the same database handle that was
  58828. ** the first argument to the sqlite3_prepare() that was used to create
  58829. ** the statement in the first place.
  58830. */
  58831. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  58832. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  58833. }
  58834. /*
  58835. ** Return true if the prepared statement is guaranteed to not modify the
  58836. ** database.
  58837. */
  58838. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  58839. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  58840. }
  58841. /*
  58842. ** Return true if the prepared statement is in need of being reset.
  58843. */
  58844. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  58845. Vdbe *v = (Vdbe*)pStmt;
  58846. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  58847. }
  58848. /*
  58849. ** Return a pointer to the next prepared statement after pStmt associated
  58850. ** with database connection pDb. If pStmt is NULL, return the first
  58851. ** prepared statement for the database connection. Return NULL if there
  58852. ** are no more.
  58853. */
  58854. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  58855. sqlite3_stmt *pNext;
  58856. sqlite3_mutex_enter(pDb->mutex);
  58857. if( pStmt==0 ){
  58858. pNext = (sqlite3_stmt*)pDb->pVdbe;
  58859. }else{
  58860. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  58861. }
  58862. sqlite3_mutex_leave(pDb->mutex);
  58863. return pNext;
  58864. }
  58865. /*
  58866. ** Return the value of a status counter for a prepared statement
  58867. */
  58868. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  58869. Vdbe *pVdbe = (Vdbe*)pStmt;
  58870. int v = pVdbe->aCounter[op-1];
  58871. if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  58872. return v;
  58873. }
  58874. /************** End of vdbeapi.c *********************************************/
  58875. /************** Begin file vdbetrace.c ***************************************/
  58876. /*
  58877. ** 2009 November 25
  58878. **
  58879. ** The author disclaims copyright to this source code. In place of
  58880. ** a legal notice, here is a blessing:
  58881. **
  58882. ** May you do good and not evil.
  58883. ** May you find forgiveness for yourself and forgive others.
  58884. ** May you share freely, never taking more than you give.
  58885. **
  58886. *************************************************************************
  58887. **
  58888. ** This file contains code used to insert the values of host parameters
  58889. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  58890. **
  58891. ** The Vdbe parse-tree explainer is also found here.
  58892. */
  58893. #ifndef SQLITE_OMIT_TRACE
  58894. /*
  58895. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  58896. ** bytes in this text up to but excluding the first character in
  58897. ** a host parameter. If the text contains no host parameters, return
  58898. ** the total number of bytes in the text.
  58899. */
  58900. static int findNextHostParameter(const char *zSql, int *pnToken){
  58901. int tokenType;
  58902. int nTotal = 0;
  58903. int n;
  58904. *pnToken = 0;
  58905. while( zSql[0] ){
  58906. n = sqlite3GetToken((u8*)zSql, &tokenType);
  58907. assert( n>0 && tokenType!=TK_ILLEGAL );
  58908. if( tokenType==TK_VARIABLE ){
  58909. *pnToken = n;
  58910. break;
  58911. }
  58912. nTotal += n;
  58913. zSql += n;
  58914. }
  58915. return nTotal;
  58916. }
  58917. /*
  58918. ** This function returns a pointer to a nul-terminated string in memory
  58919. ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
  58920. ** string contains a copy of zRawSql but with host parameters expanded to
  58921. ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
  58922. ** then the returned string holds a copy of zRawSql with "-- " prepended
  58923. ** to each line of text.
  58924. **
  58925. ** The calling function is responsible for making sure the memory returned
  58926. ** is eventually freed.
  58927. **
  58928. ** ALGORITHM: Scan the input string looking for host parameters in any of
  58929. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  58930. ** string literals, quoted identifier names, and comments. For text forms,
  58931. ** the host parameter index is found by scanning the perpared
  58932. ** statement for the corresponding OP_Variable opcode. Once the host
  58933. ** parameter index is known, locate the value in p->aVar[]. Then render
  58934. ** the value as a literal in place of the host parameter name.
  58935. */
  58936. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  58937. Vdbe *p, /* The prepared statement being evaluated */
  58938. const char *zRawSql /* Raw text of the SQL statement */
  58939. ){
  58940. sqlite3 *db; /* The database connection */
  58941. int idx = 0; /* Index of a host parameter */
  58942. int nextIndex = 1; /* Index of next ? host parameter */
  58943. int n; /* Length of a token prefix */
  58944. int nToken; /* Length of the parameter token */
  58945. int i; /* Loop counter */
  58946. Mem *pVar; /* Value of a host parameter */
  58947. StrAccum out; /* Accumulate the output here */
  58948. char zBase[100]; /* Initial working space */
  58949. db = p->db;
  58950. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  58951. db->aLimit[SQLITE_LIMIT_LENGTH]);
  58952. out.db = db;
  58953. if( db->vdbeExecCnt>1 ){
  58954. while( *zRawSql ){
  58955. const char *zStart = zRawSql;
  58956. while( *(zRawSql++)!='\n' && *zRawSql );
  58957. sqlite3StrAccumAppend(&out, "-- ", 3);
  58958. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  58959. }
  58960. }else{
  58961. while( zRawSql[0] ){
  58962. n = findNextHostParameter(zRawSql, &nToken);
  58963. assert( n>0 );
  58964. sqlite3StrAccumAppend(&out, zRawSql, n);
  58965. zRawSql += n;
  58966. assert( zRawSql[0] || nToken==0 );
  58967. if( nToken==0 ) break;
  58968. if( zRawSql[0]=='?' ){
  58969. if( nToken>1 ){
  58970. assert( sqlite3Isdigit(zRawSql[1]) );
  58971. sqlite3GetInt32(&zRawSql[1], &idx);
  58972. }else{
  58973. idx = nextIndex;
  58974. }
  58975. }else{
  58976. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  58977. testcase( zRawSql[0]==':' );
  58978. testcase( zRawSql[0]=='$' );
  58979. testcase( zRawSql[0]=='@' );
  58980. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  58981. assert( idx>0 );
  58982. }
  58983. zRawSql += nToken;
  58984. nextIndex = idx + 1;
  58985. assert( idx>0 && idx<=p->nVar );
  58986. pVar = &p->aVar[idx-1];
  58987. if( pVar->flags & MEM_Null ){
  58988. sqlite3StrAccumAppend(&out, "NULL", 4);
  58989. }else if( pVar->flags & MEM_Int ){
  58990. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  58991. }else if( pVar->flags & MEM_Real ){
  58992. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  58993. }else if( pVar->flags & MEM_Str ){
  58994. #ifndef SQLITE_OMIT_UTF16
  58995. u8 enc = ENC(db);
  58996. if( enc!=SQLITE_UTF8 ){
  58997. Mem utf8;
  58998. memset(&utf8, 0, sizeof(utf8));
  58999. utf8.db = db;
  59000. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  59001. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  59002. sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
  59003. sqlite3VdbeMemRelease(&utf8);
  59004. }else
  59005. #endif
  59006. {
  59007. sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
  59008. }
  59009. }else if( pVar->flags & MEM_Zero ){
  59010. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  59011. }else{
  59012. assert( pVar->flags & MEM_Blob );
  59013. sqlite3StrAccumAppend(&out, "x'", 2);
  59014. for(i=0; i<pVar->n; i++){
  59015. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  59016. }
  59017. sqlite3StrAccumAppend(&out, "'", 1);
  59018. }
  59019. }
  59020. }
  59021. return sqlite3StrAccumFinish(&out);
  59022. }
  59023. #endif /* #ifndef SQLITE_OMIT_TRACE */
  59024. /*****************************************************************************
  59025. ** The following code implements the data-structure explaining logic
  59026. ** for the Vdbe.
  59027. */
  59028. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  59029. /*
  59030. ** Allocate a new Explain object
  59031. */
  59032. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  59033. if( pVdbe ){
  59034. Explain *p;
  59035. sqlite3BeginBenignMalloc();
  59036. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  59037. if( p ){
  59038. p->pVdbe = pVdbe;
  59039. sqlite3_free(pVdbe->pExplain);
  59040. pVdbe->pExplain = p;
  59041. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  59042. SQLITE_MAX_LENGTH);
  59043. p->str.useMalloc = 2;
  59044. }else{
  59045. sqlite3EndBenignMalloc();
  59046. }
  59047. }
  59048. }
  59049. /*
  59050. ** Return true if the Explain ends with a new-line.
  59051. */
  59052. static int endsWithNL(Explain *p){
  59053. return p && p->str.zText && p->str.nChar
  59054. && p->str.zText[p->str.nChar-1]=='\n';
  59055. }
  59056. /*
  59057. ** Append text to the indentation
  59058. */
  59059. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  59060. Explain *p;
  59061. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  59062. va_list ap;
  59063. if( p->nIndent && endsWithNL(p) ){
  59064. int n = p->nIndent;
  59065. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  59066. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  59067. }
  59068. va_start(ap, zFormat);
  59069. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  59070. va_end(ap);
  59071. }
  59072. }
  59073. /*
  59074. ** Append a '\n' if there is not already one.
  59075. */
  59076. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  59077. Explain *p;
  59078. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  59079. sqlite3StrAccumAppend(&p->str, "\n", 1);
  59080. }
  59081. }
  59082. /*
  59083. ** Push a new indentation level. Subsequent lines will be indented
  59084. ** so that they begin at the current cursor position.
  59085. */
  59086. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  59087. Explain *p;
  59088. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  59089. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  59090. const char *z = p->str.zText;
  59091. int i = p->str.nChar-1;
  59092. int x;
  59093. while( i>=0 && z[i]!='\n' ){ i--; }
  59094. x = (p->str.nChar - 1) - i;
  59095. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  59096. x = p->aIndent[p->nIndent-1];
  59097. }
  59098. p->aIndent[p->nIndent] = x;
  59099. }
  59100. p->nIndent++;
  59101. }
  59102. }
  59103. /*
  59104. ** Pop the indentation stack by one level.
  59105. */
  59106. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  59107. if( p && p->pExplain ) p->pExplain->nIndent--;
  59108. }
  59109. /*
  59110. ** Free the indentation structure
  59111. */
  59112. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  59113. if( pVdbe && pVdbe->pExplain ){
  59114. sqlite3_free(pVdbe->zExplain);
  59115. sqlite3ExplainNL(pVdbe);
  59116. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  59117. sqlite3_free(pVdbe->pExplain);
  59118. pVdbe->pExplain = 0;
  59119. sqlite3EndBenignMalloc();
  59120. }
  59121. }
  59122. /*
  59123. ** Return the explanation of a virtual machine.
  59124. */
  59125. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  59126. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  59127. }
  59128. #endif /* defined(SQLITE_DEBUG) */
  59129. /************** End of vdbetrace.c *******************************************/
  59130. /************** Begin file vdbe.c ********************************************/
  59131. /*
  59132. ** 2001 September 15
  59133. **
  59134. ** The author disclaims copyright to this source code. In place of
  59135. ** a legal notice, here is a blessing:
  59136. **
  59137. ** May you do good and not evil.
  59138. ** May you find forgiveness for yourself and forgive others.
  59139. ** May you share freely, never taking more than you give.
  59140. **
  59141. *************************************************************************
  59142. ** The code in this file implements execution method of the
  59143. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  59144. ** handles housekeeping details such as creating and deleting
  59145. ** VDBE instances. This file is solely interested in executing
  59146. ** the VDBE program.
  59147. **
  59148. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  59149. ** to a VDBE.
  59150. **
  59151. ** The SQL parser generates a program which is then executed by
  59152. ** the VDBE to do the work of the SQL statement. VDBE programs are
  59153. ** similar in form to assembly language. The program consists of
  59154. ** a linear sequence of operations. Each operation has an opcode
  59155. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  59156. ** is a null-terminated string. Operand P5 is an unsigned character.
  59157. ** Few opcodes use all 5 operands.
  59158. **
  59159. ** Computation results are stored on a set of registers numbered beginning
  59160. ** with 1 and going up to Vdbe.nMem. Each register can store
  59161. ** either an integer, a null-terminated string, a floating point
  59162. ** number, or the SQL "NULL" value. An implicit conversion from one
  59163. ** type to the other occurs as necessary.
  59164. **
  59165. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  59166. ** function which does the work of interpreting a VDBE program.
  59167. ** But other routines are also provided to help in building up
  59168. ** a program instruction by instruction.
  59169. **
  59170. ** Various scripts scan this source file in order to generate HTML
  59171. ** documentation, headers files, or other derived files. The formatting
  59172. ** of the code in this file is, therefore, important. See other comments
  59173. ** in this file for details. If in doubt, do not deviate from existing
  59174. ** commenting and indentation practices when changing or adding code.
  59175. */
  59176. /*
  59177. ** Invoke this macro on memory cells just prior to changing the
  59178. ** value of the cell. This macro verifies that shallow copies are
  59179. ** not misused.
  59180. */
  59181. #ifdef SQLITE_DEBUG
  59182. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  59183. #else
  59184. # define memAboutToChange(P,M)
  59185. #endif
  59186. /*
  59187. ** The following global variable is incremented every time a cursor
  59188. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  59189. ** procedures use this information to make sure that indices are
  59190. ** working correctly. This variable has no function other than to
  59191. ** help verify the correct operation of the library.
  59192. */
  59193. #ifdef SQLITE_TEST
  59194. SQLITE_API int sqlite3_search_count = 0;
  59195. #endif
  59196. /*
  59197. ** When this global variable is positive, it gets decremented once before
  59198. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  59199. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  59200. **
  59201. ** This facility is used for testing purposes only. It does not function
  59202. ** in an ordinary build.
  59203. */
  59204. #ifdef SQLITE_TEST
  59205. SQLITE_API int sqlite3_interrupt_count = 0;
  59206. #endif
  59207. /*
  59208. ** The next global variable is incremented each type the OP_Sort opcode
  59209. ** is executed. The test procedures use this information to make sure that
  59210. ** sorting is occurring or not occurring at appropriate times. This variable
  59211. ** has no function other than to help verify the correct operation of the
  59212. ** library.
  59213. */
  59214. #ifdef SQLITE_TEST
  59215. SQLITE_API int sqlite3_sort_count = 0;
  59216. #endif
  59217. /*
  59218. ** The next global variable records the size of the largest MEM_Blob
  59219. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  59220. ** use this information to make sure that the zero-blob functionality
  59221. ** is working correctly. This variable has no function other than to
  59222. ** help verify the correct operation of the library.
  59223. */
  59224. #ifdef SQLITE_TEST
  59225. SQLITE_API int sqlite3_max_blobsize = 0;
  59226. static void updateMaxBlobsize(Mem *p){
  59227. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  59228. sqlite3_max_blobsize = p->n;
  59229. }
  59230. }
  59231. #endif
  59232. /*
  59233. ** The next global variable is incremented each type the OP_Found opcode
  59234. ** is executed. This is used to test whether or not the foreign key
  59235. ** operation implemented using OP_FkIsZero is working. This variable
  59236. ** has no function other than to help verify the correct operation of the
  59237. ** library.
  59238. */
  59239. #ifdef SQLITE_TEST
  59240. SQLITE_API int sqlite3_found_count = 0;
  59241. #endif
  59242. /*
  59243. ** Test a register to see if it exceeds the current maximum blob size.
  59244. ** If it does, record the new maximum blob size.
  59245. */
  59246. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  59247. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  59248. #else
  59249. # define UPDATE_MAX_BLOBSIZE(P)
  59250. #endif
  59251. /*
  59252. ** Convert the given register into a string if it isn't one
  59253. ** already. Return non-zero if a malloc() fails.
  59254. */
  59255. #define Stringify(P, enc) \
  59256. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  59257. { goto no_mem; }
  59258. /*
  59259. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  59260. ** a pointer to a dynamically allocated string where some other entity
  59261. ** is responsible for deallocating that string. Because the register
  59262. ** does not control the string, it might be deleted without the register
  59263. ** knowing it.
  59264. **
  59265. ** This routine converts an ephemeral string into a dynamically allocated
  59266. ** string that the register itself controls. In other words, it
  59267. ** converts an MEM_Ephem string into an MEM_Dyn string.
  59268. */
  59269. #define Deephemeralize(P) \
  59270. if( ((P)->flags&MEM_Ephem)!=0 \
  59271. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  59272. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  59273. #ifdef SQLITE_OMIT_MERGE_SORT
  59274. # define isSorter(x) 0
  59275. #else
  59276. # define isSorter(x) ((x)->pSorter!=0)
  59277. #endif
  59278. /*
  59279. ** Argument pMem points at a register that will be passed to a
  59280. ** user-defined function or returned to the user as the result of a query.
  59281. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  59282. ** routines.
  59283. */
  59284. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  59285. int flags = pMem->flags;
  59286. if( flags & MEM_Null ){
  59287. pMem->type = SQLITE_NULL;
  59288. }
  59289. else if( flags & MEM_Int ){
  59290. pMem->type = SQLITE_INTEGER;
  59291. }
  59292. else if( flags & MEM_Real ){
  59293. pMem->type = SQLITE_FLOAT;
  59294. }
  59295. else if( flags & MEM_Str ){
  59296. pMem->type = SQLITE_TEXT;
  59297. }else{
  59298. pMem->type = SQLITE_BLOB;
  59299. }
  59300. }
  59301. /*
  59302. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  59303. ** if we run out of memory.
  59304. */
  59305. static VdbeCursor *allocateCursor(
  59306. Vdbe *p, /* The virtual machine */
  59307. int iCur, /* Index of the new VdbeCursor */
  59308. int nField, /* Number of fields in the table or index */
  59309. int iDb, /* Database the cursor belongs to, or -1 */
  59310. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  59311. ){
  59312. /* Find the memory cell that will be used to store the blob of memory
  59313. ** required for this VdbeCursor structure. It is convenient to use a
  59314. ** vdbe memory cell to manage the memory allocation required for a
  59315. ** VdbeCursor structure for the following reasons:
  59316. **
  59317. ** * Sometimes cursor numbers are used for a couple of different
  59318. ** purposes in a vdbe program. The different uses might require
  59319. ** different sized allocations. Memory cells provide growable
  59320. ** allocations.
  59321. **
  59322. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  59323. ** be freed lazily via the sqlite3_release_memory() API. This
  59324. ** minimizes the number of malloc calls made by the system.
  59325. **
  59326. ** Memory cells for cursors are allocated at the top of the address
  59327. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  59328. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  59329. */
  59330. Mem *pMem = &p->aMem[p->nMem-iCur];
  59331. int nByte;
  59332. VdbeCursor *pCx = 0;
  59333. nByte =
  59334. ROUND8(sizeof(VdbeCursor)) +
  59335. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  59336. 2*nField*sizeof(u32);
  59337. assert( iCur<p->nCursor );
  59338. if( p->apCsr[iCur] ){
  59339. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  59340. p->apCsr[iCur] = 0;
  59341. }
  59342. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  59343. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  59344. memset(pCx, 0, sizeof(VdbeCursor));
  59345. pCx->iDb = iDb;
  59346. pCx->nField = nField;
  59347. if( nField ){
  59348. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  59349. }
  59350. if( isBtreeCursor ){
  59351. pCx->pCursor = (BtCursor*)
  59352. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  59353. sqlite3BtreeCursorZero(pCx->pCursor);
  59354. }
  59355. }
  59356. return pCx;
  59357. }
  59358. /*
  59359. ** Try to convert a value into a numeric representation if we can
  59360. ** do so without loss of information. In other words, if the string
  59361. ** looks like a number, convert it into a number. If it does not
  59362. ** look like a number, leave it alone.
  59363. */
  59364. static void applyNumericAffinity(Mem *pRec){
  59365. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  59366. double rValue;
  59367. i64 iValue;
  59368. u8 enc = pRec->enc;
  59369. if( (pRec->flags&MEM_Str)==0 ) return;
  59370. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  59371. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  59372. pRec->u.i = iValue;
  59373. pRec->flags |= MEM_Int;
  59374. }else{
  59375. pRec->r = rValue;
  59376. pRec->flags |= MEM_Real;
  59377. }
  59378. }
  59379. }
  59380. /*
  59381. ** Processing is determine by the affinity parameter:
  59382. **
  59383. ** SQLITE_AFF_INTEGER:
  59384. ** SQLITE_AFF_REAL:
  59385. ** SQLITE_AFF_NUMERIC:
  59386. ** Try to convert pRec to an integer representation or a
  59387. ** floating-point representation if an integer representation
  59388. ** is not possible. Note that the integer representation is
  59389. ** always preferred, even if the affinity is REAL, because
  59390. ** an integer representation is more space efficient on disk.
  59391. **
  59392. ** SQLITE_AFF_TEXT:
  59393. ** Convert pRec to a text representation.
  59394. **
  59395. ** SQLITE_AFF_NONE:
  59396. ** No-op. pRec is unchanged.
  59397. */
  59398. static void applyAffinity(
  59399. Mem *pRec, /* The value to apply affinity to */
  59400. char affinity, /* The affinity to be applied */
  59401. u8 enc /* Use this text encoding */
  59402. ){
  59403. if( affinity==SQLITE_AFF_TEXT ){
  59404. /* Only attempt the conversion to TEXT if there is an integer or real
  59405. ** representation (blob and NULL do not get converted) but no string
  59406. ** representation.
  59407. */
  59408. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  59409. sqlite3VdbeMemStringify(pRec, enc);
  59410. }
  59411. pRec->flags &= ~(MEM_Real|MEM_Int);
  59412. }else if( affinity!=SQLITE_AFF_NONE ){
  59413. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  59414. || affinity==SQLITE_AFF_NUMERIC );
  59415. applyNumericAffinity(pRec);
  59416. if( pRec->flags & MEM_Real ){
  59417. sqlite3VdbeIntegerAffinity(pRec);
  59418. }
  59419. }
  59420. }
  59421. /*
  59422. ** Try to convert the type of a function argument or a result column
  59423. ** into a numeric representation. Use either INTEGER or REAL whichever
  59424. ** is appropriate. But only do the conversion if it is possible without
  59425. ** loss of information and return the revised type of the argument.
  59426. */
  59427. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  59428. Mem *pMem = (Mem*)pVal;
  59429. if( pMem->type==SQLITE_TEXT ){
  59430. applyNumericAffinity(pMem);
  59431. sqlite3VdbeMemStoreType(pMem);
  59432. }
  59433. return pMem->type;
  59434. }
  59435. /*
  59436. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  59437. ** not the internal Mem* type.
  59438. */
  59439. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  59440. sqlite3_value *pVal,
  59441. u8 affinity,
  59442. u8 enc
  59443. ){
  59444. applyAffinity((Mem *)pVal, affinity, enc);
  59445. }
  59446. #ifdef SQLITE_DEBUG
  59447. /*
  59448. ** Write a nice string representation of the contents of cell pMem
  59449. ** into buffer zBuf, length nBuf.
  59450. */
  59451. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  59452. char *zCsr = zBuf;
  59453. int f = pMem->flags;
  59454. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  59455. if( f&MEM_Blob ){
  59456. int i;
  59457. char c;
  59458. if( f & MEM_Dyn ){
  59459. c = 'z';
  59460. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  59461. }else if( f & MEM_Static ){
  59462. c = 't';
  59463. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  59464. }else if( f & MEM_Ephem ){
  59465. c = 'e';
  59466. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  59467. }else{
  59468. c = 's';
  59469. }
  59470. sqlite3_snprintf(100, zCsr, "%c", c);
  59471. zCsr += sqlite3Strlen30(zCsr);
  59472. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  59473. zCsr += sqlite3Strlen30(zCsr);
  59474. for(i=0; i<16 && i<pMem->n; i++){
  59475. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  59476. zCsr += sqlite3Strlen30(zCsr);
  59477. }
  59478. for(i=0; i<16 && i<pMem->n; i++){
  59479. char z = pMem->z[i];
  59480. if( z<32 || z>126 ) *zCsr++ = '.';
  59481. else *zCsr++ = z;
  59482. }
  59483. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  59484. zCsr += sqlite3Strlen30(zCsr);
  59485. if( f & MEM_Zero ){
  59486. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  59487. zCsr += sqlite3Strlen30(zCsr);
  59488. }
  59489. *zCsr = '\0';
  59490. }else if( f & MEM_Str ){
  59491. int j, k;
  59492. zBuf[0] = ' ';
  59493. if( f & MEM_Dyn ){
  59494. zBuf[1] = 'z';
  59495. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  59496. }else if( f & MEM_Static ){
  59497. zBuf[1] = 't';
  59498. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  59499. }else if( f & MEM_Ephem ){
  59500. zBuf[1] = 'e';
  59501. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  59502. }else{
  59503. zBuf[1] = 's';
  59504. }
  59505. k = 2;
  59506. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  59507. k += sqlite3Strlen30(&zBuf[k]);
  59508. zBuf[k++] = '[';
  59509. for(j=0; j<15 && j<pMem->n; j++){
  59510. u8 c = pMem->z[j];
  59511. if( c>=0x20 && c<0x7f ){
  59512. zBuf[k++] = c;
  59513. }else{
  59514. zBuf[k++] = '.';
  59515. }
  59516. }
  59517. zBuf[k++] = ']';
  59518. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  59519. k += sqlite3Strlen30(&zBuf[k]);
  59520. zBuf[k++] = 0;
  59521. }
  59522. }
  59523. #endif
  59524. #ifdef SQLITE_DEBUG
  59525. /*
  59526. ** Print the value of a register for tracing purposes:
  59527. */
  59528. static void memTracePrint(FILE *out, Mem *p){
  59529. if( p->flags & MEM_Invalid ){
  59530. fprintf(out, " undefined");
  59531. }else if( p->flags & MEM_Null ){
  59532. fprintf(out, " NULL");
  59533. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  59534. fprintf(out, " si:%lld", p->u.i);
  59535. }else if( p->flags & MEM_Int ){
  59536. fprintf(out, " i:%lld", p->u.i);
  59537. #ifndef SQLITE_OMIT_FLOATING_POINT
  59538. }else if( p->flags & MEM_Real ){
  59539. fprintf(out, " r:%g", p->r);
  59540. #endif
  59541. }else if( p->flags & MEM_RowSet ){
  59542. fprintf(out, " (rowset)");
  59543. }else{
  59544. char zBuf[200];
  59545. sqlite3VdbeMemPrettyPrint(p, zBuf);
  59546. fprintf(out, " ");
  59547. fprintf(out, "%s", zBuf);
  59548. }
  59549. }
  59550. static void registerTrace(FILE *out, int iReg, Mem *p){
  59551. fprintf(out, "REG[%d] = ", iReg);
  59552. memTracePrint(out, p);
  59553. fprintf(out, "\n");
  59554. }
  59555. #endif
  59556. #ifdef SQLITE_DEBUG
  59557. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  59558. #else
  59559. # define REGISTER_TRACE(R,M)
  59560. #endif
  59561. #ifdef VDBE_PROFILE
  59562. /*
  59563. ** hwtime.h contains inline assembler code for implementing
  59564. ** high-performance timing routines.
  59565. */
  59566. /************** Include hwtime.h in the middle of vdbe.c *********************/
  59567. /************** Begin file hwtime.h ******************************************/
  59568. /*
  59569. ** 2008 May 27
  59570. **
  59571. ** The author disclaims copyright to this source code. In place of
  59572. ** a legal notice, here is a blessing:
  59573. **
  59574. ** May you do good and not evil.
  59575. ** May you find forgiveness for yourself and forgive others.
  59576. ** May you share freely, never taking more than you give.
  59577. **
  59578. ******************************************************************************
  59579. **
  59580. ** This file contains inline asm code for retrieving "high-performance"
  59581. ** counters for x86 class CPUs.
  59582. */
  59583. #ifndef _HWTIME_H_
  59584. #define _HWTIME_H_
  59585. /*
  59586. ** The following routine only works on pentium-class (or newer) processors.
  59587. ** It uses the RDTSC opcode to read the cycle count value out of the
  59588. ** processor and returns that value. This can be used for high-res
  59589. ** profiling.
  59590. */
  59591. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  59592. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  59593. #if defined(__GNUC__)
  59594. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  59595. unsigned int lo, hi;
  59596. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  59597. return (sqlite_uint64)hi << 32 | lo;
  59598. }
  59599. #elif defined(_MSC_VER)
  59600. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  59601. __asm {
  59602. rdtsc
  59603. ret ; return value at EDX:EAX
  59604. }
  59605. }
  59606. #endif
  59607. #elif (defined(__GNUC__) && defined(__x86_64__))
  59608. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  59609. unsigned long val;
  59610. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  59611. return val;
  59612. }
  59613. #elif (defined(__GNUC__) && defined(__ppc__))
  59614. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  59615. unsigned long long retval;
  59616. unsigned long junk;
  59617. __asm__ __volatile__ ("\n\
  59618. 1: mftbu %1\n\
  59619. mftb %L0\n\
  59620. mftbu %0\n\
  59621. cmpw %0,%1\n\
  59622. bne 1b"
  59623. : "=r" (retval), "=r" (junk));
  59624. return retval;
  59625. }
  59626. #else
  59627. #error Need implementation of sqlite3Hwtime() for your platform.
  59628. /*
  59629. ** To compile without implementing sqlite3Hwtime() for your platform,
  59630. ** you can remove the above #error and use the following
  59631. ** stub function. You will lose timing support for many
  59632. ** of the debugging and testing utilities, but it should at
  59633. ** least compile and run.
  59634. */
  59635. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  59636. #endif
  59637. #endif /* !defined(_HWTIME_H_) */
  59638. /************** End of hwtime.h **********************************************/
  59639. /************** Continuing where we left off in vdbe.c ***********************/
  59640. #endif
  59641. /*
  59642. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  59643. ** sqlite3_interrupt() routine has been called. If it has been, then
  59644. ** processing of the VDBE program is interrupted.
  59645. **
  59646. ** This macro added to every instruction that does a jump in order to
  59647. ** implement a loop. This test used to be on every single instruction,
  59648. ** but that meant we more testing than we needed. By only testing the
  59649. ** flag on jump instructions, we get a (small) speed improvement.
  59650. */
  59651. #define CHECK_FOR_INTERRUPT \
  59652. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  59653. #ifndef NDEBUG
  59654. /*
  59655. ** This function is only called from within an assert() expression. It
  59656. ** checks that the sqlite3.nTransaction variable is correctly set to
  59657. ** the number of non-transaction savepoints currently in the
  59658. ** linked list starting at sqlite3.pSavepoint.
  59659. **
  59660. ** Usage:
  59661. **
  59662. ** assert( checkSavepointCount(db) );
  59663. */
  59664. static int checkSavepointCount(sqlite3 *db){
  59665. int n = 0;
  59666. Savepoint *p;
  59667. for(p=db->pSavepoint; p; p=p->pNext) n++;
  59668. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  59669. return 1;
  59670. }
  59671. #endif
  59672. /*
  59673. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  59674. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  59675. ** in memory obtained from sqlite3DbMalloc).
  59676. */
  59677. static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
  59678. sqlite3 *db = p->db;
  59679. sqlite3DbFree(db, p->zErrMsg);
  59680. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  59681. sqlite3_free(pVtab->zErrMsg);
  59682. pVtab->zErrMsg = 0;
  59683. }
  59684. /*
  59685. ** Execute as much of a VDBE program as we can then return.
  59686. **
  59687. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  59688. ** close the program with a final OP_Halt and to set up the callbacks
  59689. ** and the error message pointer.
  59690. **
  59691. ** Whenever a row or result data is available, this routine will either
  59692. ** invoke the result callback (if there is one) or return with
  59693. ** SQLITE_ROW.
  59694. **
  59695. ** If an attempt is made to open a locked database, then this routine
  59696. ** will either invoke the busy callback (if there is one) or it will
  59697. ** return SQLITE_BUSY.
  59698. **
  59699. ** If an error occurs, an error message is written to memory obtained
  59700. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  59701. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  59702. **
  59703. ** If the callback ever returns non-zero, then the program exits
  59704. ** immediately. There will be no error message but the p->rc field is
  59705. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  59706. **
  59707. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  59708. ** routine to return SQLITE_ERROR.
  59709. **
  59710. ** Other fatal errors return SQLITE_ERROR.
  59711. **
  59712. ** After this routine has finished, sqlite3VdbeFinalize() should be
  59713. ** used to clean up the mess that was left behind.
  59714. */
  59715. SQLITE_PRIVATE int sqlite3VdbeExec(
  59716. Vdbe *p /* The VDBE */
  59717. ){
  59718. int pc=0; /* The program counter */
  59719. Op *aOp = p->aOp; /* Copy of p->aOp */
  59720. Op *pOp; /* Current operation */
  59721. int rc = SQLITE_OK; /* Value to return */
  59722. sqlite3 *db = p->db; /* The database */
  59723. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  59724. u8 encoding = ENC(db); /* The database encoding */
  59725. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  59726. int checkProgress; /* True if progress callbacks are enabled */
  59727. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  59728. #endif
  59729. Mem *aMem = p->aMem; /* Copy of p->aMem */
  59730. Mem *pIn1 = 0; /* 1st input operand */
  59731. Mem *pIn2 = 0; /* 2nd input operand */
  59732. Mem *pIn3 = 0; /* 3rd input operand */
  59733. Mem *pOut = 0; /* Output operand */
  59734. int iCompare = 0; /* Result of last OP_Compare operation */
  59735. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  59736. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  59737. #ifdef VDBE_PROFILE
  59738. u64 start; /* CPU clock count at start of opcode */
  59739. int origPc; /* Program counter at start of opcode */
  59740. #endif
  59741. /********************************************************************
  59742. ** Automatically generated code
  59743. **
  59744. ** The following union is automatically generated by the
  59745. ** vdbe-compress.tcl script. The purpose of this union is to
  59746. ** reduce the amount of stack space required by this function.
  59747. ** See comments in the vdbe-compress.tcl script for details.
  59748. */
  59749. union vdbeExecUnion {
  59750. struct OP_Yield_stack_vars {
  59751. int pcDest;
  59752. } aa;
  59753. struct OP_Null_stack_vars {
  59754. int cnt;
  59755. u16 nullFlag;
  59756. } ab;
  59757. struct OP_Variable_stack_vars {
  59758. Mem *pVar; /* Value being transferred */
  59759. } ac;
  59760. struct OP_Move_stack_vars {
  59761. char *zMalloc; /* Holding variable for allocated memory */
  59762. int n; /* Number of registers left to copy */
  59763. int p1; /* Register to copy from */
  59764. int p2; /* Register to copy to */
  59765. } ad;
  59766. struct OP_Copy_stack_vars {
  59767. int n;
  59768. } ae;
  59769. struct OP_ResultRow_stack_vars {
  59770. Mem *pMem;
  59771. int i;
  59772. } af;
  59773. struct OP_Concat_stack_vars {
  59774. i64 nByte;
  59775. } ag;
  59776. struct OP_Remainder_stack_vars {
  59777. char bIntint; /* Started out as two integer operands */
  59778. int flags; /* Combined MEM_* flags from both inputs */
  59779. i64 iA; /* Integer value of left operand */
  59780. i64 iB; /* Integer value of right operand */
  59781. double rA; /* Real value of left operand */
  59782. double rB; /* Real value of right operand */
  59783. } ah;
  59784. struct OP_Function_stack_vars {
  59785. int i;
  59786. Mem *pArg;
  59787. sqlite3_context ctx;
  59788. sqlite3_value **apVal;
  59789. int n;
  59790. } ai;
  59791. struct OP_ShiftRight_stack_vars {
  59792. i64 iA;
  59793. u64 uA;
  59794. i64 iB;
  59795. u8 op;
  59796. } aj;
  59797. struct OP_Ge_stack_vars {
  59798. int res; /* Result of the comparison of pIn1 against pIn3 */
  59799. char affinity; /* Affinity to use for comparison */
  59800. u16 flags1; /* Copy of initial value of pIn1->flags */
  59801. u16 flags3; /* Copy of initial value of pIn3->flags */
  59802. } ak;
  59803. struct OP_Compare_stack_vars {
  59804. int n;
  59805. int i;
  59806. int p1;
  59807. int p2;
  59808. const KeyInfo *pKeyInfo;
  59809. int idx;
  59810. CollSeq *pColl; /* Collating sequence to use on this term */
  59811. int bRev; /* True for DESCENDING sort order */
  59812. } al;
  59813. struct OP_Or_stack_vars {
  59814. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  59815. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  59816. } am;
  59817. struct OP_IfNot_stack_vars {
  59818. int c;
  59819. } an;
  59820. struct OP_Column_stack_vars {
  59821. u32 payloadSize; /* Number of bytes in the record */
  59822. i64 payloadSize64; /* Number of bytes in the record */
  59823. int p1; /* P1 value of the opcode */
  59824. int p2; /* column number to retrieve */
  59825. VdbeCursor *pC; /* The VDBE cursor */
  59826. char *zRec; /* Pointer to complete record-data */
  59827. BtCursor *pCrsr; /* The BTree cursor */
  59828. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  59829. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  59830. int nField; /* number of fields in the record */
  59831. int len; /* The length of the serialized data for the column */
  59832. int i; /* Loop counter */
  59833. char *zData; /* Part of the record being decoded */
  59834. Mem *pDest; /* Where to write the extracted value */
  59835. Mem sMem; /* For storing the record being decoded */
  59836. u8 *zIdx; /* Index into header */
  59837. u8 *zEndHdr; /* Pointer to first byte after the header */
  59838. u32 offset; /* Offset into the data */
  59839. u32 szField; /* Number of bytes in the content of a field */
  59840. int szHdr; /* Size of the header size field at start of record */
  59841. int avail; /* Number of bytes of available data */
  59842. u32 t; /* A type code from the record header */
  59843. Mem *pReg; /* PseudoTable input register */
  59844. } ao;
  59845. struct OP_Affinity_stack_vars {
  59846. const char *zAffinity; /* The affinity to be applied */
  59847. char cAff; /* A single character of affinity */
  59848. } ap;
  59849. struct OP_MakeRecord_stack_vars {
  59850. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  59851. Mem *pRec; /* The new record */
  59852. u64 nData; /* Number of bytes of data space */
  59853. int nHdr; /* Number of bytes of header space */
  59854. i64 nByte; /* Data space required for this record */
  59855. int nZero; /* Number of zero bytes at the end of the record */
  59856. int nVarint; /* Number of bytes in a varint */
  59857. u32 serial_type; /* Type field */
  59858. Mem *pData0; /* First field to be combined into the record */
  59859. Mem *pLast; /* Last field of the record */
  59860. int nField; /* Number of fields in the record */
  59861. char *zAffinity; /* The affinity string for the record */
  59862. int file_format; /* File format to use for encoding */
  59863. int i; /* Space used in zNewRecord[] */
  59864. int len; /* Length of a field */
  59865. } aq;
  59866. struct OP_Count_stack_vars {
  59867. i64 nEntry;
  59868. BtCursor *pCrsr;
  59869. } ar;
  59870. struct OP_Savepoint_stack_vars {
  59871. int p1; /* Value of P1 operand */
  59872. char *zName; /* Name of savepoint */
  59873. int nName;
  59874. Savepoint *pNew;
  59875. Savepoint *pSavepoint;
  59876. Savepoint *pTmp;
  59877. int iSavepoint;
  59878. int ii;
  59879. } as;
  59880. struct OP_AutoCommit_stack_vars {
  59881. int desiredAutoCommit;
  59882. int iRollback;
  59883. int turnOnAC;
  59884. } at;
  59885. struct OP_Transaction_stack_vars {
  59886. Btree *pBt;
  59887. } au;
  59888. struct OP_ReadCookie_stack_vars {
  59889. int iMeta;
  59890. int iDb;
  59891. int iCookie;
  59892. } av;
  59893. struct OP_SetCookie_stack_vars {
  59894. Db *pDb;
  59895. } aw;
  59896. struct OP_VerifyCookie_stack_vars {
  59897. int iMeta;
  59898. int iGen;
  59899. Btree *pBt;
  59900. } ax;
  59901. struct OP_OpenWrite_stack_vars {
  59902. int nField;
  59903. KeyInfo *pKeyInfo;
  59904. int p2;
  59905. int iDb;
  59906. int wrFlag;
  59907. Btree *pX;
  59908. VdbeCursor *pCur;
  59909. Db *pDb;
  59910. } ay;
  59911. struct OP_OpenEphemeral_stack_vars {
  59912. VdbeCursor *pCx;
  59913. } az;
  59914. struct OP_SorterOpen_stack_vars {
  59915. VdbeCursor *pCx;
  59916. } ba;
  59917. struct OP_OpenPseudo_stack_vars {
  59918. VdbeCursor *pCx;
  59919. } bb;
  59920. struct OP_SeekGt_stack_vars {
  59921. int res;
  59922. int oc;
  59923. VdbeCursor *pC;
  59924. UnpackedRecord r;
  59925. int nField;
  59926. i64 iKey; /* The rowid we are to seek to */
  59927. } bc;
  59928. struct OP_Seek_stack_vars {
  59929. VdbeCursor *pC;
  59930. } bd;
  59931. struct OP_Found_stack_vars {
  59932. int alreadyExists;
  59933. VdbeCursor *pC;
  59934. int res;
  59935. char *pFree;
  59936. UnpackedRecord *pIdxKey;
  59937. UnpackedRecord r;
  59938. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  59939. } be;
  59940. struct OP_IsUnique_stack_vars {
  59941. u16 ii;
  59942. VdbeCursor *pCx;
  59943. BtCursor *pCrsr;
  59944. u16 nField;
  59945. Mem *aMx;
  59946. UnpackedRecord r; /* B-Tree index search key */
  59947. i64 R; /* Rowid stored in register P3 */
  59948. } bf;
  59949. struct OP_NotExists_stack_vars {
  59950. VdbeCursor *pC;
  59951. BtCursor *pCrsr;
  59952. int res;
  59953. u64 iKey;
  59954. } bg;
  59955. struct OP_NewRowid_stack_vars {
  59956. i64 v; /* The new rowid */
  59957. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  59958. int res; /* Result of an sqlite3BtreeLast() */
  59959. int cnt; /* Counter to limit the number of searches */
  59960. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  59961. VdbeFrame *pFrame; /* Root frame of VDBE */
  59962. } bh;
  59963. struct OP_InsertInt_stack_vars {
  59964. Mem *pData; /* MEM cell holding data for the record to be inserted */
  59965. Mem *pKey; /* MEM cell holding key for the record */
  59966. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  59967. VdbeCursor *pC; /* Cursor to table into which insert is written */
  59968. int nZero; /* Number of zero-bytes to append */
  59969. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  59970. const char *zDb; /* database name - used by the update hook */
  59971. const char *zTbl; /* Table name - used by the opdate hook */
  59972. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  59973. } bi;
  59974. struct OP_Delete_stack_vars {
  59975. i64 iKey;
  59976. VdbeCursor *pC;
  59977. } bj;
  59978. struct OP_SorterCompare_stack_vars {
  59979. VdbeCursor *pC;
  59980. int res;
  59981. } bk;
  59982. struct OP_SorterData_stack_vars {
  59983. VdbeCursor *pC;
  59984. } bl;
  59985. struct OP_RowData_stack_vars {
  59986. VdbeCursor *pC;
  59987. BtCursor *pCrsr;
  59988. u32 n;
  59989. i64 n64;
  59990. } bm;
  59991. struct OP_Rowid_stack_vars {
  59992. VdbeCursor *pC;
  59993. i64 v;
  59994. sqlite3_vtab *pVtab;
  59995. const sqlite3_module *pModule;
  59996. } bn;
  59997. struct OP_NullRow_stack_vars {
  59998. VdbeCursor *pC;
  59999. } bo;
  60000. struct OP_Last_stack_vars {
  60001. VdbeCursor *pC;
  60002. BtCursor *pCrsr;
  60003. int res;
  60004. } bp;
  60005. struct OP_Rewind_stack_vars {
  60006. VdbeCursor *pC;
  60007. BtCursor *pCrsr;
  60008. int res;
  60009. } bq;
  60010. struct OP_Next_stack_vars {
  60011. VdbeCursor *pC;
  60012. int res;
  60013. } br;
  60014. struct OP_IdxInsert_stack_vars {
  60015. VdbeCursor *pC;
  60016. BtCursor *pCrsr;
  60017. int nKey;
  60018. const char *zKey;
  60019. } bs;
  60020. struct OP_IdxDelete_stack_vars {
  60021. VdbeCursor *pC;
  60022. BtCursor *pCrsr;
  60023. int res;
  60024. UnpackedRecord r;
  60025. } bt;
  60026. struct OP_IdxRowid_stack_vars {
  60027. BtCursor *pCrsr;
  60028. VdbeCursor *pC;
  60029. i64 rowid;
  60030. } bu;
  60031. struct OP_IdxGE_stack_vars {
  60032. VdbeCursor *pC;
  60033. int res;
  60034. UnpackedRecord r;
  60035. } bv;
  60036. struct OP_Destroy_stack_vars {
  60037. int iMoved;
  60038. int iCnt;
  60039. Vdbe *pVdbe;
  60040. int iDb;
  60041. } bw;
  60042. struct OP_Clear_stack_vars {
  60043. int nChange;
  60044. } bx;
  60045. struct OP_CreateTable_stack_vars {
  60046. int pgno;
  60047. int flags;
  60048. Db *pDb;
  60049. } by;
  60050. struct OP_ParseSchema_stack_vars {
  60051. int iDb;
  60052. const char *zMaster;
  60053. char *zSql;
  60054. InitData initData;
  60055. } bz;
  60056. struct OP_IntegrityCk_stack_vars {
  60057. int nRoot; /* Number of tables to check. (Number of root pages.) */
  60058. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  60059. int j; /* Loop counter */
  60060. int nErr; /* Number of errors reported */
  60061. char *z; /* Text of the error report */
  60062. Mem *pnErr; /* Register keeping track of errors remaining */
  60063. } ca;
  60064. struct OP_RowSetRead_stack_vars {
  60065. i64 val;
  60066. } cb;
  60067. struct OP_RowSetTest_stack_vars {
  60068. int iSet;
  60069. int exists;
  60070. } cc;
  60071. struct OP_Program_stack_vars {
  60072. int nMem; /* Number of memory registers for sub-program */
  60073. int nByte; /* Bytes of runtime space required for sub-program */
  60074. Mem *pRt; /* Register to allocate runtime space */
  60075. Mem *pMem; /* Used to iterate through memory cells */
  60076. Mem *pEnd; /* Last memory cell in new array */
  60077. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  60078. SubProgram *pProgram; /* Sub-program to execute */
  60079. void *t; /* Token identifying trigger */
  60080. } cd;
  60081. struct OP_Param_stack_vars {
  60082. VdbeFrame *pFrame;
  60083. Mem *pIn;
  60084. } ce;
  60085. struct OP_MemMax_stack_vars {
  60086. Mem *pIn1;
  60087. VdbeFrame *pFrame;
  60088. } cf;
  60089. struct OP_AggStep_stack_vars {
  60090. int n;
  60091. int i;
  60092. Mem *pMem;
  60093. Mem *pRec;
  60094. sqlite3_context ctx;
  60095. sqlite3_value **apVal;
  60096. } cg;
  60097. struct OP_AggFinal_stack_vars {
  60098. Mem *pMem;
  60099. } ch;
  60100. struct OP_Checkpoint_stack_vars {
  60101. int i; /* Loop counter */
  60102. int aRes[3]; /* Results */
  60103. Mem *pMem; /* Write results here */
  60104. } ci;
  60105. struct OP_JournalMode_stack_vars {
  60106. Btree *pBt; /* Btree to change journal mode of */
  60107. Pager *pPager; /* Pager associated with pBt */
  60108. int eNew; /* New journal mode */
  60109. int eOld; /* The old journal mode */
  60110. #ifndef SQLITE_OMIT_WAL
  60111. const char *zFilename; /* Name of database file for pPager */
  60112. #endif
  60113. } cj;
  60114. struct OP_IncrVacuum_stack_vars {
  60115. Btree *pBt;
  60116. } ck;
  60117. struct OP_VBegin_stack_vars {
  60118. VTable *pVTab;
  60119. } cl;
  60120. struct OP_VOpen_stack_vars {
  60121. VdbeCursor *pCur;
  60122. sqlite3_vtab_cursor *pVtabCursor;
  60123. sqlite3_vtab *pVtab;
  60124. sqlite3_module *pModule;
  60125. } cm;
  60126. struct OP_VFilter_stack_vars {
  60127. int nArg;
  60128. int iQuery;
  60129. const sqlite3_module *pModule;
  60130. Mem *pQuery;
  60131. Mem *pArgc;
  60132. sqlite3_vtab_cursor *pVtabCursor;
  60133. sqlite3_vtab *pVtab;
  60134. VdbeCursor *pCur;
  60135. int res;
  60136. int i;
  60137. Mem **apArg;
  60138. } cn;
  60139. struct OP_VColumn_stack_vars {
  60140. sqlite3_vtab *pVtab;
  60141. const sqlite3_module *pModule;
  60142. Mem *pDest;
  60143. sqlite3_context sContext;
  60144. } co;
  60145. struct OP_VNext_stack_vars {
  60146. sqlite3_vtab *pVtab;
  60147. const sqlite3_module *pModule;
  60148. int res;
  60149. VdbeCursor *pCur;
  60150. } cp;
  60151. struct OP_VRename_stack_vars {
  60152. sqlite3_vtab *pVtab;
  60153. Mem *pName;
  60154. } cq;
  60155. struct OP_VUpdate_stack_vars {
  60156. sqlite3_vtab *pVtab;
  60157. sqlite3_module *pModule;
  60158. int nArg;
  60159. int i;
  60160. sqlite_int64 rowid;
  60161. Mem **apArg;
  60162. Mem *pX;
  60163. } cr;
  60164. struct OP_Trace_stack_vars {
  60165. char *zTrace;
  60166. char *z;
  60167. } cs;
  60168. } u;
  60169. /* End automatically generated code
  60170. ********************************************************************/
  60171. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  60172. sqlite3VdbeEnter(p);
  60173. if( p->rc==SQLITE_NOMEM ){
  60174. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  60175. ** sqlite3_column_text16() failed. */
  60176. goto no_mem;
  60177. }
  60178. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  60179. p->rc = SQLITE_OK;
  60180. assert( p->explain==0 );
  60181. p->pResultSet = 0;
  60182. db->busyHandler.nBusy = 0;
  60183. CHECK_FOR_INTERRUPT;
  60184. sqlite3VdbeIOTraceSql(p);
  60185. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  60186. checkProgress = db->xProgress!=0;
  60187. #endif
  60188. #ifdef SQLITE_DEBUG
  60189. sqlite3BeginBenignMalloc();
  60190. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  60191. int i;
  60192. printf("VDBE Program Listing:\n");
  60193. sqlite3VdbePrintSql(p);
  60194. for(i=0; i<p->nOp; i++){
  60195. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  60196. }
  60197. }
  60198. sqlite3EndBenignMalloc();
  60199. #endif
  60200. for(pc=p->pc; rc==SQLITE_OK; pc++){
  60201. assert( pc>=0 && pc<p->nOp );
  60202. if( db->mallocFailed ) goto no_mem;
  60203. #ifdef VDBE_PROFILE
  60204. origPc = pc;
  60205. start = sqlite3Hwtime();
  60206. #endif
  60207. pOp = &aOp[pc];
  60208. /* Only allow tracing if SQLITE_DEBUG is defined.
  60209. */
  60210. #ifdef SQLITE_DEBUG
  60211. if( p->trace ){
  60212. if( pc==0 ){
  60213. printf("VDBE Execution Trace:\n");
  60214. sqlite3VdbePrintSql(p);
  60215. }
  60216. sqlite3VdbePrintOp(p->trace, pc, pOp);
  60217. }
  60218. #endif
  60219. /* Check to see if we need to simulate an interrupt. This only happens
  60220. ** if we have a special test build.
  60221. */
  60222. #ifdef SQLITE_TEST
  60223. if( sqlite3_interrupt_count>0 ){
  60224. sqlite3_interrupt_count--;
  60225. if( sqlite3_interrupt_count==0 ){
  60226. sqlite3_interrupt(db);
  60227. }
  60228. }
  60229. #endif
  60230. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  60231. /* Call the progress callback if it is configured and the required number
  60232. ** of VDBE ops have been executed (either since this invocation of
  60233. ** sqlite3VdbeExec() or since last time the progress callback was called).
  60234. ** If the progress callback returns non-zero, exit the virtual machine with
  60235. ** a return code SQLITE_ABORT.
  60236. */
  60237. if( checkProgress ){
  60238. if( db->nProgressOps==nProgressOps ){
  60239. int prc;
  60240. prc = db->xProgress(db->pProgressArg);
  60241. if( prc!=0 ){
  60242. rc = SQLITE_INTERRUPT;
  60243. goto vdbe_error_halt;
  60244. }
  60245. nProgressOps = 0;
  60246. }
  60247. nProgressOps++;
  60248. }
  60249. #endif
  60250. /* On any opcode with the "out2-prerelease" tag, free any
  60251. ** external allocations out of mem[p2] and set mem[p2] to be
  60252. ** an undefined integer. Opcodes will either fill in the integer
  60253. ** value or convert mem[p2] to a different type.
  60254. */
  60255. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  60256. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  60257. assert( pOp->p2>0 );
  60258. assert( pOp->p2<=p->nMem );
  60259. pOut = &aMem[pOp->p2];
  60260. memAboutToChange(p, pOut);
  60261. VdbeMemRelease(pOut);
  60262. pOut->flags = MEM_Int;
  60263. }
  60264. /* Sanity checking on other operands */
  60265. #ifdef SQLITE_DEBUG
  60266. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  60267. assert( pOp->p1>0 );
  60268. assert( pOp->p1<=p->nMem );
  60269. assert( memIsValid(&aMem[pOp->p1]) );
  60270. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  60271. }
  60272. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  60273. assert( pOp->p2>0 );
  60274. assert( pOp->p2<=p->nMem );
  60275. assert( memIsValid(&aMem[pOp->p2]) );
  60276. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  60277. }
  60278. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  60279. assert( pOp->p3>0 );
  60280. assert( pOp->p3<=p->nMem );
  60281. assert( memIsValid(&aMem[pOp->p3]) );
  60282. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  60283. }
  60284. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  60285. assert( pOp->p2>0 );
  60286. assert( pOp->p2<=p->nMem );
  60287. memAboutToChange(p, &aMem[pOp->p2]);
  60288. }
  60289. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  60290. assert( pOp->p3>0 );
  60291. assert( pOp->p3<=p->nMem );
  60292. memAboutToChange(p, &aMem[pOp->p3]);
  60293. }
  60294. #endif
  60295. switch( pOp->opcode ){
  60296. /*****************************************************************************
  60297. ** What follows is a massive switch statement where each case implements a
  60298. ** separate instruction in the virtual machine. If we follow the usual
  60299. ** indentation conventions, each case should be indented by 6 spaces. But
  60300. ** that is a lot of wasted space on the left margin. So the code within
  60301. ** the switch statement will break with convention and be flush-left. Another
  60302. ** big comment (similar to this one) will mark the point in the code where
  60303. ** we transition back to normal indentation.
  60304. **
  60305. ** The formatting of each case is important. The makefile for SQLite
  60306. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  60307. ** file looking for lines that begin with "case OP_". The opcodes.h files
  60308. ** will be filled with #defines that give unique integer values to each
  60309. ** opcode and the opcodes.c file is filled with an array of strings where
  60310. ** each string is the symbolic name for the corresponding opcode. If the
  60311. ** case statement is followed by a comment of the form "/# same as ... #/"
  60312. ** that comment is used to determine the particular value of the opcode.
  60313. **
  60314. ** Other keywords in the comment that follows each case are used to
  60315. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  60316. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  60317. ** the mkopcodeh.awk script for additional information.
  60318. **
  60319. ** Documentation about VDBE opcodes is generated by scanning this file
  60320. ** for lines of that contain "Opcode:". That line and all subsequent
  60321. ** comment lines are used in the generation of the opcode.html documentation
  60322. ** file.
  60323. **
  60324. ** SUMMARY:
  60325. **
  60326. ** Formatting is important to scripts that scan this file.
  60327. ** Do not deviate from the formatting style currently in use.
  60328. **
  60329. *****************************************************************************/
  60330. /* Opcode: Goto * P2 * * *
  60331. **
  60332. ** An unconditional jump to address P2.
  60333. ** The next instruction executed will be
  60334. ** the one at index P2 from the beginning of
  60335. ** the program.
  60336. */
  60337. case OP_Goto: { /* jump */
  60338. CHECK_FOR_INTERRUPT;
  60339. pc = pOp->p2 - 1;
  60340. break;
  60341. }
  60342. /* Opcode: Gosub P1 P2 * * *
  60343. **
  60344. ** Write the current address onto register P1
  60345. ** and then jump to address P2.
  60346. */
  60347. case OP_Gosub: { /* jump */
  60348. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  60349. pIn1 = &aMem[pOp->p1];
  60350. assert( (pIn1->flags & MEM_Dyn)==0 );
  60351. memAboutToChange(p, pIn1);
  60352. pIn1->flags = MEM_Int;
  60353. pIn1->u.i = pc;
  60354. REGISTER_TRACE(pOp->p1, pIn1);
  60355. pc = pOp->p2 - 1;
  60356. break;
  60357. }
  60358. /* Opcode: Return P1 * * * *
  60359. **
  60360. ** Jump to the next instruction after the address in register P1.
  60361. */
  60362. case OP_Return: { /* in1 */
  60363. pIn1 = &aMem[pOp->p1];
  60364. assert( pIn1->flags & MEM_Int );
  60365. pc = (int)pIn1->u.i;
  60366. break;
  60367. }
  60368. /* Opcode: Yield P1 * * * *
  60369. **
  60370. ** Swap the program counter with the value in register P1.
  60371. */
  60372. case OP_Yield: { /* in1 */
  60373. #if 0 /* local variables moved into u.aa */
  60374. int pcDest;
  60375. #endif /* local variables moved into u.aa */
  60376. pIn1 = &aMem[pOp->p1];
  60377. assert( (pIn1->flags & MEM_Dyn)==0 );
  60378. pIn1->flags = MEM_Int;
  60379. u.aa.pcDest = (int)pIn1->u.i;
  60380. pIn1->u.i = pc;
  60381. REGISTER_TRACE(pOp->p1, pIn1);
  60382. pc = u.aa.pcDest;
  60383. break;
  60384. }
  60385. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  60386. **
  60387. ** Check the value in register P3. If it is NULL then Halt using
  60388. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  60389. ** value in register P3 is not NULL, then this routine is a no-op.
  60390. */
  60391. case OP_HaltIfNull: { /* in3 */
  60392. pIn3 = &aMem[pOp->p3];
  60393. if( (pIn3->flags & MEM_Null)==0 ) break;
  60394. /* Fall through into OP_Halt */
  60395. }
  60396. /* Opcode: Halt P1 P2 * P4 *
  60397. **
  60398. ** Exit immediately. All open cursors, etc are closed
  60399. ** automatically.
  60400. **
  60401. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  60402. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  60403. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  60404. ** whether or not to rollback the current transaction. Do not rollback
  60405. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  60406. ** then back out all changes that have occurred during this execution of the
  60407. ** VDBE, but do not rollback the transaction.
  60408. **
  60409. ** If P4 is not null then it is an error message string.
  60410. **
  60411. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  60412. ** every program. So a jump past the last instruction of the program
  60413. ** is the same as executing Halt.
  60414. */
  60415. case OP_Halt: {
  60416. if( pOp->p1==SQLITE_OK && p->pFrame ){
  60417. /* Halt the sub-program. Return control to the parent frame. */
  60418. VdbeFrame *pFrame = p->pFrame;
  60419. p->pFrame = pFrame->pParent;
  60420. p->nFrame--;
  60421. sqlite3VdbeSetChanges(db, p->nChange);
  60422. pc = sqlite3VdbeFrameRestore(pFrame);
  60423. lastRowid = db->lastRowid;
  60424. if( pOp->p2==OE_Ignore ){
  60425. /* Instruction pc is the OP_Program that invoked the sub-program
  60426. ** currently being halted. If the p2 instruction of this OP_Halt
  60427. ** instruction is set to OE_Ignore, then the sub-program is throwing
  60428. ** an IGNORE exception. In this case jump to the address specified
  60429. ** as the p2 of the calling OP_Program. */
  60430. pc = p->aOp[pc].p2-1;
  60431. }
  60432. aOp = p->aOp;
  60433. aMem = p->aMem;
  60434. break;
  60435. }
  60436. p->rc = pOp->p1;
  60437. p->errorAction = (u8)pOp->p2;
  60438. p->pc = pc;
  60439. if( pOp->p4.z ){
  60440. assert( p->rc!=SQLITE_OK );
  60441. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  60442. testcase( sqlite3GlobalConfig.xLog!=0 );
  60443. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  60444. }else if( p->rc ){
  60445. testcase( sqlite3GlobalConfig.xLog!=0 );
  60446. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  60447. }
  60448. rc = sqlite3VdbeHalt(p);
  60449. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  60450. if( rc==SQLITE_BUSY ){
  60451. p->rc = rc = SQLITE_BUSY;
  60452. }else{
  60453. assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
  60454. assert( rc==SQLITE_OK || db->nDeferredCons>0 );
  60455. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  60456. }
  60457. goto vdbe_return;
  60458. }
  60459. /* Opcode: Integer P1 P2 * * *
  60460. **
  60461. ** The 32-bit integer value P1 is written into register P2.
  60462. */
  60463. case OP_Integer: { /* out2-prerelease */
  60464. pOut->u.i = pOp->p1;
  60465. break;
  60466. }
  60467. /* Opcode: Int64 * P2 * P4 *
  60468. **
  60469. ** P4 is a pointer to a 64-bit integer value.
  60470. ** Write that value into register P2.
  60471. */
  60472. case OP_Int64: { /* out2-prerelease */
  60473. assert( pOp->p4.pI64!=0 );
  60474. pOut->u.i = *pOp->p4.pI64;
  60475. break;
  60476. }
  60477. #ifndef SQLITE_OMIT_FLOATING_POINT
  60478. /* Opcode: Real * P2 * P4 *
  60479. **
  60480. ** P4 is a pointer to a 64-bit floating point value.
  60481. ** Write that value into register P2.
  60482. */
  60483. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  60484. pOut->flags = MEM_Real;
  60485. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  60486. pOut->r = *pOp->p4.pReal;
  60487. break;
  60488. }
  60489. #endif
  60490. /* Opcode: String8 * P2 * P4 *
  60491. **
  60492. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  60493. ** into an OP_String before it is executed for the first time.
  60494. */
  60495. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  60496. assert( pOp->p4.z!=0 );
  60497. pOp->opcode = OP_String;
  60498. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  60499. #ifndef SQLITE_OMIT_UTF16
  60500. if( encoding!=SQLITE_UTF8 ){
  60501. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  60502. if( rc==SQLITE_TOOBIG ) goto too_big;
  60503. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  60504. assert( pOut->zMalloc==pOut->z );
  60505. assert( pOut->flags & MEM_Dyn );
  60506. pOut->zMalloc = 0;
  60507. pOut->flags |= MEM_Static;
  60508. pOut->flags &= ~MEM_Dyn;
  60509. if( pOp->p4type==P4_DYNAMIC ){
  60510. sqlite3DbFree(db, pOp->p4.z);
  60511. }
  60512. pOp->p4type = P4_DYNAMIC;
  60513. pOp->p4.z = pOut->z;
  60514. pOp->p1 = pOut->n;
  60515. }
  60516. #endif
  60517. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  60518. goto too_big;
  60519. }
  60520. /* Fall through to the next case, OP_String */
  60521. }
  60522. /* Opcode: String P1 P2 * P4 *
  60523. **
  60524. ** The string value P4 of length P1 (bytes) is stored in register P2.
  60525. */
  60526. case OP_String: { /* out2-prerelease */
  60527. assert( pOp->p4.z!=0 );
  60528. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  60529. pOut->z = pOp->p4.z;
  60530. pOut->n = pOp->p1;
  60531. pOut->enc = encoding;
  60532. UPDATE_MAX_BLOBSIZE(pOut);
  60533. break;
  60534. }
  60535. /* Opcode: Null P1 P2 P3 * *
  60536. **
  60537. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  60538. ** NULL into register P3 and every register in between P2 and P3. If P3
  60539. ** is less than P2 (typically P3 is zero) then only register P2 is
  60540. ** set to NULL.
  60541. **
  60542. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  60543. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  60544. ** OP_Ne or OP_Eq.
  60545. */
  60546. case OP_Null: { /* out2-prerelease */
  60547. #if 0 /* local variables moved into u.ab */
  60548. int cnt;
  60549. u16 nullFlag;
  60550. #endif /* local variables moved into u.ab */
  60551. u.ab.cnt = pOp->p3-pOp->p2;
  60552. assert( pOp->p3<=p->nMem );
  60553. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  60554. while( u.ab.cnt>0 ){
  60555. pOut++;
  60556. memAboutToChange(p, pOut);
  60557. VdbeMemRelease(pOut);
  60558. pOut->flags = u.ab.nullFlag;
  60559. u.ab.cnt--;
  60560. }
  60561. break;
  60562. }
  60563. /* Opcode: Blob P1 P2 * P4
  60564. **
  60565. ** P4 points to a blob of data P1 bytes long. Store this
  60566. ** blob in register P2.
  60567. */
  60568. case OP_Blob: { /* out2-prerelease */
  60569. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  60570. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  60571. pOut->enc = encoding;
  60572. UPDATE_MAX_BLOBSIZE(pOut);
  60573. break;
  60574. }
  60575. /* Opcode: Variable P1 P2 * P4 *
  60576. **
  60577. ** Transfer the values of bound parameter P1 into register P2
  60578. **
  60579. ** If the parameter is named, then its name appears in P4 and P3==1.
  60580. ** The P4 value is used by sqlite3_bind_parameter_name().
  60581. */
  60582. case OP_Variable: { /* out2-prerelease */
  60583. #if 0 /* local variables moved into u.ac */
  60584. Mem *pVar; /* Value being transferred */
  60585. #endif /* local variables moved into u.ac */
  60586. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  60587. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  60588. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  60589. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  60590. goto too_big;
  60591. }
  60592. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  60593. UPDATE_MAX_BLOBSIZE(pOut);
  60594. break;
  60595. }
  60596. /* Opcode: Move P1 P2 P3 * *
  60597. **
  60598. ** Move the values in register P1..P1+P3 over into
  60599. ** registers P2..P2+P3. Registers P1..P1+P3 are
  60600. ** left holding a NULL. It is an error for register ranges
  60601. ** P1..P1+P3 and P2..P2+P3 to overlap.
  60602. */
  60603. case OP_Move: {
  60604. #if 0 /* local variables moved into u.ad */
  60605. char *zMalloc; /* Holding variable for allocated memory */
  60606. int n; /* Number of registers left to copy */
  60607. int p1; /* Register to copy from */
  60608. int p2; /* Register to copy to */
  60609. #endif /* local variables moved into u.ad */
  60610. u.ad.n = pOp->p3 + 1;
  60611. u.ad.p1 = pOp->p1;
  60612. u.ad.p2 = pOp->p2;
  60613. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  60614. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  60615. pIn1 = &aMem[u.ad.p1];
  60616. pOut = &aMem[u.ad.p2];
  60617. while( u.ad.n-- ){
  60618. assert( pOut<=&aMem[p->nMem] );
  60619. assert( pIn1<=&aMem[p->nMem] );
  60620. assert( memIsValid(pIn1) );
  60621. memAboutToChange(p, pOut);
  60622. u.ad.zMalloc = pOut->zMalloc;
  60623. pOut->zMalloc = 0;
  60624. sqlite3VdbeMemMove(pOut, pIn1);
  60625. #ifdef SQLITE_DEBUG
  60626. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  60627. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  60628. }
  60629. #endif
  60630. pIn1->zMalloc = u.ad.zMalloc;
  60631. REGISTER_TRACE(u.ad.p2++, pOut);
  60632. pIn1++;
  60633. pOut++;
  60634. }
  60635. break;
  60636. }
  60637. /* Opcode: Copy P1 P2 P3 * *
  60638. **
  60639. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  60640. **
  60641. ** This instruction makes a deep copy of the value. A duplicate
  60642. ** is made of any string or blob constant. See also OP_SCopy.
  60643. */
  60644. case OP_Copy: {
  60645. #if 0 /* local variables moved into u.ae */
  60646. int n;
  60647. #endif /* local variables moved into u.ae */
  60648. u.ae.n = pOp->p3;
  60649. pIn1 = &aMem[pOp->p1];
  60650. pOut = &aMem[pOp->p2];
  60651. assert( pOut!=pIn1 );
  60652. while( 1 ){
  60653. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  60654. Deephemeralize(pOut);
  60655. #ifdef SQLITE_DEBUG
  60656. pOut->pScopyFrom = 0;
  60657. #endif
  60658. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  60659. if( (u.ae.n--)==0 ) break;
  60660. pOut++;
  60661. pIn1++;
  60662. }
  60663. break;
  60664. }
  60665. /* Opcode: SCopy P1 P2 * * *
  60666. **
  60667. ** Make a shallow copy of register P1 into register P2.
  60668. **
  60669. ** This instruction makes a shallow copy of the value. If the value
  60670. ** is a string or blob, then the copy is only a pointer to the
  60671. ** original and hence if the original changes so will the copy.
  60672. ** Worse, if the original is deallocated, the copy becomes invalid.
  60673. ** Thus the program must guarantee that the original will not change
  60674. ** during the lifetime of the copy. Use OP_Copy to make a complete
  60675. ** copy.
  60676. */
  60677. case OP_SCopy: { /* in1, out2 */
  60678. pIn1 = &aMem[pOp->p1];
  60679. pOut = &aMem[pOp->p2];
  60680. assert( pOut!=pIn1 );
  60681. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  60682. #ifdef SQLITE_DEBUG
  60683. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  60684. #endif
  60685. REGISTER_TRACE(pOp->p2, pOut);
  60686. break;
  60687. }
  60688. /* Opcode: ResultRow P1 P2 * * *
  60689. **
  60690. ** The registers P1 through P1+P2-1 contain a single row of
  60691. ** results. This opcode causes the sqlite3_step() call to terminate
  60692. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  60693. ** structure to provide access to the top P1 values as the result
  60694. ** row.
  60695. */
  60696. case OP_ResultRow: {
  60697. #if 0 /* local variables moved into u.af */
  60698. Mem *pMem;
  60699. int i;
  60700. #endif /* local variables moved into u.af */
  60701. assert( p->nResColumn==pOp->p2 );
  60702. assert( pOp->p1>0 );
  60703. assert( pOp->p1+pOp->p2<=p->nMem+1 );
  60704. /* If this statement has violated immediate foreign key constraints, do
  60705. ** not return the number of rows modified. And do not RELEASE the statement
  60706. ** transaction. It needs to be rolled back. */
  60707. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  60708. assert( db->flags&SQLITE_CountRows );
  60709. assert( p->usesStmtJournal );
  60710. break;
  60711. }
  60712. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  60713. ** DML statements invoke this opcode to return the number of rows
  60714. ** modified to the user. This is the only way that a VM that
  60715. ** opens a statement transaction may invoke this opcode.
  60716. **
  60717. ** In case this is such a statement, close any statement transaction
  60718. ** opened by this VM before returning control to the user. This is to
  60719. ** ensure that statement-transactions are always nested, not overlapping.
  60720. ** If the open statement-transaction is not closed here, then the user
  60721. ** may step another VM that opens its own statement transaction. This
  60722. ** may lead to overlapping statement transactions.
  60723. **
  60724. ** The statement transaction is never a top-level transaction. Hence
  60725. ** the RELEASE call below can never fail.
  60726. */
  60727. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  60728. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  60729. if( NEVER(rc!=SQLITE_OK) ){
  60730. break;
  60731. }
  60732. /* Invalidate all ephemeral cursor row caches */
  60733. p->cacheCtr = (p->cacheCtr + 2)|1;
  60734. /* Make sure the results of the current row are \000 terminated
  60735. ** and have an assigned type. The results are de-ephemeralized as
  60736. ** a side effect.
  60737. */
  60738. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  60739. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  60740. assert( memIsValid(&u.af.pMem[u.af.i]) );
  60741. Deephemeralize(&u.af.pMem[u.af.i]);
  60742. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  60743. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  60744. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  60745. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  60746. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  60747. }
  60748. if( db->mallocFailed ) goto no_mem;
  60749. /* Return SQLITE_ROW
  60750. */
  60751. p->pc = pc + 1;
  60752. rc = SQLITE_ROW;
  60753. goto vdbe_return;
  60754. }
  60755. /* Opcode: Concat P1 P2 P3 * *
  60756. **
  60757. ** Add the text in register P1 onto the end of the text in
  60758. ** register P2 and store the result in register P3.
  60759. ** If either the P1 or P2 text are NULL then store NULL in P3.
  60760. **
  60761. ** P3 = P2 || P1
  60762. **
  60763. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  60764. ** if P3 is the same register as P2, the implementation is able
  60765. ** to avoid a memcpy().
  60766. */
  60767. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  60768. #if 0 /* local variables moved into u.ag */
  60769. i64 nByte;
  60770. #endif /* local variables moved into u.ag */
  60771. pIn1 = &aMem[pOp->p1];
  60772. pIn2 = &aMem[pOp->p2];
  60773. pOut = &aMem[pOp->p3];
  60774. assert( pIn1!=pOut );
  60775. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  60776. sqlite3VdbeMemSetNull(pOut);
  60777. break;
  60778. }
  60779. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  60780. Stringify(pIn1, encoding);
  60781. Stringify(pIn2, encoding);
  60782. u.ag.nByte = pIn1->n + pIn2->n;
  60783. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  60784. goto too_big;
  60785. }
  60786. MemSetTypeFlag(pOut, MEM_Str);
  60787. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  60788. goto no_mem;
  60789. }
  60790. if( pOut!=pIn2 ){
  60791. memcpy(pOut->z, pIn2->z, pIn2->n);
  60792. }
  60793. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  60794. pOut->z[u.ag.nByte] = 0;
  60795. pOut->z[u.ag.nByte+1] = 0;
  60796. pOut->flags |= MEM_Term;
  60797. pOut->n = (int)u.ag.nByte;
  60798. pOut->enc = encoding;
  60799. UPDATE_MAX_BLOBSIZE(pOut);
  60800. break;
  60801. }
  60802. /* Opcode: Add P1 P2 P3 * *
  60803. **
  60804. ** Add the value in register P1 to the value in register P2
  60805. ** and store the result in register P3.
  60806. ** If either input is NULL, the result is NULL.
  60807. */
  60808. /* Opcode: Multiply P1 P2 P3 * *
  60809. **
  60810. **
  60811. ** Multiply the value in register P1 by the value in register P2
  60812. ** and store the result in register P3.
  60813. ** If either input is NULL, the result is NULL.
  60814. */
  60815. /* Opcode: Subtract P1 P2 P3 * *
  60816. **
  60817. ** Subtract the value in register P1 from the value in register P2
  60818. ** and store the result in register P3.
  60819. ** If either input is NULL, the result is NULL.
  60820. */
  60821. /* Opcode: Divide P1 P2 P3 * *
  60822. **
  60823. ** Divide the value in register P1 by the value in register P2
  60824. ** and store the result in register P3 (P3=P2/P1). If the value in
  60825. ** register P1 is zero, then the result is NULL. If either input is
  60826. ** NULL, the result is NULL.
  60827. */
  60828. /* Opcode: Remainder P1 P2 P3 * *
  60829. **
  60830. ** Compute the remainder after integer division of the value in
  60831. ** register P1 by the value in register P2 and store the result in P3.
  60832. ** If the value in register P2 is zero the result is NULL.
  60833. ** If either operand is NULL, the result is NULL.
  60834. */
  60835. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  60836. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  60837. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  60838. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  60839. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  60840. #if 0 /* local variables moved into u.ah */
  60841. char bIntint; /* Started out as two integer operands */
  60842. int flags; /* Combined MEM_* flags from both inputs */
  60843. i64 iA; /* Integer value of left operand */
  60844. i64 iB; /* Integer value of right operand */
  60845. double rA; /* Real value of left operand */
  60846. double rB; /* Real value of right operand */
  60847. #endif /* local variables moved into u.ah */
  60848. pIn1 = &aMem[pOp->p1];
  60849. applyNumericAffinity(pIn1);
  60850. pIn2 = &aMem[pOp->p2];
  60851. applyNumericAffinity(pIn2);
  60852. pOut = &aMem[pOp->p3];
  60853. u.ah.flags = pIn1->flags | pIn2->flags;
  60854. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  60855. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  60856. u.ah.iA = pIn1->u.i;
  60857. u.ah.iB = pIn2->u.i;
  60858. u.ah.bIntint = 1;
  60859. switch( pOp->opcode ){
  60860. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  60861. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  60862. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  60863. case OP_Divide: {
  60864. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  60865. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  60866. u.ah.iB /= u.ah.iA;
  60867. break;
  60868. }
  60869. default: {
  60870. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  60871. if( u.ah.iA==-1 ) u.ah.iA = 1;
  60872. u.ah.iB %= u.ah.iA;
  60873. break;
  60874. }
  60875. }
  60876. pOut->u.i = u.ah.iB;
  60877. MemSetTypeFlag(pOut, MEM_Int);
  60878. }else{
  60879. u.ah.bIntint = 0;
  60880. fp_math:
  60881. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  60882. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  60883. switch( pOp->opcode ){
  60884. case OP_Add: u.ah.rB += u.ah.rA; break;
  60885. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  60886. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  60887. case OP_Divide: {
  60888. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  60889. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  60890. u.ah.rB /= u.ah.rA;
  60891. break;
  60892. }
  60893. default: {
  60894. u.ah.iA = (i64)u.ah.rA;
  60895. u.ah.iB = (i64)u.ah.rB;
  60896. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  60897. if( u.ah.iA==-1 ) u.ah.iA = 1;
  60898. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  60899. break;
  60900. }
  60901. }
  60902. #ifdef SQLITE_OMIT_FLOATING_POINT
  60903. pOut->u.i = u.ah.rB;
  60904. MemSetTypeFlag(pOut, MEM_Int);
  60905. #else
  60906. if( sqlite3IsNaN(u.ah.rB) ){
  60907. goto arithmetic_result_is_null;
  60908. }
  60909. pOut->r = u.ah.rB;
  60910. MemSetTypeFlag(pOut, MEM_Real);
  60911. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  60912. sqlite3VdbeIntegerAffinity(pOut);
  60913. }
  60914. #endif
  60915. }
  60916. break;
  60917. arithmetic_result_is_null:
  60918. sqlite3VdbeMemSetNull(pOut);
  60919. break;
  60920. }
  60921. /* Opcode: CollSeq P1 * * P4
  60922. **
  60923. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  60924. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  60925. ** be returned. This is used by the built-in min(), max() and nullif()
  60926. ** functions.
  60927. **
  60928. ** If P1 is not zero, then it is a register that a subsequent min() or
  60929. ** max() aggregate will set to 1 if the current row is not the minimum or
  60930. ** maximum. The P1 register is initialized to 0 by this instruction.
  60931. **
  60932. ** The interface used by the implementation of the aforementioned functions
  60933. ** to retrieve the collation sequence set by this opcode is not available
  60934. ** publicly, only to user functions defined in func.c.
  60935. */
  60936. case OP_CollSeq: {
  60937. assert( pOp->p4type==P4_COLLSEQ );
  60938. if( pOp->p1 ){
  60939. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  60940. }
  60941. break;
  60942. }
  60943. /* Opcode: Function P1 P2 P3 P4 P5
  60944. **
  60945. ** Invoke a user function (P4 is a pointer to a Function structure that
  60946. ** defines the function) with P5 arguments taken from register P2 and
  60947. ** successors. The result of the function is stored in register P3.
  60948. ** Register P3 must not be one of the function inputs.
  60949. **
  60950. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  60951. ** function was determined to be constant at compile time. If the first
  60952. ** argument was constant then bit 0 of P1 is set. This is used to determine
  60953. ** whether meta data associated with a user function argument using the
  60954. ** sqlite3_set_auxdata() API may be safely retained until the next
  60955. ** invocation of this opcode.
  60956. **
  60957. ** See also: AggStep and AggFinal
  60958. */
  60959. case OP_Function: {
  60960. #if 0 /* local variables moved into u.ai */
  60961. int i;
  60962. Mem *pArg;
  60963. sqlite3_context ctx;
  60964. sqlite3_value **apVal;
  60965. int n;
  60966. #endif /* local variables moved into u.ai */
  60967. u.ai.n = pOp->p5;
  60968. u.ai.apVal = p->apArg;
  60969. assert( u.ai.apVal || u.ai.n==0 );
  60970. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  60971. pOut = &aMem[pOp->p3];
  60972. memAboutToChange(p, pOut);
  60973. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
  60974. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  60975. u.ai.pArg = &aMem[pOp->p2];
  60976. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  60977. assert( memIsValid(u.ai.pArg) );
  60978. u.ai.apVal[u.ai.i] = u.ai.pArg;
  60979. Deephemeralize(u.ai.pArg);
  60980. sqlite3VdbeMemStoreType(u.ai.pArg);
  60981. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  60982. }
  60983. assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  60984. if( pOp->p4type==P4_FUNCDEF ){
  60985. u.ai.ctx.pFunc = pOp->p4.pFunc;
  60986. u.ai.ctx.pVdbeFunc = 0;
  60987. }else{
  60988. u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
  60989. u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
  60990. }
  60991. u.ai.ctx.s.flags = MEM_Null;
  60992. u.ai.ctx.s.db = db;
  60993. u.ai.ctx.s.xDel = 0;
  60994. u.ai.ctx.s.zMalloc = 0;
  60995. /* The output cell may already have a buffer allocated. Move
  60996. ** the pointer to u.ai.ctx.s so in case the user-function can use
  60997. ** the already allocated buffer instead of allocating a new one.
  60998. */
  60999. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  61000. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  61001. u.ai.ctx.isError = 0;
  61002. if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  61003. assert( pOp>aOp );
  61004. assert( pOp[-1].p4type==P4_COLLSEQ );
  61005. assert( pOp[-1].opcode==OP_CollSeq );
  61006. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  61007. }
  61008. db->lastRowid = lastRowid;
  61009. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  61010. lastRowid = db->lastRowid;
  61011. /* If any auxiliary data functions have been called by this user function,
  61012. ** immediately call the destructor for any non-static values.
  61013. */
  61014. if( u.ai.ctx.pVdbeFunc ){
  61015. sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
  61016. pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
  61017. pOp->p4type = P4_VDBEFUNC;
  61018. }
  61019. if( db->mallocFailed ){
  61020. /* Even though a malloc() has failed, the implementation of the
  61021. ** user function may have called an sqlite3_result_XXX() function
  61022. ** to return a value. The following call releases any resources
  61023. ** associated with such a value.
  61024. */
  61025. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  61026. goto no_mem;
  61027. }
  61028. /* If the function returned an error, throw an exception */
  61029. if( u.ai.ctx.isError ){
  61030. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  61031. rc = u.ai.ctx.isError;
  61032. }
  61033. /* Copy the result of the function into register P3 */
  61034. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  61035. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  61036. if( sqlite3VdbeMemTooBig(pOut) ){
  61037. goto too_big;
  61038. }
  61039. #if 0
  61040. /* The app-defined function has done something that as caused this
  61041. ** statement to expire. (Perhaps the function called sqlite3_exec()
  61042. ** with a CREATE TABLE statement.)
  61043. */
  61044. if( p->expired ) rc = SQLITE_ABORT;
  61045. #endif
  61046. REGISTER_TRACE(pOp->p3, pOut);
  61047. UPDATE_MAX_BLOBSIZE(pOut);
  61048. break;
  61049. }
  61050. /* Opcode: BitAnd P1 P2 P3 * *
  61051. **
  61052. ** Take the bit-wise AND of the values in register P1 and P2 and
  61053. ** store the result in register P3.
  61054. ** If either input is NULL, the result is NULL.
  61055. */
  61056. /* Opcode: BitOr P1 P2 P3 * *
  61057. **
  61058. ** Take the bit-wise OR of the values in register P1 and P2 and
  61059. ** store the result in register P3.
  61060. ** If either input is NULL, the result is NULL.
  61061. */
  61062. /* Opcode: ShiftLeft P1 P2 P3 * *
  61063. **
  61064. ** Shift the integer value in register P2 to the left by the
  61065. ** number of bits specified by the integer in register P1.
  61066. ** Store the result in register P3.
  61067. ** If either input is NULL, the result is NULL.
  61068. */
  61069. /* Opcode: ShiftRight P1 P2 P3 * *
  61070. **
  61071. ** Shift the integer value in register P2 to the right by the
  61072. ** number of bits specified by the integer in register P1.
  61073. ** Store the result in register P3.
  61074. ** If either input is NULL, the result is NULL.
  61075. */
  61076. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  61077. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  61078. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  61079. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  61080. #if 0 /* local variables moved into u.aj */
  61081. i64 iA;
  61082. u64 uA;
  61083. i64 iB;
  61084. u8 op;
  61085. #endif /* local variables moved into u.aj */
  61086. pIn1 = &aMem[pOp->p1];
  61087. pIn2 = &aMem[pOp->p2];
  61088. pOut = &aMem[pOp->p3];
  61089. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  61090. sqlite3VdbeMemSetNull(pOut);
  61091. break;
  61092. }
  61093. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  61094. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  61095. u.aj.op = pOp->opcode;
  61096. if( u.aj.op==OP_BitAnd ){
  61097. u.aj.iA &= u.aj.iB;
  61098. }else if( u.aj.op==OP_BitOr ){
  61099. u.aj.iA |= u.aj.iB;
  61100. }else if( u.aj.iB!=0 ){
  61101. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  61102. /* If shifting by a negative amount, shift in the other direction */
  61103. if( u.aj.iB<0 ){
  61104. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  61105. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  61106. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  61107. }
  61108. if( u.aj.iB>=64 ){
  61109. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  61110. }else{
  61111. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  61112. if( u.aj.op==OP_ShiftLeft ){
  61113. u.aj.uA <<= u.aj.iB;
  61114. }else{
  61115. u.aj.uA >>= u.aj.iB;
  61116. /* Sign-extend on a right shift of a negative number */
  61117. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  61118. }
  61119. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  61120. }
  61121. }
  61122. pOut->u.i = u.aj.iA;
  61123. MemSetTypeFlag(pOut, MEM_Int);
  61124. break;
  61125. }
  61126. /* Opcode: AddImm P1 P2 * * *
  61127. **
  61128. ** Add the constant P2 to the value in register P1.
  61129. ** The result is always an integer.
  61130. **
  61131. ** To force any register to be an integer, just add 0.
  61132. */
  61133. case OP_AddImm: { /* in1 */
  61134. pIn1 = &aMem[pOp->p1];
  61135. memAboutToChange(p, pIn1);
  61136. sqlite3VdbeMemIntegerify(pIn1);
  61137. pIn1->u.i += pOp->p2;
  61138. break;
  61139. }
  61140. /* Opcode: MustBeInt P1 P2 * * *
  61141. **
  61142. ** Force the value in register P1 to be an integer. If the value
  61143. ** in P1 is not an integer and cannot be converted into an integer
  61144. ** without data loss, then jump immediately to P2, or if P2==0
  61145. ** raise an SQLITE_MISMATCH exception.
  61146. */
  61147. case OP_MustBeInt: { /* jump, in1 */
  61148. pIn1 = &aMem[pOp->p1];
  61149. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  61150. if( (pIn1->flags & MEM_Int)==0 ){
  61151. if( pOp->p2==0 ){
  61152. rc = SQLITE_MISMATCH;
  61153. goto abort_due_to_error;
  61154. }else{
  61155. pc = pOp->p2 - 1;
  61156. }
  61157. }else{
  61158. MemSetTypeFlag(pIn1, MEM_Int);
  61159. }
  61160. break;
  61161. }
  61162. #ifndef SQLITE_OMIT_FLOATING_POINT
  61163. /* Opcode: RealAffinity P1 * * * *
  61164. **
  61165. ** If register P1 holds an integer convert it to a real value.
  61166. **
  61167. ** This opcode is used when extracting information from a column that
  61168. ** has REAL affinity. Such column values may still be stored as
  61169. ** integers, for space efficiency, but after extraction we want them
  61170. ** to have only a real value.
  61171. */
  61172. case OP_RealAffinity: { /* in1 */
  61173. pIn1 = &aMem[pOp->p1];
  61174. if( pIn1->flags & MEM_Int ){
  61175. sqlite3VdbeMemRealify(pIn1);
  61176. }
  61177. break;
  61178. }
  61179. #endif
  61180. #ifndef SQLITE_OMIT_CAST
  61181. /* Opcode: ToText P1 * * * *
  61182. **
  61183. ** Force the value in register P1 to be text.
  61184. ** If the value is numeric, convert it to a string using the
  61185. ** equivalent of printf(). Blob values are unchanged and
  61186. ** are afterwards simply interpreted as text.
  61187. **
  61188. ** A NULL value is not changed by this routine. It remains NULL.
  61189. */
  61190. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  61191. pIn1 = &aMem[pOp->p1];
  61192. memAboutToChange(p, pIn1);
  61193. if( pIn1->flags & MEM_Null ) break;
  61194. assert( MEM_Str==(MEM_Blob>>3) );
  61195. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  61196. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  61197. rc = ExpandBlob(pIn1);
  61198. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  61199. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  61200. UPDATE_MAX_BLOBSIZE(pIn1);
  61201. break;
  61202. }
  61203. /* Opcode: ToBlob P1 * * * *
  61204. **
  61205. ** Force the value in register P1 to be a BLOB.
  61206. ** If the value is numeric, convert it to a string first.
  61207. ** Strings are simply reinterpreted as blobs with no change
  61208. ** to the underlying data.
  61209. **
  61210. ** A NULL value is not changed by this routine. It remains NULL.
  61211. */
  61212. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  61213. pIn1 = &aMem[pOp->p1];
  61214. if( pIn1->flags & MEM_Null ) break;
  61215. if( (pIn1->flags & MEM_Blob)==0 ){
  61216. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  61217. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  61218. MemSetTypeFlag(pIn1, MEM_Blob);
  61219. }else{
  61220. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  61221. }
  61222. UPDATE_MAX_BLOBSIZE(pIn1);
  61223. break;
  61224. }
  61225. /* Opcode: ToNumeric P1 * * * *
  61226. **
  61227. ** Force the value in register P1 to be numeric (either an
  61228. ** integer or a floating-point number.)
  61229. ** If the value is text or blob, try to convert it to an using the
  61230. ** equivalent of atoi() or atof() and store 0 if no such conversion
  61231. ** is possible.
  61232. **
  61233. ** A NULL value is not changed by this routine. It remains NULL.
  61234. */
  61235. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  61236. pIn1 = &aMem[pOp->p1];
  61237. sqlite3VdbeMemNumerify(pIn1);
  61238. break;
  61239. }
  61240. #endif /* SQLITE_OMIT_CAST */
  61241. /* Opcode: ToInt P1 * * * *
  61242. **
  61243. ** Force the value in register P1 to be an integer. If
  61244. ** The value is currently a real number, drop its fractional part.
  61245. ** If the value is text or blob, try to convert it to an integer using the
  61246. ** equivalent of atoi() and store 0 if no such conversion is possible.
  61247. **
  61248. ** A NULL value is not changed by this routine. It remains NULL.
  61249. */
  61250. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  61251. pIn1 = &aMem[pOp->p1];
  61252. if( (pIn1->flags & MEM_Null)==0 ){
  61253. sqlite3VdbeMemIntegerify(pIn1);
  61254. }
  61255. break;
  61256. }
  61257. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  61258. /* Opcode: ToReal P1 * * * *
  61259. **
  61260. ** Force the value in register P1 to be a floating point number.
  61261. ** If The value is currently an integer, convert it.
  61262. ** If the value is text or blob, try to convert it to an integer using the
  61263. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  61264. **
  61265. ** A NULL value is not changed by this routine. It remains NULL.
  61266. */
  61267. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  61268. pIn1 = &aMem[pOp->p1];
  61269. memAboutToChange(p, pIn1);
  61270. if( (pIn1->flags & MEM_Null)==0 ){
  61271. sqlite3VdbeMemRealify(pIn1);
  61272. }
  61273. break;
  61274. }
  61275. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  61276. /* Opcode: Lt P1 P2 P3 P4 P5
  61277. **
  61278. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  61279. ** jump to address P2.
  61280. **
  61281. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  61282. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  61283. ** bit is clear then fall through if either operand is NULL.
  61284. **
  61285. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  61286. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  61287. ** to coerce both inputs according to this affinity before the
  61288. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  61289. ** affinity is used. Note that the affinity conversions are stored
  61290. ** back into the input registers P1 and P3. So this opcode can cause
  61291. ** persistent changes to registers P1 and P3.
  61292. **
  61293. ** Once any conversions have taken place, and neither value is NULL,
  61294. ** the values are compared. If both values are blobs then memcmp() is
  61295. ** used to determine the results of the comparison. If both values
  61296. ** are text, then the appropriate collating function specified in
  61297. ** P4 is used to do the comparison. If P4 is not specified then
  61298. ** memcmp() is used to compare text string. If both values are
  61299. ** numeric, then a numeric comparison is used. If the two values
  61300. ** are of different types, then numbers are considered less than
  61301. ** strings and strings are considered less than blobs.
  61302. **
  61303. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  61304. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  61305. **
  61306. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  61307. ** equal to one another, provided that they do not have their MEM_Cleared
  61308. ** bit set.
  61309. */
  61310. /* Opcode: Ne P1 P2 P3 P4 P5
  61311. **
  61312. ** This works just like the Lt opcode except that the jump is taken if
  61313. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  61314. ** additional information.
  61315. **
  61316. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  61317. ** true or false and is never NULL. If both operands are NULL then the result
  61318. ** of comparison is false. If either operand is NULL then the result is true.
  61319. ** If neither operand is NULL the result is the same as it would be if
  61320. ** the SQLITE_NULLEQ flag were omitted from P5.
  61321. */
  61322. /* Opcode: Eq P1 P2 P3 P4 P5
  61323. **
  61324. ** This works just like the Lt opcode except that the jump is taken if
  61325. ** the operands in registers P1 and P3 are equal.
  61326. ** See the Lt opcode for additional information.
  61327. **
  61328. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  61329. ** true or false and is never NULL. If both operands are NULL then the result
  61330. ** of comparison is true. If either operand is NULL then the result is false.
  61331. ** If neither operand is NULL the result is the same as it would be if
  61332. ** the SQLITE_NULLEQ flag were omitted from P5.
  61333. */
  61334. /* Opcode: Le P1 P2 P3 P4 P5
  61335. **
  61336. ** This works just like the Lt opcode except that the jump is taken if
  61337. ** the content of register P3 is less than or equal to the content of
  61338. ** register P1. See the Lt opcode for additional information.
  61339. */
  61340. /* Opcode: Gt P1 P2 P3 P4 P5
  61341. **
  61342. ** This works just like the Lt opcode except that the jump is taken if
  61343. ** the content of register P3 is greater than the content of
  61344. ** register P1. See the Lt opcode for additional information.
  61345. */
  61346. /* Opcode: Ge P1 P2 P3 P4 P5
  61347. **
  61348. ** This works just like the Lt opcode except that the jump is taken if
  61349. ** the content of register P3 is greater than or equal to the content of
  61350. ** register P1. See the Lt opcode for additional information.
  61351. */
  61352. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  61353. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  61354. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  61355. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  61356. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  61357. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  61358. #if 0 /* local variables moved into u.ak */
  61359. int res; /* Result of the comparison of pIn1 against pIn3 */
  61360. char affinity; /* Affinity to use for comparison */
  61361. u16 flags1; /* Copy of initial value of pIn1->flags */
  61362. u16 flags3; /* Copy of initial value of pIn3->flags */
  61363. #endif /* local variables moved into u.ak */
  61364. pIn1 = &aMem[pOp->p1];
  61365. pIn3 = &aMem[pOp->p3];
  61366. u.ak.flags1 = pIn1->flags;
  61367. u.ak.flags3 = pIn3->flags;
  61368. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  61369. /* One or both operands are NULL */
  61370. if( pOp->p5 & SQLITE_NULLEQ ){
  61371. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  61372. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  61373. ** or not both operands are null.
  61374. */
  61375. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  61376. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  61377. if( (u.ak.flags1&MEM_Null)!=0
  61378. && (u.ak.flags3&MEM_Null)!=0
  61379. && (u.ak.flags3&MEM_Cleared)==0
  61380. ){
  61381. u.ak.res = 0; /* Results are equal */
  61382. }else{
  61383. u.ak.res = 1; /* Results are not equal */
  61384. }
  61385. }else{
  61386. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  61387. ** then the result is always NULL.
  61388. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  61389. */
  61390. if( pOp->p5 & SQLITE_STOREP2 ){
  61391. pOut = &aMem[pOp->p2];
  61392. MemSetTypeFlag(pOut, MEM_Null);
  61393. REGISTER_TRACE(pOp->p2, pOut);
  61394. }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
  61395. pc = pOp->p2-1;
  61396. }
  61397. break;
  61398. }
  61399. }else{
  61400. /* Neither operand is NULL. Do a comparison. */
  61401. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  61402. if( u.ak.affinity ){
  61403. applyAffinity(pIn1, u.ak.affinity, encoding);
  61404. applyAffinity(pIn3, u.ak.affinity, encoding);
  61405. if( db->mallocFailed ) goto no_mem;
  61406. }
  61407. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  61408. ExpandBlob(pIn1);
  61409. ExpandBlob(pIn3);
  61410. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  61411. }
  61412. switch( pOp->opcode ){
  61413. case OP_Eq: u.ak.res = u.ak.res==0; break;
  61414. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  61415. case OP_Lt: u.ak.res = u.ak.res<0; break;
  61416. case OP_Le: u.ak.res = u.ak.res<=0; break;
  61417. case OP_Gt: u.ak.res = u.ak.res>0; break;
  61418. default: u.ak.res = u.ak.res>=0; break;
  61419. }
  61420. if( pOp->p5 & SQLITE_STOREP2 ){
  61421. pOut = &aMem[pOp->p2];
  61422. memAboutToChange(p, pOut);
  61423. MemSetTypeFlag(pOut, MEM_Int);
  61424. pOut->u.i = u.ak.res;
  61425. REGISTER_TRACE(pOp->p2, pOut);
  61426. }else if( u.ak.res ){
  61427. pc = pOp->p2-1;
  61428. }
  61429. /* Undo any changes made by applyAffinity() to the input registers. */
  61430. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  61431. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  61432. break;
  61433. }
  61434. /* Opcode: Permutation * * * P4 *
  61435. **
  61436. ** Set the permutation used by the OP_Compare operator to be the array
  61437. ** of integers in P4.
  61438. **
  61439. ** The permutation is only valid until the next OP_Compare that has
  61440. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  61441. ** occur immediately prior to the OP_Compare.
  61442. */
  61443. case OP_Permutation: {
  61444. assert( pOp->p4type==P4_INTARRAY );
  61445. assert( pOp->p4.ai );
  61446. aPermute = pOp->p4.ai;
  61447. break;
  61448. }
  61449. /* Opcode: Compare P1 P2 P3 P4 P5
  61450. **
  61451. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  61452. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  61453. ** the comparison for use by the next OP_Jump instruct.
  61454. **
  61455. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  61456. ** determined by the most recent OP_Permutation operator. If the
  61457. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  61458. ** order.
  61459. **
  61460. ** P4 is a KeyInfo structure that defines collating sequences and sort
  61461. ** orders for the comparison. The permutation applies to registers
  61462. ** only. The KeyInfo elements are used sequentially.
  61463. **
  61464. ** The comparison is a sort comparison, so NULLs compare equal,
  61465. ** NULLs are less than numbers, numbers are less than strings,
  61466. ** and strings are less than blobs.
  61467. */
  61468. case OP_Compare: {
  61469. #if 0 /* local variables moved into u.al */
  61470. int n;
  61471. int i;
  61472. int p1;
  61473. int p2;
  61474. const KeyInfo *pKeyInfo;
  61475. int idx;
  61476. CollSeq *pColl; /* Collating sequence to use on this term */
  61477. int bRev; /* True for DESCENDING sort order */
  61478. #endif /* local variables moved into u.al */
  61479. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  61480. u.al.n = pOp->p3;
  61481. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  61482. assert( u.al.n>0 );
  61483. assert( u.al.pKeyInfo!=0 );
  61484. u.al.p1 = pOp->p1;
  61485. u.al.p2 = pOp->p2;
  61486. #if SQLITE_DEBUG
  61487. if( aPermute ){
  61488. int k, mx = 0;
  61489. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  61490. assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
  61491. assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
  61492. }else{
  61493. assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
  61494. assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
  61495. }
  61496. #endif /* SQLITE_DEBUG */
  61497. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  61498. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  61499. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  61500. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  61501. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  61502. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  61503. assert( u.al.i<u.al.pKeyInfo->nField );
  61504. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  61505. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  61506. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  61507. if( iCompare ){
  61508. if( u.al.bRev ) iCompare = -iCompare;
  61509. break;
  61510. }
  61511. }
  61512. aPermute = 0;
  61513. break;
  61514. }
  61515. /* Opcode: Jump P1 P2 P3 * *
  61516. **
  61517. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  61518. ** in the most recent OP_Compare instruction the P1 vector was less than
  61519. ** equal to, or greater than the P2 vector, respectively.
  61520. */
  61521. case OP_Jump: { /* jump */
  61522. if( iCompare<0 ){
  61523. pc = pOp->p1 - 1;
  61524. }else if( iCompare==0 ){
  61525. pc = pOp->p2 - 1;
  61526. }else{
  61527. pc = pOp->p3 - 1;
  61528. }
  61529. break;
  61530. }
  61531. /* Opcode: And P1 P2 P3 * *
  61532. **
  61533. ** Take the logical AND of the values in registers P1 and P2 and
  61534. ** write the result into register P3.
  61535. **
  61536. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  61537. ** the other input is NULL. A NULL and true or two NULLs give
  61538. ** a NULL output.
  61539. */
  61540. /* Opcode: Or P1 P2 P3 * *
  61541. **
  61542. ** Take the logical OR of the values in register P1 and P2 and
  61543. ** store the answer in register P3.
  61544. **
  61545. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  61546. ** even if the other input is NULL. A NULL and false or two NULLs
  61547. ** give a NULL output.
  61548. */
  61549. case OP_And: /* same as TK_AND, in1, in2, out3 */
  61550. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  61551. #if 0 /* local variables moved into u.am */
  61552. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61553. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  61554. #endif /* local variables moved into u.am */
  61555. pIn1 = &aMem[pOp->p1];
  61556. if( pIn1->flags & MEM_Null ){
  61557. u.am.v1 = 2;
  61558. }else{
  61559. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  61560. }
  61561. pIn2 = &aMem[pOp->p2];
  61562. if( pIn2->flags & MEM_Null ){
  61563. u.am.v2 = 2;
  61564. }else{
  61565. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  61566. }
  61567. if( pOp->opcode==OP_And ){
  61568. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  61569. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  61570. }else{
  61571. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  61572. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  61573. }
  61574. pOut = &aMem[pOp->p3];
  61575. if( u.am.v1==2 ){
  61576. MemSetTypeFlag(pOut, MEM_Null);
  61577. }else{
  61578. pOut->u.i = u.am.v1;
  61579. MemSetTypeFlag(pOut, MEM_Int);
  61580. }
  61581. break;
  61582. }
  61583. /* Opcode: Not P1 P2 * * *
  61584. **
  61585. ** Interpret the value in register P1 as a boolean value. Store the
  61586. ** boolean complement in register P2. If the value in register P1 is
  61587. ** NULL, then a NULL is stored in P2.
  61588. */
  61589. case OP_Not: { /* same as TK_NOT, in1, out2 */
  61590. pIn1 = &aMem[pOp->p1];
  61591. pOut = &aMem[pOp->p2];
  61592. if( pIn1->flags & MEM_Null ){
  61593. sqlite3VdbeMemSetNull(pOut);
  61594. }else{
  61595. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  61596. }
  61597. break;
  61598. }
  61599. /* Opcode: BitNot P1 P2 * * *
  61600. **
  61601. ** Interpret the content of register P1 as an integer. Store the
  61602. ** ones-complement of the P1 value into register P2. If P1 holds
  61603. ** a NULL then store a NULL in P2.
  61604. */
  61605. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  61606. pIn1 = &aMem[pOp->p1];
  61607. pOut = &aMem[pOp->p2];
  61608. if( pIn1->flags & MEM_Null ){
  61609. sqlite3VdbeMemSetNull(pOut);
  61610. }else{
  61611. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  61612. }
  61613. break;
  61614. }
  61615. /* Opcode: Once P1 P2 * * *
  61616. **
  61617. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  61618. ** set the flag and fall through to the next instruction.
  61619. */
  61620. case OP_Once: { /* jump */
  61621. assert( pOp->p1<p->nOnceFlag );
  61622. if( p->aOnceFlag[pOp->p1] ){
  61623. pc = pOp->p2-1;
  61624. }else{
  61625. p->aOnceFlag[pOp->p1] = 1;
  61626. }
  61627. break;
  61628. }
  61629. /* Opcode: If P1 P2 P3 * *
  61630. **
  61631. ** Jump to P2 if the value in register P1 is true. The value
  61632. ** is considered true if it is numeric and non-zero. If the value
  61633. ** in P1 is NULL then take the jump if P3 is non-zero.
  61634. */
  61635. /* Opcode: IfNot P1 P2 P3 * *
  61636. **
  61637. ** Jump to P2 if the value in register P1 is False. The value
  61638. ** is considered false if it has a numeric value of zero. If the value
  61639. ** in P1 is NULL then take the jump if P3 is zero.
  61640. */
  61641. case OP_If: /* jump, in1 */
  61642. case OP_IfNot: { /* jump, in1 */
  61643. #if 0 /* local variables moved into u.an */
  61644. int c;
  61645. #endif /* local variables moved into u.an */
  61646. pIn1 = &aMem[pOp->p1];
  61647. if( pIn1->flags & MEM_Null ){
  61648. u.an.c = pOp->p3;
  61649. }else{
  61650. #ifdef SQLITE_OMIT_FLOATING_POINT
  61651. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  61652. #else
  61653. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  61654. #endif
  61655. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  61656. }
  61657. if( u.an.c ){
  61658. pc = pOp->p2-1;
  61659. }
  61660. break;
  61661. }
  61662. /* Opcode: IsNull P1 P2 * * *
  61663. **
  61664. ** Jump to P2 if the value in register P1 is NULL.
  61665. */
  61666. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  61667. pIn1 = &aMem[pOp->p1];
  61668. if( (pIn1->flags & MEM_Null)!=0 ){
  61669. pc = pOp->p2 - 1;
  61670. }
  61671. break;
  61672. }
  61673. /* Opcode: NotNull P1 P2 * * *
  61674. **
  61675. ** Jump to P2 if the value in register P1 is not NULL.
  61676. */
  61677. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  61678. pIn1 = &aMem[pOp->p1];
  61679. if( (pIn1->flags & MEM_Null)==0 ){
  61680. pc = pOp->p2 - 1;
  61681. }
  61682. break;
  61683. }
  61684. /* Opcode: Column P1 P2 P3 P4 P5
  61685. **
  61686. ** Interpret the data that cursor P1 points to as a structure built using
  61687. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  61688. ** information about the format of the data.) Extract the P2-th column
  61689. ** from this record. If there are less that (P2+1)
  61690. ** values in the record, extract a NULL.
  61691. **
  61692. ** The value extracted is stored in register P3.
  61693. **
  61694. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  61695. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  61696. ** the result.
  61697. **
  61698. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  61699. ** then the cache of the cursor is reset prior to extracting the column.
  61700. ** The first OP_Column against a pseudo-table after the value of the content
  61701. ** register has changed should have this bit set.
  61702. **
  61703. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  61704. ** the result is guaranteed to only be used as the argument of a length()
  61705. ** or typeof() function, respectively. The loading of large blobs can be
  61706. ** skipped for length() and all content loading can be skipped for typeof().
  61707. */
  61708. case OP_Column: {
  61709. #if 0 /* local variables moved into u.ao */
  61710. u32 payloadSize; /* Number of bytes in the record */
  61711. i64 payloadSize64; /* Number of bytes in the record */
  61712. int p1; /* P1 value of the opcode */
  61713. int p2; /* column number to retrieve */
  61714. VdbeCursor *pC; /* The VDBE cursor */
  61715. char *zRec; /* Pointer to complete record-data */
  61716. BtCursor *pCrsr; /* The BTree cursor */
  61717. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  61718. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  61719. int nField; /* number of fields in the record */
  61720. int len; /* The length of the serialized data for the column */
  61721. int i; /* Loop counter */
  61722. char *zData; /* Part of the record being decoded */
  61723. Mem *pDest; /* Where to write the extracted value */
  61724. Mem sMem; /* For storing the record being decoded */
  61725. u8 *zIdx; /* Index into header */
  61726. u8 *zEndHdr; /* Pointer to first byte after the header */
  61727. u32 offset; /* Offset into the data */
  61728. u32 szField; /* Number of bytes in the content of a field */
  61729. int szHdr; /* Size of the header size field at start of record */
  61730. int avail; /* Number of bytes of available data */
  61731. u32 t; /* A type code from the record header */
  61732. Mem *pReg; /* PseudoTable input register */
  61733. #endif /* local variables moved into u.ao */
  61734. u.ao.p1 = pOp->p1;
  61735. u.ao.p2 = pOp->p2;
  61736. u.ao.pC = 0;
  61737. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  61738. assert( u.ao.p1<p->nCursor );
  61739. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  61740. u.ao.pDest = &aMem[pOp->p3];
  61741. memAboutToChange(p, u.ao.pDest);
  61742. u.ao.zRec = 0;
  61743. /* This block sets the variable u.ao.payloadSize to be the total number of
  61744. ** bytes in the record.
  61745. **
  61746. ** u.ao.zRec is set to be the complete text of the record if it is available.
  61747. ** The complete record text is always available for pseudo-tables
  61748. ** If the record is stored in a cursor, the complete record text
  61749. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  61750. ** If the data is unavailable, u.ao.zRec is set to NULL.
  61751. **
  61752. ** We also compute the number of columns in the record. For cursors,
  61753. ** the number of columns is stored in the VdbeCursor.nField element.
  61754. */
  61755. u.ao.pC = p->apCsr[u.ao.p1];
  61756. assert( u.ao.pC!=0 );
  61757. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61758. assert( u.ao.pC->pVtabCursor==0 );
  61759. #endif
  61760. u.ao.pCrsr = u.ao.pC->pCursor;
  61761. if( u.ao.pCrsr!=0 ){
  61762. /* The record is stored in a B-Tree */
  61763. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  61764. if( rc ) goto abort_due_to_error;
  61765. if( u.ao.pC->nullRow ){
  61766. u.ao.payloadSize = 0;
  61767. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  61768. u.ao.payloadSize = u.ao.pC->payloadSize;
  61769. u.ao.zRec = (char*)u.ao.pC->aRow;
  61770. }else if( u.ao.pC->isIndex ){
  61771. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  61772. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  61773. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  61774. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  61775. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  61776. ** larger than 32 bits. */
  61777. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  61778. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  61779. }else{
  61780. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  61781. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  61782. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  61783. }
  61784. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  61785. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  61786. if( u.ao.pC->multiPseudo ){
  61787. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  61788. Deephemeralize(u.ao.pDest);
  61789. goto op_column_out;
  61790. }
  61791. assert( u.ao.pReg->flags & MEM_Blob );
  61792. assert( memIsValid(u.ao.pReg) );
  61793. u.ao.payloadSize = u.ao.pReg->n;
  61794. u.ao.zRec = u.ao.pReg->z;
  61795. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  61796. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  61797. }else{
  61798. /* Consider the row to be NULL */
  61799. u.ao.payloadSize = 0;
  61800. }
  61801. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  61802. ** nullRow or because of a corrupt database. */
  61803. if( u.ao.payloadSize==0 ){
  61804. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  61805. goto op_column_out;
  61806. }
  61807. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  61808. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  61809. goto too_big;
  61810. }
  61811. u.ao.nField = u.ao.pC->nField;
  61812. assert( u.ao.p2<u.ao.nField );
  61813. /* Read and parse the table header. Store the results of the parse
  61814. ** into the record header cache fields of the cursor.
  61815. */
  61816. u.ao.aType = u.ao.pC->aType;
  61817. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  61818. u.ao.aOffset = u.ao.pC->aOffset;
  61819. }else{
  61820. assert(u.ao.aType);
  61821. u.ao.avail = 0;
  61822. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  61823. u.ao.pC->payloadSize = u.ao.payloadSize;
  61824. u.ao.pC->cacheStatus = p->cacheCtr;
  61825. /* Figure out how many bytes are in the header */
  61826. if( u.ao.zRec ){
  61827. u.ao.zData = u.ao.zRec;
  61828. }else{
  61829. if( u.ao.pC->isIndex ){
  61830. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  61831. }else{
  61832. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  61833. }
  61834. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  61835. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  61836. ** having to make additional calls to fetch the content portion of
  61837. ** the record.
  61838. */
  61839. assert( u.ao.avail>=0 );
  61840. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  61841. u.ao.zRec = u.ao.zData;
  61842. u.ao.pC->aRow = (u8*)u.ao.zData;
  61843. }else{
  61844. u.ao.pC->aRow = 0;
  61845. }
  61846. }
  61847. /* The following assert is true in all cases except when
  61848. ** the database file has been corrupted externally.
  61849. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  61850. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  61851. /* Make sure a corrupt database has not given us an oversize header.
  61852. ** Do this now to avoid an oversize memory allocation.
  61853. **
  61854. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  61855. ** types use so much data space that there can only be 4096 and 32 of
  61856. ** them, respectively. So the maximum header length results from a
  61857. ** 3-byte type for each of the maximum of 32768 columns plus three
  61858. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  61859. */
  61860. if( u.ao.offset > 98307 ){
  61861. rc = SQLITE_CORRUPT_BKPT;
  61862. goto op_column_out;
  61863. }
  61864. /* Compute in u.ao.len the number of bytes of data we need to read in order
  61865. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  61866. ** u.ao.nField might be significantly less than the true number of columns
  61867. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  61868. ** We want to minimize u.ao.len in order to limit the size of the memory
  61869. ** allocation, especially if a corrupt database file has caused u.ao.offset
  61870. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  61871. ** still exceed Robson memory allocation limits on some configurations.
  61872. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  61873. ** will likely be much smaller since u.ao.nField will likely be less than
  61874. ** 20 or so. This insures that Robson memory allocation limits are
  61875. ** not exceeded even for corrupt database files.
  61876. */
  61877. u.ao.len = u.ao.nField*5 + 3;
  61878. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  61879. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  61880. ** record header in most cases. But they will fail to get the complete
  61881. ** record header if the record header does not fit on a single page
  61882. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  61883. ** acquire the complete header text.
  61884. */
  61885. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  61886. u.ao.sMem.flags = 0;
  61887. u.ao.sMem.db = 0;
  61888. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  61889. if( rc!=SQLITE_OK ){
  61890. goto op_column_out;
  61891. }
  61892. u.ao.zData = u.ao.sMem.z;
  61893. }
  61894. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  61895. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  61896. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  61897. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  61898. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  61899. ** of the record to the start of the data for the u.ao.i-th column
  61900. */
  61901. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  61902. if( u.ao.zIdx<u.ao.zEndHdr ){
  61903. u.ao.aOffset[u.ao.i] = u.ao.offset;
  61904. if( u.ao.zIdx[0]<0x80 ){
  61905. u.ao.t = u.ao.zIdx[0];
  61906. u.ao.zIdx++;
  61907. }else{
  61908. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  61909. }
  61910. u.ao.aType[u.ao.i] = u.ao.t;
  61911. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  61912. u.ao.offset += u.ao.szField;
  61913. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  61914. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  61915. break;
  61916. }
  61917. }else{
  61918. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  61919. ** record than SetNumColumns indicated there are columns in the
  61920. ** table. Set the u.ao.offset for any extra columns not present in
  61921. ** the record to 0. This tells code below to store the default value
  61922. ** for the column instead of deserializing a value from the record.
  61923. */
  61924. u.ao.aOffset[u.ao.i] = 0;
  61925. }
  61926. }
  61927. sqlite3VdbeMemRelease(&u.ao.sMem);
  61928. u.ao.sMem.flags = MEM_Null;
  61929. /* If we have read more header data than was contained in the header,
  61930. ** or if the end of the last field appears to be past the end of the
  61931. ** record, or if the end of the last field appears to be before the end
  61932. ** of the record (when all fields present), then we must be dealing
  61933. ** with a corrupt database.
  61934. */
  61935. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  61936. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  61937. rc = SQLITE_CORRUPT_BKPT;
  61938. goto op_column_out;
  61939. }
  61940. }
  61941. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  61942. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  61943. ** then there are not enough fields in the record to satisfy the
  61944. ** request. In this case, set the value NULL or to P4 if P4 is
  61945. ** a pointer to a Mem object.
  61946. */
  61947. if( u.ao.aOffset[u.ao.p2] ){
  61948. assert( rc==SQLITE_OK );
  61949. if( u.ao.zRec ){
  61950. /* This is the common case where the whole row fits on a single page */
  61951. VdbeMemRelease(u.ao.pDest);
  61952. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  61953. }else{
  61954. /* This branch happens only when the row overflows onto multiple pages */
  61955. u.ao.t = u.ao.aType[u.ao.p2];
  61956. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  61957. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  61958. ){
  61959. /* Content is irrelevant for the typeof() function and for
  61960. ** the length(X) function if X is a blob. So we might as well use
  61961. ** bogus content rather than reading content from disk. NULL works
  61962. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  61963. ** will work for everything else. */
  61964. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  61965. }else{
  61966. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  61967. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  61968. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  61969. &u.ao.sMem);
  61970. if( rc!=SQLITE_OK ){
  61971. goto op_column_out;
  61972. }
  61973. u.ao.zData = u.ao.sMem.z;
  61974. }
  61975. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  61976. }
  61977. u.ao.pDest->enc = encoding;
  61978. }else{
  61979. if( pOp->p4type==P4_MEM ){
  61980. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  61981. }else{
  61982. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  61983. }
  61984. }
  61985. /* If we dynamically allocated space to hold the data (in the
  61986. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  61987. ** dynamically allocated space over to the u.ao.pDest structure.
  61988. ** This prevents a memory copy.
  61989. */
  61990. if( u.ao.sMem.zMalloc ){
  61991. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  61992. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  61993. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  61994. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  61995. u.ao.pDest->flags |= MEM_Term;
  61996. u.ao.pDest->z = u.ao.sMem.z;
  61997. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  61998. }
  61999. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  62000. op_column_out:
  62001. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  62002. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  62003. break;
  62004. }
  62005. /* Opcode: Affinity P1 P2 * P4 *
  62006. **
  62007. ** Apply affinities to a range of P2 registers starting with P1.
  62008. **
  62009. ** P4 is a string that is P2 characters long. The nth character of the
  62010. ** string indicates the column affinity that should be used for the nth
  62011. ** memory cell in the range.
  62012. */
  62013. case OP_Affinity: {
  62014. #if 0 /* local variables moved into u.ap */
  62015. const char *zAffinity; /* The affinity to be applied */
  62016. char cAff; /* A single character of affinity */
  62017. #endif /* local variables moved into u.ap */
  62018. u.ap.zAffinity = pOp->p4.z;
  62019. assert( u.ap.zAffinity!=0 );
  62020. assert( u.ap.zAffinity[pOp->p2]==0 );
  62021. pIn1 = &aMem[pOp->p1];
  62022. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  62023. assert( pIn1 <= &p->aMem[p->nMem] );
  62024. assert( memIsValid(pIn1) );
  62025. ExpandBlob(pIn1);
  62026. applyAffinity(pIn1, u.ap.cAff, encoding);
  62027. pIn1++;
  62028. }
  62029. break;
  62030. }
  62031. /* Opcode: MakeRecord P1 P2 P3 P4 *
  62032. **
  62033. ** Convert P2 registers beginning with P1 into the [record format]
  62034. ** use as a data record in a database table or as a key
  62035. ** in an index. The OP_Column opcode can decode the record later.
  62036. **
  62037. ** P4 may be a string that is P2 characters long. The nth character of the
  62038. ** string indicates the column affinity that should be used for the nth
  62039. ** field of the index key.
  62040. **
  62041. ** The mapping from character to affinity is given by the SQLITE_AFF_
  62042. ** macros defined in sqliteInt.h.
  62043. **
  62044. ** If P4 is NULL then all index fields have the affinity NONE.
  62045. */
  62046. case OP_MakeRecord: {
  62047. #if 0 /* local variables moved into u.aq */
  62048. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  62049. Mem *pRec; /* The new record */
  62050. u64 nData; /* Number of bytes of data space */
  62051. int nHdr; /* Number of bytes of header space */
  62052. i64 nByte; /* Data space required for this record */
  62053. int nZero; /* Number of zero bytes at the end of the record */
  62054. int nVarint; /* Number of bytes in a varint */
  62055. u32 serial_type; /* Type field */
  62056. Mem *pData0; /* First field to be combined into the record */
  62057. Mem *pLast; /* Last field of the record */
  62058. int nField; /* Number of fields in the record */
  62059. char *zAffinity; /* The affinity string for the record */
  62060. int file_format; /* File format to use for encoding */
  62061. int i; /* Space used in zNewRecord[] */
  62062. int len; /* Length of a field */
  62063. #endif /* local variables moved into u.aq */
  62064. /* Assuming the record contains N fields, the record format looks
  62065. ** like this:
  62066. **
  62067. ** ------------------------------------------------------------------------
  62068. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  62069. ** ------------------------------------------------------------------------
  62070. **
  62071. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  62072. ** and so froth.
  62073. **
  62074. ** Each type field is a varint representing the serial type of the
  62075. ** corresponding data element (see sqlite3VdbeSerialType()). The
  62076. ** hdr-size field is also a varint which is the offset from the beginning
  62077. ** of the record to data0.
  62078. */
  62079. u.aq.nData = 0; /* Number of bytes of data space */
  62080. u.aq.nHdr = 0; /* Number of bytes of header space */
  62081. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  62082. u.aq.nField = pOp->p1;
  62083. u.aq.zAffinity = pOp->p4.z;
  62084. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
  62085. u.aq.pData0 = &aMem[u.aq.nField];
  62086. u.aq.nField = pOp->p2;
  62087. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  62088. u.aq.file_format = p->minWriteFileFormat;
  62089. /* Identify the output register */
  62090. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  62091. pOut = &aMem[pOp->p3];
  62092. memAboutToChange(p, pOut);
  62093. /* Loop through the elements that will make up the record to figure
  62094. ** out how much space is required for the new record.
  62095. */
  62096. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  62097. assert( memIsValid(u.aq.pRec) );
  62098. if( u.aq.zAffinity ){
  62099. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  62100. }
  62101. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  62102. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  62103. }
  62104. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  62105. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  62106. u.aq.nData += u.aq.len;
  62107. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  62108. if( u.aq.pRec->flags & MEM_Zero ){
  62109. /* Only pure zero-filled BLOBs can be input to this Opcode.
  62110. ** We do not allow blobs with a prefix and a zero-filled tail. */
  62111. u.aq.nZero += u.aq.pRec->u.nZero;
  62112. }else if( u.aq.len ){
  62113. u.aq.nZero = 0;
  62114. }
  62115. }
  62116. /* Add the initial header varint and total the size */
  62117. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  62118. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  62119. u.aq.nHdr++;
  62120. }
  62121. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  62122. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  62123. goto too_big;
  62124. }
  62125. /* Make sure the output register has a buffer large enough to store
  62126. ** the new record. The output register (pOp->p3) is not allowed to
  62127. ** be one of the input registers (because the following call to
  62128. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  62129. */
  62130. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  62131. goto no_mem;
  62132. }
  62133. u.aq.zNewRecord = (u8 *)pOut->z;
  62134. /* Write the record */
  62135. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  62136. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  62137. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  62138. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  62139. }
  62140. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  62141. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  62142. }
  62143. assert( u.aq.i==u.aq.nByte );
  62144. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  62145. pOut->n = (int)u.aq.nByte;
  62146. pOut->flags = MEM_Blob | MEM_Dyn;
  62147. pOut->xDel = 0;
  62148. if( u.aq.nZero ){
  62149. pOut->u.nZero = u.aq.nZero;
  62150. pOut->flags |= MEM_Zero;
  62151. }
  62152. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  62153. REGISTER_TRACE(pOp->p3, pOut);
  62154. UPDATE_MAX_BLOBSIZE(pOut);
  62155. break;
  62156. }
  62157. /* Opcode: Count P1 P2 * * *
  62158. **
  62159. ** Store the number of entries (an integer value) in the table or index
  62160. ** opened by cursor P1 in register P2
  62161. */
  62162. #ifndef SQLITE_OMIT_BTREECOUNT
  62163. case OP_Count: { /* out2-prerelease */
  62164. #if 0 /* local variables moved into u.ar */
  62165. i64 nEntry;
  62166. BtCursor *pCrsr;
  62167. #endif /* local variables moved into u.ar */
  62168. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  62169. if( ALWAYS(u.ar.pCrsr) ){
  62170. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  62171. }else{
  62172. u.ar.nEntry = 0;
  62173. }
  62174. pOut->u.i = u.ar.nEntry;
  62175. break;
  62176. }
  62177. #endif
  62178. /* Opcode: Savepoint P1 * * P4 *
  62179. **
  62180. ** Open, release or rollback the savepoint named by parameter P4, depending
  62181. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  62182. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  62183. */
  62184. case OP_Savepoint: {
  62185. #if 0 /* local variables moved into u.as */
  62186. int p1; /* Value of P1 operand */
  62187. char *zName; /* Name of savepoint */
  62188. int nName;
  62189. Savepoint *pNew;
  62190. Savepoint *pSavepoint;
  62191. Savepoint *pTmp;
  62192. int iSavepoint;
  62193. int ii;
  62194. #endif /* local variables moved into u.as */
  62195. u.as.p1 = pOp->p1;
  62196. u.as.zName = pOp->p4.z;
  62197. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  62198. ** transaction, then there cannot be any savepoints.
  62199. */
  62200. assert( db->pSavepoint==0 || db->autoCommit==0 );
  62201. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  62202. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  62203. assert( checkSavepointCount(db) );
  62204. if( u.as.p1==SAVEPOINT_BEGIN ){
  62205. if( db->writeVdbeCnt>0 ){
  62206. /* A new savepoint cannot be created if there are active write
  62207. ** statements (i.e. open read/write incremental blob handles).
  62208. */
  62209. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  62210. "SQL statements in progress");
  62211. rc = SQLITE_BUSY;
  62212. }else{
  62213. u.as.nName = sqlite3Strlen30(u.as.zName);
  62214. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62215. /* This call is Ok even if this savepoint is actually a transaction
  62216. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  62217. ** If this is a transaction savepoint being opened, it is guaranteed
  62218. ** that the db->aVTrans[] array is empty. */
  62219. assert( db->autoCommit==0 || db->nVTrans==0 );
  62220. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  62221. db->nStatement+db->nSavepoint);
  62222. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  62223. #endif
  62224. /* Create a new savepoint structure. */
  62225. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  62226. if( u.as.pNew ){
  62227. u.as.pNew->zName = (char *)&u.as.pNew[1];
  62228. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  62229. /* If there is no open transaction, then mark this as a special
  62230. ** "transaction savepoint". */
  62231. if( db->autoCommit ){
  62232. db->autoCommit = 0;
  62233. db->isTransactionSavepoint = 1;
  62234. }else{
  62235. db->nSavepoint++;
  62236. }
  62237. /* Link the new savepoint into the database handle's list. */
  62238. u.as.pNew->pNext = db->pSavepoint;
  62239. db->pSavepoint = u.as.pNew;
  62240. u.as.pNew->nDeferredCons = db->nDeferredCons;
  62241. }
  62242. }
  62243. }else{
  62244. u.as.iSavepoint = 0;
  62245. /* Find the named savepoint. If there is no such savepoint, then an
  62246. ** an error is returned to the user. */
  62247. for(
  62248. u.as.pSavepoint = db->pSavepoint;
  62249. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  62250. u.as.pSavepoint = u.as.pSavepoint->pNext
  62251. ){
  62252. u.as.iSavepoint++;
  62253. }
  62254. if( !u.as.pSavepoint ){
  62255. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  62256. rc = SQLITE_ERROR;
  62257. }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
  62258. /* It is not possible to release (commit) a savepoint if there are
  62259. ** active write statements.
  62260. */
  62261. sqlite3SetString(&p->zErrMsg, db,
  62262. "cannot release savepoint - SQL statements in progress"
  62263. );
  62264. rc = SQLITE_BUSY;
  62265. }else{
  62266. /* Determine whether or not this is a transaction savepoint. If so,
  62267. ** and this is a RELEASE command, then the current transaction
  62268. ** is committed.
  62269. */
  62270. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  62271. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  62272. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  62273. goto vdbe_return;
  62274. }
  62275. db->autoCommit = 1;
  62276. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  62277. p->pc = pc;
  62278. db->autoCommit = 0;
  62279. p->rc = rc = SQLITE_BUSY;
  62280. goto vdbe_return;
  62281. }
  62282. db->isTransactionSavepoint = 0;
  62283. rc = p->rc;
  62284. }else{
  62285. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  62286. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  62287. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  62288. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  62289. }
  62290. }
  62291. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  62292. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  62293. if( rc!=SQLITE_OK ){
  62294. goto abort_due_to_error;
  62295. }
  62296. }
  62297. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  62298. sqlite3ExpirePreparedStatements(db);
  62299. sqlite3ResetAllSchemasOfConnection(db);
  62300. db->flags = (db->flags | SQLITE_InternChanges);
  62301. }
  62302. }
  62303. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  62304. ** savepoints nested inside of the savepoint being operated on. */
  62305. while( db->pSavepoint!=u.as.pSavepoint ){
  62306. u.as.pTmp = db->pSavepoint;
  62307. db->pSavepoint = u.as.pTmp->pNext;
  62308. sqlite3DbFree(db, u.as.pTmp);
  62309. db->nSavepoint--;
  62310. }
  62311. /* If it is a RELEASE, then destroy the savepoint being operated on
  62312. ** too. If it is a ROLLBACK TO, then set the number of deferred
  62313. ** constraint violations present in the database to the value stored
  62314. ** when the savepoint was created. */
  62315. if( u.as.p1==SAVEPOINT_RELEASE ){
  62316. assert( u.as.pSavepoint==db->pSavepoint );
  62317. db->pSavepoint = u.as.pSavepoint->pNext;
  62318. sqlite3DbFree(db, u.as.pSavepoint);
  62319. if( !isTransaction ){
  62320. db->nSavepoint--;
  62321. }
  62322. }else{
  62323. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  62324. }
  62325. if( !isTransaction ){
  62326. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  62327. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  62328. }
  62329. }
  62330. }
  62331. break;
  62332. }
  62333. /* Opcode: AutoCommit P1 P2 * * *
  62334. **
  62335. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  62336. ** back any currently active btree transactions. If there are any active
  62337. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  62338. ** there are active writing VMs or active VMs that use shared cache.
  62339. **
  62340. ** This instruction causes the VM to halt.
  62341. */
  62342. case OP_AutoCommit: {
  62343. #if 0 /* local variables moved into u.at */
  62344. int desiredAutoCommit;
  62345. int iRollback;
  62346. int turnOnAC;
  62347. #endif /* local variables moved into u.at */
  62348. u.at.desiredAutoCommit = pOp->p1;
  62349. u.at.iRollback = pOp->p2;
  62350. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  62351. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  62352. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  62353. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  62354. #if 0
  62355. if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
  62356. /* If this instruction implements a ROLLBACK and other VMs are
  62357. ** still running, and a transaction is active, return an error indicating
  62358. ** that the other VMs must complete first.
  62359. */
  62360. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  62361. "SQL statements in progress");
  62362. rc = SQLITE_BUSY;
  62363. }else
  62364. #endif
  62365. if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
  62366. /* If this instruction implements a COMMIT and other VMs are writing
  62367. ** return an error indicating that the other VMs must complete first.
  62368. */
  62369. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  62370. "SQL statements in progress");
  62371. rc = SQLITE_BUSY;
  62372. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  62373. if( u.at.iRollback ){
  62374. assert( u.at.desiredAutoCommit==1 );
  62375. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  62376. db->autoCommit = 1;
  62377. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  62378. goto vdbe_return;
  62379. }else{
  62380. db->autoCommit = (u8)u.at.desiredAutoCommit;
  62381. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  62382. p->pc = pc;
  62383. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  62384. p->rc = rc = SQLITE_BUSY;
  62385. goto vdbe_return;
  62386. }
  62387. }
  62388. assert( db->nStatement==0 );
  62389. sqlite3CloseSavepoints(db);
  62390. if( p->rc==SQLITE_OK ){
  62391. rc = SQLITE_DONE;
  62392. }else{
  62393. rc = SQLITE_ERROR;
  62394. }
  62395. goto vdbe_return;
  62396. }else{
  62397. sqlite3SetString(&p->zErrMsg, db,
  62398. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  62399. (u.at.iRollback)?"cannot rollback - no transaction is active":
  62400. "cannot commit - no transaction is active"));
  62401. rc = SQLITE_ERROR;
  62402. }
  62403. break;
  62404. }
  62405. /* Opcode: Transaction P1 P2 * * *
  62406. **
  62407. ** Begin a transaction. The transaction ends when a Commit or Rollback
  62408. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  62409. ** transaction might also be rolled back if an error is encountered.
  62410. **
  62411. ** P1 is the index of the database file on which the transaction is
  62412. ** started. Index 0 is the main database file and index 1 is the
  62413. ** file used for temporary tables. Indices of 2 or more are used for
  62414. ** attached databases.
  62415. **
  62416. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  62417. ** obtained on the database file when a write-transaction is started. No
  62418. ** other process can start another write transaction while this transaction is
  62419. ** underway. Starting a write transaction also creates a rollback journal. A
  62420. ** write transaction must be started before any changes can be made to the
  62421. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  62422. ** on the file.
  62423. **
  62424. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  62425. ** true (this flag is set if the Vdbe may modify more than one row and may
  62426. ** throw an ABORT exception), a statement transaction may also be opened.
  62427. ** More specifically, a statement transaction is opened iff the database
  62428. ** connection is currently not in autocommit mode, or if there are other
  62429. ** active statements. A statement transaction allows the changes made by this
  62430. ** VDBE to be rolled back after an error without having to roll back the
  62431. ** entire transaction. If no error is encountered, the statement transaction
  62432. ** will automatically commit when the VDBE halts.
  62433. **
  62434. ** If P2 is zero, then a read-lock is obtained on the database file.
  62435. */
  62436. case OP_Transaction: {
  62437. #if 0 /* local variables moved into u.au */
  62438. Btree *pBt;
  62439. #endif /* local variables moved into u.au */
  62440. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  62441. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  62442. u.au.pBt = db->aDb[pOp->p1].pBt;
  62443. if( u.au.pBt ){
  62444. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  62445. if( rc==SQLITE_BUSY ){
  62446. p->pc = pc;
  62447. p->rc = rc = SQLITE_BUSY;
  62448. goto vdbe_return;
  62449. }
  62450. if( rc!=SQLITE_OK ){
  62451. goto abort_due_to_error;
  62452. }
  62453. if( pOp->p2 && p->usesStmtJournal
  62454. && (db->autoCommit==0 || db->activeVdbeCnt>1)
  62455. ){
  62456. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  62457. if( p->iStatement==0 ){
  62458. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  62459. db->nStatement++;
  62460. p->iStatement = db->nSavepoint + db->nStatement;
  62461. }
  62462. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  62463. if( rc==SQLITE_OK ){
  62464. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  62465. }
  62466. /* Store the current value of the database handles deferred constraint
  62467. ** counter. If the statement transaction needs to be rolled back,
  62468. ** the value of this counter needs to be restored too. */
  62469. p->nStmtDefCons = db->nDeferredCons;
  62470. }
  62471. }
  62472. break;
  62473. }
  62474. /* Opcode: ReadCookie P1 P2 P3 * *
  62475. **
  62476. ** Read cookie number P3 from database P1 and write it into register P2.
  62477. ** P3==1 is the schema version. P3==2 is the database format.
  62478. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  62479. ** the main database file and P1==1 is the database file used to store
  62480. ** temporary tables.
  62481. **
  62482. ** There must be a read-lock on the database (either a transaction
  62483. ** must be started or there must be an open cursor) before
  62484. ** executing this instruction.
  62485. */
  62486. case OP_ReadCookie: { /* out2-prerelease */
  62487. #if 0 /* local variables moved into u.av */
  62488. int iMeta;
  62489. int iDb;
  62490. int iCookie;
  62491. #endif /* local variables moved into u.av */
  62492. u.av.iDb = pOp->p1;
  62493. u.av.iCookie = pOp->p3;
  62494. assert( pOp->p3<SQLITE_N_BTREE_META );
  62495. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  62496. assert( db->aDb[u.av.iDb].pBt!=0 );
  62497. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  62498. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  62499. pOut->u.i = u.av.iMeta;
  62500. break;
  62501. }
  62502. /* Opcode: SetCookie P1 P2 P3 * *
  62503. **
  62504. ** Write the content of register P3 (interpreted as an integer)
  62505. ** into cookie number P2 of database P1. P2==1 is the schema version.
  62506. ** P2==2 is the database format. P2==3 is the recommended pager cache
  62507. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  62508. ** database file used to store temporary tables.
  62509. **
  62510. ** A transaction must be started before executing this opcode.
  62511. */
  62512. case OP_SetCookie: { /* in3 */
  62513. #if 0 /* local variables moved into u.aw */
  62514. Db *pDb;
  62515. #endif /* local variables moved into u.aw */
  62516. assert( pOp->p2<SQLITE_N_BTREE_META );
  62517. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  62518. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  62519. u.aw.pDb = &db->aDb[pOp->p1];
  62520. assert( u.aw.pDb->pBt!=0 );
  62521. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  62522. pIn3 = &aMem[pOp->p3];
  62523. sqlite3VdbeMemIntegerify(pIn3);
  62524. /* See note about index shifting on OP_ReadCookie */
  62525. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  62526. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  62527. /* When the schema cookie changes, record the new cookie internally */
  62528. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  62529. db->flags |= SQLITE_InternChanges;
  62530. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  62531. /* Record changes in the file format */
  62532. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  62533. }
  62534. if( pOp->p1==1 ){
  62535. /* Invalidate all prepared statements whenever the TEMP database
  62536. ** schema is changed. Ticket #1644 */
  62537. sqlite3ExpirePreparedStatements(db);
  62538. p->expired = 0;
  62539. }
  62540. break;
  62541. }
  62542. /* Opcode: VerifyCookie P1 P2 P3 * *
  62543. **
  62544. ** Check the value of global database parameter number 0 (the
  62545. ** schema version) and make sure it is equal to P2 and that the
  62546. ** generation counter on the local schema parse equals P3.
  62547. **
  62548. ** P1 is the database number which is 0 for the main database file
  62549. ** and 1 for the file holding temporary tables and some higher number
  62550. ** for auxiliary databases.
  62551. **
  62552. ** The cookie changes its value whenever the database schema changes.
  62553. ** This operation is used to detect when that the cookie has changed
  62554. ** and that the current process needs to reread the schema.
  62555. **
  62556. ** Either a transaction needs to have been started or an OP_Open needs
  62557. ** to be executed (to establish a read lock) before this opcode is
  62558. ** invoked.
  62559. */
  62560. case OP_VerifyCookie: {
  62561. #if 0 /* local variables moved into u.ax */
  62562. int iMeta;
  62563. int iGen;
  62564. Btree *pBt;
  62565. #endif /* local variables moved into u.ax */
  62566. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  62567. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  62568. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  62569. u.ax.pBt = db->aDb[pOp->p1].pBt;
  62570. if( u.ax.pBt ){
  62571. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  62572. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  62573. }else{
  62574. u.ax.iGen = u.ax.iMeta = 0;
  62575. }
  62576. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  62577. sqlite3DbFree(db, p->zErrMsg);
  62578. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  62579. /* If the schema-cookie from the database file matches the cookie
  62580. ** stored with the in-memory representation of the schema, do
  62581. ** not reload the schema from the database file.
  62582. **
  62583. ** If virtual-tables are in use, this is not just an optimization.
  62584. ** Often, v-tables store their data in other SQLite tables, which
  62585. ** are queried from within xNext() and other v-table methods using
  62586. ** prepared queries. If such a query is out-of-date, we do not want to
  62587. ** discard the database schema, as the user code implementing the
  62588. ** v-table would have to be ready for the sqlite3_vtab structure itself
  62589. ** to be invalidated whenever sqlite3_step() is called from within
  62590. ** a v-table method.
  62591. */
  62592. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  62593. sqlite3ResetOneSchema(db, pOp->p1);
  62594. }
  62595. p->expired = 1;
  62596. rc = SQLITE_SCHEMA;
  62597. }
  62598. break;
  62599. }
  62600. /* Opcode: OpenRead P1 P2 P3 P4 P5
  62601. **
  62602. ** Open a read-only cursor for the database table whose root page is
  62603. ** P2 in a database file. The database file is determined by P3.
  62604. ** P3==0 means the main database, P3==1 means the database used for
  62605. ** temporary tables, and P3>1 means used the corresponding attached
  62606. ** database. Give the new cursor an identifier of P1. The P1
  62607. ** values need not be contiguous but all P1 values should be small integers.
  62608. ** It is an error for P1 to be negative.
  62609. **
  62610. ** If P5!=0 then use the content of register P2 as the root page, not
  62611. ** the value of P2 itself.
  62612. **
  62613. ** There will be a read lock on the database whenever there is an
  62614. ** open cursor. If the database was unlocked prior to this instruction
  62615. ** then a read lock is acquired as part of this instruction. A read
  62616. ** lock allows other processes to read the database but prohibits
  62617. ** any other process from modifying the database. The read lock is
  62618. ** released when all cursors are closed. If this instruction attempts
  62619. ** to get a read lock but fails, the script terminates with an
  62620. ** SQLITE_BUSY error code.
  62621. **
  62622. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  62623. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  62624. ** structure, then said structure defines the content and collating
  62625. ** sequence of the index being opened. Otherwise, if P4 is an integer
  62626. ** value, it is set to the number of columns in the table.
  62627. **
  62628. ** See also OpenWrite.
  62629. */
  62630. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  62631. **
  62632. ** Open a read/write cursor named P1 on the table or index whose root
  62633. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  62634. ** root page.
  62635. **
  62636. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  62637. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  62638. ** structure, then said structure defines the content and collating
  62639. ** sequence of the index being opened. Otherwise, if P4 is an integer
  62640. ** value, it is set to the number of columns in the table, or to the
  62641. ** largest index of any column of the table that is actually used.
  62642. **
  62643. ** This instruction works just like OpenRead except that it opens the cursor
  62644. ** in read/write mode. For a given table, there can be one or more read-only
  62645. ** cursors or a single read/write cursor but not both.
  62646. **
  62647. ** See also OpenRead.
  62648. */
  62649. case OP_OpenRead:
  62650. case OP_OpenWrite: {
  62651. #if 0 /* local variables moved into u.ay */
  62652. int nField;
  62653. KeyInfo *pKeyInfo;
  62654. int p2;
  62655. int iDb;
  62656. int wrFlag;
  62657. Btree *pX;
  62658. VdbeCursor *pCur;
  62659. Db *pDb;
  62660. #endif /* local variables moved into u.ay */
  62661. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  62662. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  62663. if( p->expired ){
  62664. rc = SQLITE_ABORT;
  62665. break;
  62666. }
  62667. u.ay.nField = 0;
  62668. u.ay.pKeyInfo = 0;
  62669. u.ay.p2 = pOp->p2;
  62670. u.ay.iDb = pOp->p3;
  62671. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  62672. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  62673. u.ay.pDb = &db->aDb[u.ay.iDb];
  62674. u.ay.pX = u.ay.pDb->pBt;
  62675. assert( u.ay.pX!=0 );
  62676. if( pOp->opcode==OP_OpenWrite ){
  62677. u.ay.wrFlag = 1;
  62678. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  62679. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  62680. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  62681. }
  62682. }else{
  62683. u.ay.wrFlag = 0;
  62684. }
  62685. if( pOp->p5 & OPFLAG_P2ISREG ){
  62686. assert( u.ay.p2>0 );
  62687. assert( u.ay.p2<=p->nMem );
  62688. pIn2 = &aMem[u.ay.p2];
  62689. assert( memIsValid(pIn2) );
  62690. assert( (pIn2->flags & MEM_Int)!=0 );
  62691. sqlite3VdbeMemIntegerify(pIn2);
  62692. u.ay.p2 = (int)pIn2->u.i;
  62693. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  62694. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  62695. ** If there were a failure, the prepared statement would have halted
  62696. ** before reaching this instruction. */
  62697. if( NEVER(u.ay.p2<2) ) {
  62698. rc = SQLITE_CORRUPT_BKPT;
  62699. goto abort_due_to_error;
  62700. }
  62701. }
  62702. if( pOp->p4type==P4_KEYINFO ){
  62703. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  62704. u.ay.pKeyInfo->enc = ENC(p->db);
  62705. u.ay.nField = u.ay.pKeyInfo->nField+1;
  62706. }else if( pOp->p4type==P4_INT32 ){
  62707. u.ay.nField = pOp->p4.i;
  62708. }
  62709. assert( pOp->p1>=0 );
  62710. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  62711. if( u.ay.pCur==0 ) goto no_mem;
  62712. u.ay.pCur->nullRow = 1;
  62713. u.ay.pCur->isOrdered = 1;
  62714. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  62715. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  62716. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  62717. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  62718. /* Since it performs no memory allocation or IO, the only value that
  62719. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  62720. assert( rc==SQLITE_OK );
  62721. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  62722. ** SQLite used to check if the root-page flags were sane at this point
  62723. ** and report database corruption if they were not, but this check has
  62724. ** since moved into the btree layer. */
  62725. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  62726. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  62727. break;
  62728. }
  62729. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  62730. **
  62731. ** Open a new cursor P1 to a transient table.
  62732. ** The cursor is always opened read/write even if
  62733. ** the main database is read-only. The ephemeral
  62734. ** table is deleted automatically when the cursor is closed.
  62735. **
  62736. ** P2 is the number of columns in the ephemeral table.
  62737. ** The cursor points to a BTree table if P4==0 and to a BTree index
  62738. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  62739. ** that defines the format of keys in the index.
  62740. **
  62741. ** This opcode was once called OpenTemp. But that created
  62742. ** confusion because the term "temp table", might refer either
  62743. ** to a TEMP table at the SQL level, or to a table opened by
  62744. ** this opcode. Then this opcode was call OpenVirtual. But
  62745. ** that created confusion with the whole virtual-table idea.
  62746. **
  62747. ** The P5 parameter can be a mask of the BTREE_* flags defined
  62748. ** in btree.h. These flags control aspects of the operation of
  62749. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  62750. ** added automatically.
  62751. */
  62752. /* Opcode: OpenAutoindex P1 P2 * P4 *
  62753. **
  62754. ** This opcode works the same as OP_OpenEphemeral. It has a
  62755. ** different name to distinguish its use. Tables created using
  62756. ** by this opcode will be used for automatically created transient
  62757. ** indices in joins.
  62758. */
  62759. case OP_OpenAutoindex:
  62760. case OP_OpenEphemeral: {
  62761. #if 0 /* local variables moved into u.az */
  62762. VdbeCursor *pCx;
  62763. #endif /* local variables moved into u.az */
  62764. static const int vfsFlags =
  62765. SQLITE_OPEN_READWRITE |
  62766. SQLITE_OPEN_CREATE |
  62767. SQLITE_OPEN_EXCLUSIVE |
  62768. SQLITE_OPEN_DELETEONCLOSE |
  62769. SQLITE_OPEN_TRANSIENT_DB;
  62770. assert( pOp->p1>=0 );
  62771. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  62772. if( u.az.pCx==0 ) goto no_mem;
  62773. u.az.pCx->nullRow = 1;
  62774. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  62775. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  62776. if( rc==SQLITE_OK ){
  62777. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  62778. }
  62779. if( rc==SQLITE_OK ){
  62780. /* If a transient index is required, create it by calling
  62781. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  62782. ** opening it. If a transient table is required, just use the
  62783. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  62784. */
  62785. if( pOp->p4.pKeyInfo ){
  62786. int pgno;
  62787. assert( pOp->p4type==P4_KEYINFO );
  62788. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  62789. if( rc==SQLITE_OK ){
  62790. assert( pgno==MASTER_ROOT+1 );
  62791. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  62792. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  62793. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  62794. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  62795. }
  62796. u.az.pCx->isTable = 0;
  62797. }else{
  62798. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  62799. u.az.pCx->isTable = 1;
  62800. }
  62801. }
  62802. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  62803. u.az.pCx->isIndex = !u.az.pCx->isTable;
  62804. break;
  62805. }
  62806. /* Opcode: SorterOpen P1 P2 * P4 *
  62807. **
  62808. ** This opcode works like OP_OpenEphemeral except that it opens
  62809. ** a transient index that is specifically designed to sort large
  62810. ** tables using an external merge-sort algorithm.
  62811. */
  62812. case OP_SorterOpen: {
  62813. #if 0 /* local variables moved into u.ba */
  62814. VdbeCursor *pCx;
  62815. #endif /* local variables moved into u.ba */
  62816. #ifndef SQLITE_OMIT_MERGE_SORT
  62817. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  62818. if( u.ba.pCx==0 ) goto no_mem;
  62819. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  62820. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  62821. u.ba.pCx->isSorter = 1;
  62822. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  62823. #else
  62824. pOp->opcode = OP_OpenEphemeral;
  62825. pc--;
  62826. #endif
  62827. break;
  62828. }
  62829. /* Opcode: OpenPseudo P1 P2 P3 * P5
  62830. **
  62831. ** Open a new cursor that points to a fake table that contains a single
  62832. ** row of data. The content of that one row in the content of memory
  62833. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  62834. ** MEM_Blob content contained in register P2. When P5==1, then the
  62835. ** row is represented by P3 consecutive registers beginning with P2.
  62836. **
  62837. ** A pseudo-table created by this opcode is used to hold a single
  62838. ** row output from the sorter so that the row can be decomposed into
  62839. ** individual columns using the OP_Column opcode. The OP_Column opcode
  62840. ** is the only cursor opcode that works with a pseudo-table.
  62841. **
  62842. ** P3 is the number of fields in the records that will be stored by
  62843. ** the pseudo-table.
  62844. */
  62845. case OP_OpenPseudo: {
  62846. #if 0 /* local variables moved into u.bb */
  62847. VdbeCursor *pCx;
  62848. #endif /* local variables moved into u.bb */
  62849. assert( pOp->p1>=0 );
  62850. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  62851. if( u.bb.pCx==0 ) goto no_mem;
  62852. u.bb.pCx->nullRow = 1;
  62853. u.bb.pCx->pseudoTableReg = pOp->p2;
  62854. u.bb.pCx->isTable = 1;
  62855. u.bb.pCx->isIndex = 0;
  62856. u.bb.pCx->multiPseudo = pOp->p5;
  62857. break;
  62858. }
  62859. /* Opcode: Close P1 * * * *
  62860. **
  62861. ** Close a cursor previously opened as P1. If P1 is not
  62862. ** currently open, this instruction is a no-op.
  62863. */
  62864. case OP_Close: {
  62865. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62866. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  62867. p->apCsr[pOp->p1] = 0;
  62868. break;
  62869. }
  62870. /* Opcode: SeekGe P1 P2 P3 P4 *
  62871. **
  62872. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  62873. ** use the value in register P3 as the key. If cursor P1 refers
  62874. ** to an SQL index, then P3 is the first in an array of P4 registers
  62875. ** that are used as an unpacked index key.
  62876. **
  62877. ** Reposition cursor P1 so that it points to the smallest entry that
  62878. ** is greater than or equal to the key value. If there are no records
  62879. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  62880. **
  62881. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  62882. */
  62883. /* Opcode: SeekGt P1 P2 P3 P4 *
  62884. **
  62885. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  62886. ** use the value in register P3 as a key. If cursor P1 refers
  62887. ** to an SQL index, then P3 is the first in an array of P4 registers
  62888. ** that are used as an unpacked index key.
  62889. **
  62890. ** Reposition cursor P1 so that it points to the smallest entry that
  62891. ** is greater than the key value. If there are no records greater than
  62892. ** the key and P2 is not zero, then jump to P2.
  62893. **
  62894. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  62895. */
  62896. /* Opcode: SeekLt P1 P2 P3 P4 *
  62897. **
  62898. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  62899. ** use the value in register P3 as a key. If cursor P1 refers
  62900. ** to an SQL index, then P3 is the first in an array of P4 registers
  62901. ** that are used as an unpacked index key.
  62902. **
  62903. ** Reposition cursor P1 so that it points to the largest entry that
  62904. ** is less than the key value. If there are no records less than
  62905. ** the key and P2 is not zero, then jump to P2.
  62906. **
  62907. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  62908. */
  62909. /* Opcode: SeekLe P1 P2 P3 P4 *
  62910. **
  62911. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  62912. ** use the value in register P3 as a key. If cursor P1 refers
  62913. ** to an SQL index, then P3 is the first in an array of P4 registers
  62914. ** that are used as an unpacked index key.
  62915. **
  62916. ** Reposition cursor P1 so that it points to the largest entry that
  62917. ** is less than or equal to the key value. If there are no records
  62918. ** less than or equal to the key and P2 is not zero, then jump to P2.
  62919. **
  62920. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  62921. */
  62922. case OP_SeekLt: /* jump, in3 */
  62923. case OP_SeekLe: /* jump, in3 */
  62924. case OP_SeekGe: /* jump, in3 */
  62925. case OP_SeekGt: { /* jump, in3 */
  62926. #if 0 /* local variables moved into u.bc */
  62927. int res;
  62928. int oc;
  62929. VdbeCursor *pC;
  62930. UnpackedRecord r;
  62931. int nField;
  62932. i64 iKey; /* The rowid we are to seek to */
  62933. #endif /* local variables moved into u.bc */
  62934. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62935. assert( pOp->p2!=0 );
  62936. u.bc.pC = p->apCsr[pOp->p1];
  62937. assert( u.bc.pC!=0 );
  62938. assert( u.bc.pC->pseudoTableReg==0 );
  62939. assert( OP_SeekLe == OP_SeekLt+1 );
  62940. assert( OP_SeekGe == OP_SeekLt+2 );
  62941. assert( OP_SeekGt == OP_SeekLt+3 );
  62942. assert( u.bc.pC->isOrdered );
  62943. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  62944. u.bc.oc = pOp->opcode;
  62945. u.bc.pC->nullRow = 0;
  62946. if( u.bc.pC->isTable ){
  62947. /* The input value in P3 might be of any type: integer, real, string,
  62948. ** blob, or NULL. But it needs to be an integer before we can do
  62949. ** the seek, so covert it. */
  62950. pIn3 = &aMem[pOp->p3];
  62951. applyNumericAffinity(pIn3);
  62952. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  62953. u.bc.pC->rowidIsValid = 0;
  62954. /* If the P3 value could not be converted into an integer without
  62955. ** loss of information, then special processing is required... */
  62956. if( (pIn3->flags & MEM_Int)==0 ){
  62957. if( (pIn3->flags & MEM_Real)==0 ){
  62958. /* If the P3 value cannot be converted into any kind of a number,
  62959. ** then the seek is not possible, so jump to P2 */
  62960. pc = pOp->p2 - 1;
  62961. break;
  62962. }
  62963. /* If we reach this point, then the P3 value must be a floating
  62964. ** point number. */
  62965. assert( (pIn3->flags & MEM_Real)!=0 );
  62966. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  62967. /* The P3 value is too large in magnitude to be expressed as an
  62968. ** integer. */
  62969. u.bc.res = 1;
  62970. if( pIn3->r<0 ){
  62971. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  62972. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  62973. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  62974. }
  62975. }else{
  62976. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  62977. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  62978. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  62979. }
  62980. }
  62981. if( u.bc.res ){
  62982. pc = pOp->p2 - 1;
  62983. }
  62984. break;
  62985. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  62986. /* Use the ceiling() function to convert real->int */
  62987. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  62988. }else{
  62989. /* Use the floor() function to convert real->int */
  62990. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  62991. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  62992. }
  62993. }
  62994. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  62995. if( rc!=SQLITE_OK ){
  62996. goto abort_due_to_error;
  62997. }
  62998. if( u.bc.res==0 ){
  62999. u.bc.pC->rowidIsValid = 1;
  63000. u.bc.pC->lastRowid = u.bc.iKey;
  63001. }
  63002. }else{
  63003. u.bc.nField = pOp->p4.i;
  63004. assert( pOp->p4type==P4_INT32 );
  63005. assert( u.bc.nField>0 );
  63006. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  63007. u.bc.r.nField = (u16)u.bc.nField;
  63008. /* The next line of code computes as follows, only faster:
  63009. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  63010. ** u.bc.r.flags = UNPACKED_INCRKEY;
  63011. ** }else{
  63012. ** u.bc.r.flags = 0;
  63013. ** }
  63014. */
  63015. u.bc.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  63016. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  63017. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  63018. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  63019. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  63020. u.bc.r.aMem = &aMem[pOp->p3];
  63021. #ifdef SQLITE_DEBUG
  63022. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  63023. #endif
  63024. ExpandBlob(u.bc.r.aMem);
  63025. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  63026. if( rc!=SQLITE_OK ){
  63027. goto abort_due_to_error;
  63028. }
  63029. u.bc.pC->rowidIsValid = 0;
  63030. }
  63031. u.bc.pC->deferredMoveto = 0;
  63032. u.bc.pC->cacheStatus = CACHE_STALE;
  63033. #ifdef SQLITE_TEST
  63034. sqlite3_search_count++;
  63035. #endif
  63036. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  63037. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  63038. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  63039. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  63040. u.bc.pC->rowidIsValid = 0;
  63041. }else{
  63042. u.bc.res = 0;
  63043. }
  63044. }else{
  63045. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  63046. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  63047. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  63048. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  63049. u.bc.pC->rowidIsValid = 0;
  63050. }else{
  63051. /* u.bc.res might be negative because the table is empty. Check to
  63052. ** see if this is the case.
  63053. */
  63054. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  63055. }
  63056. }
  63057. assert( pOp->p2>0 );
  63058. if( u.bc.res ){
  63059. pc = pOp->p2 - 1;
  63060. }
  63061. }else{
  63062. /* This happens when attempting to open the sqlite3_master table
  63063. ** for read access returns SQLITE_EMPTY. In this case always
  63064. ** take the jump (since there are no records in the table).
  63065. */
  63066. pc = pOp->p2 - 1;
  63067. }
  63068. break;
  63069. }
  63070. /* Opcode: Seek P1 P2 * * *
  63071. **
  63072. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  63073. ** for P1 to move so that it points to the rowid given by P2.
  63074. **
  63075. ** This is actually a deferred seek. Nothing actually happens until
  63076. ** the cursor is used to read a record. That way, if no reads
  63077. ** occur, no unnecessary I/O happens.
  63078. */
  63079. case OP_Seek: { /* in2 */
  63080. #if 0 /* local variables moved into u.bd */
  63081. VdbeCursor *pC;
  63082. #endif /* local variables moved into u.bd */
  63083. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63084. u.bd.pC = p->apCsr[pOp->p1];
  63085. assert( u.bd.pC!=0 );
  63086. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  63087. assert( u.bd.pC->isTable );
  63088. u.bd.pC->nullRow = 0;
  63089. pIn2 = &aMem[pOp->p2];
  63090. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  63091. u.bd.pC->rowidIsValid = 0;
  63092. u.bd.pC->deferredMoveto = 1;
  63093. }
  63094. break;
  63095. }
  63096. /* Opcode: Found P1 P2 P3 P4 *
  63097. **
  63098. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  63099. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  63100. ** record.
  63101. **
  63102. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  63103. ** is a prefix of any entry in P1 then a jump is made to P2 and
  63104. ** P1 is left pointing at the matching entry.
  63105. */
  63106. /* Opcode: NotFound P1 P2 P3 P4 *
  63107. **
  63108. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  63109. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  63110. ** record.
  63111. **
  63112. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  63113. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  63114. ** does contain an entry whose prefix matches the P3/P4 record then control
  63115. ** falls through to the next instruction and P1 is left pointing at the
  63116. ** matching entry.
  63117. **
  63118. ** See also: Found, NotExists, IsUnique
  63119. */
  63120. case OP_NotFound: /* jump, in3 */
  63121. case OP_Found: { /* jump, in3 */
  63122. #if 0 /* local variables moved into u.be */
  63123. int alreadyExists;
  63124. VdbeCursor *pC;
  63125. int res;
  63126. char *pFree;
  63127. UnpackedRecord *pIdxKey;
  63128. UnpackedRecord r;
  63129. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  63130. #endif /* local variables moved into u.be */
  63131. #ifdef SQLITE_TEST
  63132. sqlite3_found_count++;
  63133. #endif
  63134. u.be.alreadyExists = 0;
  63135. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63136. assert( pOp->p4type==P4_INT32 );
  63137. u.be.pC = p->apCsr[pOp->p1];
  63138. assert( u.be.pC!=0 );
  63139. pIn3 = &aMem[pOp->p3];
  63140. if( ALWAYS(u.be.pC->pCursor!=0) ){
  63141. assert( u.be.pC->isTable==0 );
  63142. if( pOp->p4.i>0 ){
  63143. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  63144. u.be.r.nField = (u16)pOp->p4.i;
  63145. u.be.r.aMem = pIn3;
  63146. #ifdef SQLITE_DEBUG
  63147. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  63148. #endif
  63149. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  63150. u.be.pIdxKey = &u.be.r;
  63151. }else{
  63152. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  63153. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  63154. );
  63155. if( u.be.pIdxKey==0 ) goto no_mem;
  63156. assert( pIn3->flags & MEM_Blob );
  63157. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  63158. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  63159. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  63160. }
  63161. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  63162. if( pOp->p4.i==0 ){
  63163. sqlite3DbFree(db, u.be.pFree);
  63164. }
  63165. if( rc!=SQLITE_OK ){
  63166. break;
  63167. }
  63168. u.be.alreadyExists = (u.be.res==0);
  63169. u.be.pC->deferredMoveto = 0;
  63170. u.be.pC->cacheStatus = CACHE_STALE;
  63171. }
  63172. if( pOp->opcode==OP_Found ){
  63173. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  63174. }else{
  63175. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  63176. }
  63177. break;
  63178. }
  63179. /* Opcode: IsUnique P1 P2 P3 P4 *
  63180. **
  63181. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  63182. ** no data and where the key are records generated by OP_MakeRecord with
  63183. ** the list field being the integer ROWID of the entry that the index
  63184. ** entry refers to.
  63185. **
  63186. ** The P3 register contains an integer record number. Call this record
  63187. ** number R. Register P4 is the first in a set of N contiguous registers
  63188. ** that make up an unpacked index key that can be used with cursor P1.
  63189. ** The value of N can be inferred from the cursor. N includes the rowid
  63190. ** value appended to the end of the index record. This rowid value may
  63191. ** or may not be the same as R.
  63192. **
  63193. ** If any of the N registers beginning with register P4 contains a NULL
  63194. ** value, jump immediately to P2.
  63195. **
  63196. ** Otherwise, this instruction checks if cursor P1 contains an entry
  63197. ** where the first (N-1) fields match but the rowid value at the end
  63198. ** of the index entry is not R. If there is no such entry, control jumps
  63199. ** to instruction P2. Otherwise, the rowid of the conflicting index
  63200. ** entry is copied to register P3 and control falls through to the next
  63201. ** instruction.
  63202. **
  63203. ** See also: NotFound, NotExists, Found
  63204. */
  63205. case OP_IsUnique: { /* jump, in3 */
  63206. #if 0 /* local variables moved into u.bf */
  63207. u16 ii;
  63208. VdbeCursor *pCx;
  63209. BtCursor *pCrsr;
  63210. u16 nField;
  63211. Mem *aMx;
  63212. UnpackedRecord r; /* B-Tree index search key */
  63213. i64 R; /* Rowid stored in register P3 */
  63214. #endif /* local variables moved into u.bf */
  63215. pIn3 = &aMem[pOp->p3];
  63216. u.bf.aMx = &aMem[pOp->p4.i];
  63217. /* Assert that the values of parameters P1 and P4 are in range. */
  63218. assert( pOp->p4type==P4_INT32 );
  63219. assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  63220. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63221. /* Find the index cursor. */
  63222. u.bf.pCx = p->apCsr[pOp->p1];
  63223. assert( u.bf.pCx->deferredMoveto==0 );
  63224. u.bf.pCx->seekResult = 0;
  63225. u.bf.pCx->cacheStatus = CACHE_STALE;
  63226. u.bf.pCrsr = u.bf.pCx->pCursor;
  63227. /* If any of the values are NULL, take the jump. */
  63228. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  63229. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  63230. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  63231. pc = pOp->p2 - 1;
  63232. u.bf.pCrsr = 0;
  63233. break;
  63234. }
  63235. }
  63236. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  63237. if( u.bf.pCrsr!=0 ){
  63238. /* Populate the index search key. */
  63239. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  63240. u.bf.r.nField = u.bf.nField + 1;
  63241. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  63242. u.bf.r.aMem = u.bf.aMx;
  63243. #ifdef SQLITE_DEBUG
  63244. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  63245. #endif
  63246. /* Extract the value of u.bf.R from register P3. */
  63247. sqlite3VdbeMemIntegerify(pIn3);
  63248. u.bf.R = pIn3->u.i;
  63249. /* Search the B-Tree index. If no conflicting record is found, jump
  63250. ** to P2. Otherwise, copy the rowid of the conflicting record to
  63251. ** register P3 and fall through to the next instruction. */
  63252. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  63253. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  63254. pc = pOp->p2 - 1;
  63255. }else{
  63256. pIn3->u.i = u.bf.r.rowid;
  63257. }
  63258. }
  63259. break;
  63260. }
  63261. /* Opcode: NotExists P1 P2 P3 * *
  63262. **
  63263. ** Use the content of register P3 as an integer key. If a record
  63264. ** with that key does not exist in table of P1, then jump to P2.
  63265. ** If the record does exist, then fall through. The cursor is left
  63266. ** pointing to the record if it exists.
  63267. **
  63268. ** The difference between this operation and NotFound is that this
  63269. ** operation assumes the key is an integer and that P1 is a table whereas
  63270. ** NotFound assumes key is a blob constructed from MakeRecord and
  63271. ** P1 is an index.
  63272. **
  63273. ** See also: Found, NotFound, IsUnique
  63274. */
  63275. case OP_NotExists: { /* jump, in3 */
  63276. #if 0 /* local variables moved into u.bg */
  63277. VdbeCursor *pC;
  63278. BtCursor *pCrsr;
  63279. int res;
  63280. u64 iKey;
  63281. #endif /* local variables moved into u.bg */
  63282. pIn3 = &aMem[pOp->p3];
  63283. assert( pIn3->flags & MEM_Int );
  63284. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63285. u.bg.pC = p->apCsr[pOp->p1];
  63286. assert( u.bg.pC!=0 );
  63287. assert( u.bg.pC->isTable );
  63288. assert( u.bg.pC->pseudoTableReg==0 );
  63289. u.bg.pCrsr = u.bg.pC->pCursor;
  63290. if( ALWAYS(u.bg.pCrsr!=0) ){
  63291. u.bg.res = 0;
  63292. u.bg.iKey = pIn3->u.i;
  63293. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  63294. u.bg.pC->lastRowid = pIn3->u.i;
  63295. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  63296. u.bg.pC->nullRow = 0;
  63297. u.bg.pC->cacheStatus = CACHE_STALE;
  63298. u.bg.pC->deferredMoveto = 0;
  63299. if( u.bg.res!=0 ){
  63300. pc = pOp->p2 - 1;
  63301. assert( u.bg.pC->rowidIsValid==0 );
  63302. }
  63303. u.bg.pC->seekResult = u.bg.res;
  63304. }else{
  63305. /* This happens when an attempt to open a read cursor on the
  63306. ** sqlite_master table returns SQLITE_EMPTY.
  63307. */
  63308. pc = pOp->p2 - 1;
  63309. assert( u.bg.pC->rowidIsValid==0 );
  63310. u.bg.pC->seekResult = 0;
  63311. }
  63312. break;
  63313. }
  63314. /* Opcode: Sequence P1 P2 * * *
  63315. **
  63316. ** Find the next available sequence number for cursor P1.
  63317. ** Write the sequence number into register P2.
  63318. ** The sequence number on the cursor is incremented after this
  63319. ** instruction.
  63320. */
  63321. case OP_Sequence: { /* out2-prerelease */
  63322. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63323. assert( p->apCsr[pOp->p1]!=0 );
  63324. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  63325. break;
  63326. }
  63327. /* Opcode: NewRowid P1 P2 P3 * *
  63328. **
  63329. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  63330. ** The record number is not previously used as a key in the database
  63331. ** table that cursor P1 points to. The new record number is written
  63332. ** written to register P2.
  63333. **
  63334. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  63335. ** the largest previously generated record number. No new record numbers are
  63336. ** allowed to be less than this value. When this value reaches its maximum,
  63337. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  63338. ** generated record number. This P3 mechanism is used to help implement the
  63339. ** AUTOINCREMENT feature.
  63340. */
  63341. case OP_NewRowid: { /* out2-prerelease */
  63342. #if 0 /* local variables moved into u.bh */
  63343. i64 v; /* The new rowid */
  63344. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  63345. int res; /* Result of an sqlite3BtreeLast() */
  63346. int cnt; /* Counter to limit the number of searches */
  63347. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  63348. VdbeFrame *pFrame; /* Root frame of VDBE */
  63349. #endif /* local variables moved into u.bh */
  63350. u.bh.v = 0;
  63351. u.bh.res = 0;
  63352. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63353. u.bh.pC = p->apCsr[pOp->p1];
  63354. assert( u.bh.pC!=0 );
  63355. if( NEVER(u.bh.pC->pCursor==0) ){
  63356. /* The zero initialization above is all that is needed */
  63357. }else{
  63358. /* The next rowid or record number (different terms for the same
  63359. ** thing) is obtained in a two-step algorithm.
  63360. **
  63361. ** First we attempt to find the largest existing rowid and add one
  63362. ** to that. But if the largest existing rowid is already the maximum
  63363. ** positive integer, we have to fall through to the second
  63364. ** probabilistic algorithm
  63365. **
  63366. ** The second algorithm is to select a rowid at random and see if
  63367. ** it already exists in the table. If it does not exist, we have
  63368. ** succeeded. If the random rowid does exist, we select a new one
  63369. ** and try again, up to 100 times.
  63370. */
  63371. assert( u.bh.pC->isTable );
  63372. #ifdef SQLITE_32BIT_ROWID
  63373. # define MAX_ROWID 0x7fffffff
  63374. #else
  63375. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  63376. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  63377. ** to provide the constant while making all compilers happy.
  63378. */
  63379. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  63380. #endif
  63381. if( !u.bh.pC->useRandomRowid ){
  63382. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  63383. if( u.bh.v==0 ){
  63384. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  63385. if( rc!=SQLITE_OK ){
  63386. goto abort_due_to_error;
  63387. }
  63388. if( u.bh.res ){
  63389. u.bh.v = 1; /* IMP: R-61914-48074 */
  63390. }else{
  63391. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  63392. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  63393. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  63394. if( u.bh.v>=MAX_ROWID ){
  63395. u.bh.pC->useRandomRowid = 1;
  63396. }else{
  63397. u.bh.v++; /* IMP: R-29538-34987 */
  63398. }
  63399. }
  63400. }
  63401. #ifndef SQLITE_OMIT_AUTOINCREMENT
  63402. if( pOp->p3 ){
  63403. /* Assert that P3 is a valid memory cell. */
  63404. assert( pOp->p3>0 );
  63405. if( p->pFrame ){
  63406. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  63407. /* Assert that P3 is a valid memory cell. */
  63408. assert( pOp->p3<=u.bh.pFrame->nMem );
  63409. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  63410. }else{
  63411. /* Assert that P3 is a valid memory cell. */
  63412. assert( pOp->p3<=p->nMem );
  63413. u.bh.pMem = &aMem[pOp->p3];
  63414. memAboutToChange(p, u.bh.pMem);
  63415. }
  63416. assert( memIsValid(u.bh.pMem) );
  63417. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  63418. sqlite3VdbeMemIntegerify(u.bh.pMem);
  63419. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  63420. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  63421. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  63422. goto abort_due_to_error;
  63423. }
  63424. if( u.bh.v<u.bh.pMem->u.i+1 ){
  63425. u.bh.v = u.bh.pMem->u.i + 1;
  63426. }
  63427. u.bh.pMem->u.i = u.bh.v;
  63428. }
  63429. #endif
  63430. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  63431. }
  63432. if( u.bh.pC->useRandomRowid ){
  63433. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  63434. ** largest possible integer (9223372036854775807) then the database
  63435. ** engine starts picking positive candidate ROWIDs at random until
  63436. ** it finds one that is not previously used. */
  63437. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  63438. ** an AUTOINCREMENT table. */
  63439. /* on the first attempt, simply do one more than previous */
  63440. u.bh.v = lastRowid;
  63441. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  63442. u.bh.v++; /* ensure non-zero */
  63443. u.bh.cnt = 0;
  63444. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  63445. 0, &u.bh.res))==SQLITE_OK)
  63446. && (u.bh.res==0)
  63447. && (++u.bh.cnt<100)){
  63448. /* collision - try another random rowid */
  63449. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  63450. if( u.bh.cnt<5 ){
  63451. /* try "small" random rowids for the initial attempts */
  63452. u.bh.v &= 0xffffff;
  63453. }else{
  63454. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  63455. }
  63456. u.bh.v++; /* ensure non-zero */
  63457. }
  63458. if( rc==SQLITE_OK && u.bh.res==0 ){
  63459. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  63460. goto abort_due_to_error;
  63461. }
  63462. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  63463. }
  63464. u.bh.pC->rowidIsValid = 0;
  63465. u.bh.pC->deferredMoveto = 0;
  63466. u.bh.pC->cacheStatus = CACHE_STALE;
  63467. }
  63468. pOut->u.i = u.bh.v;
  63469. break;
  63470. }
  63471. /* Opcode: Insert P1 P2 P3 P4 P5
  63472. **
  63473. ** Write an entry into the table of cursor P1. A new entry is
  63474. ** created if it doesn't already exist or the data for an existing
  63475. ** entry is overwritten. The data is the value MEM_Blob stored in register
  63476. ** number P2. The key is stored in register P3. The key must
  63477. ** be a MEM_Int.
  63478. **
  63479. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  63480. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  63481. ** then rowid is stored for subsequent return by the
  63482. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  63483. **
  63484. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  63485. ** the last seek operation (OP_NotExists) was a success, then this
  63486. ** operation will not attempt to find the appropriate row before doing
  63487. ** the insert but will instead overwrite the row that the cursor is
  63488. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  63489. ** has already positioned the cursor correctly. This is an optimization
  63490. ** that boosts performance by avoiding redundant seeks.
  63491. **
  63492. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  63493. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  63494. ** is part of an INSERT operation. The difference is only important to
  63495. ** the update hook.
  63496. **
  63497. ** Parameter P4 may point to a string containing the table-name, or
  63498. ** may be NULL. If it is not NULL, then the update-hook
  63499. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  63500. **
  63501. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  63502. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  63503. ** and register P2 becomes ephemeral. If the cursor is changed, the
  63504. ** value of register P2 will then change. Make sure this does not
  63505. ** cause any problems.)
  63506. **
  63507. ** This instruction only works on tables. The equivalent instruction
  63508. ** for indices is OP_IdxInsert.
  63509. */
  63510. /* Opcode: InsertInt P1 P2 P3 P4 P5
  63511. **
  63512. ** This works exactly like OP_Insert except that the key is the
  63513. ** integer value P3, not the value of the integer stored in register P3.
  63514. */
  63515. case OP_Insert:
  63516. case OP_InsertInt: {
  63517. #if 0 /* local variables moved into u.bi */
  63518. Mem *pData; /* MEM cell holding data for the record to be inserted */
  63519. Mem *pKey; /* MEM cell holding key for the record */
  63520. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  63521. VdbeCursor *pC; /* Cursor to table into which insert is written */
  63522. int nZero; /* Number of zero-bytes to append */
  63523. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  63524. const char *zDb; /* database name - used by the update hook */
  63525. const char *zTbl; /* Table name - used by the opdate hook */
  63526. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  63527. #endif /* local variables moved into u.bi */
  63528. u.bi.pData = &aMem[pOp->p2];
  63529. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63530. assert( memIsValid(u.bi.pData) );
  63531. u.bi.pC = p->apCsr[pOp->p1];
  63532. assert( u.bi.pC!=0 );
  63533. assert( u.bi.pC->pCursor!=0 );
  63534. assert( u.bi.pC->pseudoTableReg==0 );
  63535. assert( u.bi.pC->isTable );
  63536. REGISTER_TRACE(pOp->p2, u.bi.pData);
  63537. if( pOp->opcode==OP_Insert ){
  63538. u.bi.pKey = &aMem[pOp->p3];
  63539. assert( u.bi.pKey->flags & MEM_Int );
  63540. assert( memIsValid(u.bi.pKey) );
  63541. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  63542. u.bi.iKey = u.bi.pKey->u.i;
  63543. }else{
  63544. assert( pOp->opcode==OP_InsertInt );
  63545. u.bi.iKey = pOp->p3;
  63546. }
  63547. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  63548. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  63549. if( u.bi.pData->flags & MEM_Null ){
  63550. u.bi.pData->z = 0;
  63551. u.bi.pData->n = 0;
  63552. }else{
  63553. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  63554. }
  63555. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  63556. if( u.bi.pData->flags & MEM_Zero ){
  63557. u.bi.nZero = u.bi.pData->u.nZero;
  63558. }else{
  63559. u.bi.nZero = 0;
  63560. }
  63561. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  63562. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  63563. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  63564. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  63565. );
  63566. u.bi.pC->rowidIsValid = 0;
  63567. u.bi.pC->deferredMoveto = 0;
  63568. u.bi.pC->cacheStatus = CACHE_STALE;
  63569. /* Invoke the update-hook if required. */
  63570. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  63571. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  63572. u.bi.zTbl = pOp->p4.z;
  63573. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  63574. assert( u.bi.pC->isTable );
  63575. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  63576. assert( u.bi.pC->iDb>=0 );
  63577. }
  63578. break;
  63579. }
  63580. /* Opcode: Delete P1 P2 * P4 *
  63581. **
  63582. ** Delete the record at which the P1 cursor is currently pointing.
  63583. **
  63584. ** The cursor will be left pointing at either the next or the previous
  63585. ** record in the table. If it is left pointing at the next record, then
  63586. ** the next Next instruction will be a no-op. Hence it is OK to delete
  63587. ** a record from within an Next loop.
  63588. **
  63589. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  63590. ** incremented (otherwise not).
  63591. **
  63592. ** P1 must not be pseudo-table. It has to be a real table with
  63593. ** multiple rows.
  63594. **
  63595. ** If P4 is not NULL, then it is the name of the table that P1 is
  63596. ** pointing to. The update hook will be invoked, if it exists.
  63597. ** If P4 is not NULL then the P1 cursor must have been positioned
  63598. ** using OP_NotFound prior to invoking this opcode.
  63599. */
  63600. case OP_Delete: {
  63601. #if 0 /* local variables moved into u.bj */
  63602. i64 iKey;
  63603. VdbeCursor *pC;
  63604. #endif /* local variables moved into u.bj */
  63605. u.bj.iKey = 0;
  63606. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63607. u.bj.pC = p->apCsr[pOp->p1];
  63608. assert( u.bj.pC!=0 );
  63609. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  63610. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  63611. ** row being deleted.
  63612. */
  63613. if( db->xUpdateCallback && pOp->p4.z ){
  63614. assert( u.bj.pC->isTable );
  63615. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  63616. u.bj.iKey = u.bj.pC->lastRowid;
  63617. }
  63618. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  63619. ** OP_Column on the same table without any intervening operations that
  63620. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  63621. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  63622. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  63623. ** to guard against future changes to the code generator.
  63624. **/
  63625. assert( u.bj.pC->deferredMoveto==0 );
  63626. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  63627. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  63628. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  63629. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  63630. u.bj.pC->cacheStatus = CACHE_STALE;
  63631. /* Invoke the update-hook if required. */
  63632. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  63633. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  63634. const char *zTbl = pOp->p4.z;
  63635. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  63636. assert( u.bj.pC->iDb>=0 );
  63637. }
  63638. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  63639. break;
  63640. }
  63641. /* Opcode: ResetCount * * * * *
  63642. **
  63643. ** The value of the change counter is copied to the database handle
  63644. ** change counter (returned by subsequent calls to sqlite3_changes()).
  63645. ** Then the VMs internal change counter resets to 0.
  63646. ** This is used by trigger programs.
  63647. */
  63648. case OP_ResetCount: {
  63649. sqlite3VdbeSetChanges(db, p->nChange);
  63650. p->nChange = 0;
  63651. break;
  63652. }
  63653. /* Opcode: SorterCompare P1 P2 P3
  63654. **
  63655. ** P1 is a sorter cursor. This instruction compares the record blob in
  63656. ** register P3 with the entry that the sorter cursor currently points to.
  63657. ** If, excluding the rowid fields at the end, the two records are a match,
  63658. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  63659. */
  63660. case OP_SorterCompare: {
  63661. #if 0 /* local variables moved into u.bk */
  63662. VdbeCursor *pC;
  63663. int res;
  63664. #endif /* local variables moved into u.bk */
  63665. u.bk.pC = p->apCsr[pOp->p1];
  63666. assert( isSorter(u.bk.pC) );
  63667. pIn3 = &aMem[pOp->p3];
  63668. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  63669. if( u.bk.res ){
  63670. pc = pOp->p2-1;
  63671. }
  63672. break;
  63673. };
  63674. /* Opcode: SorterData P1 P2 * * *
  63675. **
  63676. ** Write into register P2 the current sorter data for sorter cursor P1.
  63677. */
  63678. case OP_SorterData: {
  63679. #if 0 /* local variables moved into u.bl */
  63680. VdbeCursor *pC;
  63681. #endif /* local variables moved into u.bl */
  63682. #ifndef SQLITE_OMIT_MERGE_SORT
  63683. pOut = &aMem[pOp->p2];
  63684. u.bl.pC = p->apCsr[pOp->p1];
  63685. assert( u.bl.pC->isSorter );
  63686. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  63687. #else
  63688. pOp->opcode = OP_RowKey;
  63689. pc--;
  63690. #endif
  63691. break;
  63692. }
  63693. /* Opcode: RowData P1 P2 * * *
  63694. **
  63695. ** Write into register P2 the complete row data for cursor P1.
  63696. ** There is no interpretation of the data.
  63697. ** It is just copied onto the P2 register exactly as
  63698. ** it is found in the database file.
  63699. **
  63700. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  63701. ** of a real table, not a pseudo-table.
  63702. */
  63703. /* Opcode: RowKey P1 P2 * * *
  63704. **
  63705. ** Write into register P2 the complete row key for cursor P1.
  63706. ** There is no interpretation of the data.
  63707. ** The key is copied onto the P3 register exactly as
  63708. ** it is found in the database file.
  63709. **
  63710. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  63711. ** of a real table, not a pseudo-table.
  63712. */
  63713. case OP_RowKey:
  63714. case OP_RowData: {
  63715. #if 0 /* local variables moved into u.bm */
  63716. VdbeCursor *pC;
  63717. BtCursor *pCrsr;
  63718. u32 n;
  63719. i64 n64;
  63720. #endif /* local variables moved into u.bm */
  63721. pOut = &aMem[pOp->p2];
  63722. memAboutToChange(p, pOut);
  63723. /* Note that RowKey and RowData are really exactly the same instruction */
  63724. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63725. u.bm.pC = p->apCsr[pOp->p1];
  63726. assert( u.bm.pC->isSorter==0 );
  63727. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  63728. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  63729. assert( u.bm.pC!=0 );
  63730. assert( u.bm.pC->nullRow==0 );
  63731. assert( u.bm.pC->pseudoTableReg==0 );
  63732. assert( u.bm.pC->pCursor!=0 );
  63733. u.bm.pCrsr = u.bm.pC->pCursor;
  63734. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  63735. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  63736. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  63737. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  63738. ** a no-op and can never fail. But we leave it in place as a safety.
  63739. */
  63740. assert( u.bm.pC->deferredMoveto==0 );
  63741. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  63742. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  63743. if( u.bm.pC->isIndex ){
  63744. assert( !u.bm.pC->isTable );
  63745. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  63746. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  63747. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63748. goto too_big;
  63749. }
  63750. u.bm.n = (u32)u.bm.n64;
  63751. }else{
  63752. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  63753. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  63754. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  63755. goto too_big;
  63756. }
  63757. }
  63758. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  63759. goto no_mem;
  63760. }
  63761. pOut->n = u.bm.n;
  63762. MemSetTypeFlag(pOut, MEM_Blob);
  63763. if( u.bm.pC->isIndex ){
  63764. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  63765. }else{
  63766. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  63767. }
  63768. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  63769. UPDATE_MAX_BLOBSIZE(pOut);
  63770. break;
  63771. }
  63772. /* Opcode: Rowid P1 P2 * * *
  63773. **
  63774. ** Store in register P2 an integer which is the key of the table entry that
  63775. ** P1 is currently point to.
  63776. **
  63777. ** P1 can be either an ordinary table or a virtual table. There used to
  63778. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  63779. ** one opcode now works for both table types.
  63780. */
  63781. case OP_Rowid: { /* out2-prerelease */
  63782. #if 0 /* local variables moved into u.bn */
  63783. VdbeCursor *pC;
  63784. i64 v;
  63785. sqlite3_vtab *pVtab;
  63786. const sqlite3_module *pModule;
  63787. #endif /* local variables moved into u.bn */
  63788. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63789. u.bn.pC = p->apCsr[pOp->p1];
  63790. assert( u.bn.pC!=0 );
  63791. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  63792. if( u.bn.pC->nullRow ){
  63793. pOut->flags = MEM_Null;
  63794. break;
  63795. }else if( u.bn.pC->deferredMoveto ){
  63796. u.bn.v = u.bn.pC->movetoTarget;
  63797. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63798. }else if( u.bn.pC->pVtabCursor ){
  63799. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  63800. u.bn.pModule = u.bn.pVtab->pModule;
  63801. assert( u.bn.pModule->xRowid );
  63802. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  63803. importVtabErrMsg(p, u.bn.pVtab);
  63804. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63805. }else{
  63806. assert( u.bn.pC->pCursor!=0 );
  63807. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  63808. if( rc ) goto abort_due_to_error;
  63809. if( u.bn.pC->rowidIsValid ){
  63810. u.bn.v = u.bn.pC->lastRowid;
  63811. }else{
  63812. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  63813. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  63814. }
  63815. }
  63816. pOut->u.i = u.bn.v;
  63817. break;
  63818. }
  63819. /* Opcode: NullRow P1 * * * *
  63820. **
  63821. ** Move the cursor P1 to a null row. Any OP_Column operations
  63822. ** that occur while the cursor is on the null row will always
  63823. ** write a NULL.
  63824. */
  63825. case OP_NullRow: {
  63826. #if 0 /* local variables moved into u.bo */
  63827. VdbeCursor *pC;
  63828. #endif /* local variables moved into u.bo */
  63829. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63830. u.bo.pC = p->apCsr[pOp->p1];
  63831. assert( u.bo.pC!=0 );
  63832. u.bo.pC->nullRow = 1;
  63833. u.bo.pC->rowidIsValid = 0;
  63834. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  63835. if( u.bo.pC->pCursor ){
  63836. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  63837. }
  63838. break;
  63839. }
  63840. /* Opcode: Last P1 P2 * * *
  63841. **
  63842. ** The next use of the Rowid or Column or Next instruction for P1
  63843. ** will refer to the last entry in the database table or index.
  63844. ** If the table or index is empty and P2>0, then jump immediately to P2.
  63845. ** If P2 is 0 or if the table or index is not empty, fall through
  63846. ** to the following instruction.
  63847. */
  63848. case OP_Last: { /* jump */
  63849. #if 0 /* local variables moved into u.bp */
  63850. VdbeCursor *pC;
  63851. BtCursor *pCrsr;
  63852. int res;
  63853. #endif /* local variables moved into u.bp */
  63854. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63855. u.bp.pC = p->apCsr[pOp->p1];
  63856. assert( u.bp.pC!=0 );
  63857. u.bp.pCrsr = u.bp.pC->pCursor;
  63858. u.bp.res = 0;
  63859. if( ALWAYS(u.bp.pCrsr!=0) ){
  63860. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  63861. }
  63862. u.bp.pC->nullRow = (u8)u.bp.res;
  63863. u.bp.pC->deferredMoveto = 0;
  63864. u.bp.pC->rowidIsValid = 0;
  63865. u.bp.pC->cacheStatus = CACHE_STALE;
  63866. if( pOp->p2>0 && u.bp.res ){
  63867. pc = pOp->p2 - 1;
  63868. }
  63869. break;
  63870. }
  63871. /* Opcode: Sort P1 P2 * * *
  63872. **
  63873. ** This opcode does exactly the same thing as OP_Rewind except that
  63874. ** it increments an undocumented global variable used for testing.
  63875. **
  63876. ** Sorting is accomplished by writing records into a sorting index,
  63877. ** then rewinding that index and playing it back from beginning to
  63878. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  63879. ** rewinding so that the global variable will be incremented and
  63880. ** regression tests can determine whether or not the optimizer is
  63881. ** correctly optimizing out sorts.
  63882. */
  63883. case OP_SorterSort: /* jump */
  63884. #ifdef SQLITE_OMIT_MERGE_SORT
  63885. pOp->opcode = OP_Sort;
  63886. #endif
  63887. case OP_Sort: { /* jump */
  63888. #ifdef SQLITE_TEST
  63889. sqlite3_sort_count++;
  63890. sqlite3_search_count--;
  63891. #endif
  63892. p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  63893. /* Fall through into OP_Rewind */
  63894. }
  63895. /* Opcode: Rewind P1 P2 * * *
  63896. **
  63897. ** The next use of the Rowid or Column or Next instruction for P1
  63898. ** will refer to the first entry in the database table or index.
  63899. ** If the table or index is empty and P2>0, then jump immediately to P2.
  63900. ** If P2 is 0 or if the table or index is not empty, fall through
  63901. ** to the following instruction.
  63902. */
  63903. case OP_Rewind: { /* jump */
  63904. #if 0 /* local variables moved into u.bq */
  63905. VdbeCursor *pC;
  63906. BtCursor *pCrsr;
  63907. int res;
  63908. #endif /* local variables moved into u.bq */
  63909. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63910. u.bq.pC = p->apCsr[pOp->p1];
  63911. assert( u.bq.pC!=0 );
  63912. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  63913. u.bq.res = 1;
  63914. if( isSorter(u.bq.pC) ){
  63915. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  63916. }else{
  63917. u.bq.pCrsr = u.bq.pC->pCursor;
  63918. assert( u.bq.pCrsr );
  63919. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  63920. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  63921. u.bq.pC->deferredMoveto = 0;
  63922. u.bq.pC->cacheStatus = CACHE_STALE;
  63923. u.bq.pC->rowidIsValid = 0;
  63924. }
  63925. u.bq.pC->nullRow = (u8)u.bq.res;
  63926. assert( pOp->p2>0 && pOp->p2<p->nOp );
  63927. if( u.bq.res ){
  63928. pc = pOp->p2 - 1;
  63929. }
  63930. break;
  63931. }
  63932. /* Opcode: Next P1 P2 * P4 P5
  63933. **
  63934. ** Advance cursor P1 so that it points to the next key/data pair in its
  63935. ** table or index. If there are no more key/value pairs then fall through
  63936. ** to the following instruction. But if the cursor advance was successful,
  63937. ** jump immediately to P2.
  63938. **
  63939. ** The P1 cursor must be for a real table, not a pseudo-table.
  63940. **
  63941. ** P4 is always of type P4_ADVANCE. The function pointer points to
  63942. ** sqlite3BtreeNext().
  63943. **
  63944. ** If P5 is positive and the jump is taken, then event counter
  63945. ** number P5-1 in the prepared statement is incremented.
  63946. **
  63947. ** See also: Prev
  63948. */
  63949. /* Opcode: Prev P1 P2 * * P5
  63950. **
  63951. ** Back up cursor P1 so that it points to the previous key/data pair in its
  63952. ** table or index. If there is no previous key/value pairs then fall through
  63953. ** to the following instruction. But if the cursor backup was successful,
  63954. ** jump immediately to P2.
  63955. **
  63956. ** The P1 cursor must be for a real table, not a pseudo-table.
  63957. **
  63958. ** P4 is always of type P4_ADVANCE. The function pointer points to
  63959. ** sqlite3BtreePrevious().
  63960. **
  63961. ** If P5 is positive and the jump is taken, then event counter
  63962. ** number P5-1 in the prepared statement is incremented.
  63963. */
  63964. case OP_SorterNext: /* jump */
  63965. #ifdef SQLITE_OMIT_MERGE_SORT
  63966. pOp->opcode = OP_Next;
  63967. #endif
  63968. case OP_Prev: /* jump */
  63969. case OP_Next: { /* jump */
  63970. #if 0 /* local variables moved into u.br */
  63971. VdbeCursor *pC;
  63972. int res;
  63973. #endif /* local variables moved into u.br */
  63974. CHECK_FOR_INTERRUPT;
  63975. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  63976. assert( pOp->p5<=ArraySize(p->aCounter) );
  63977. u.br.pC = p->apCsr[pOp->p1];
  63978. if( u.br.pC==0 ){
  63979. break; /* See ticket #2273 */
  63980. }
  63981. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  63982. if( isSorter(u.br.pC) ){
  63983. assert( pOp->opcode==OP_SorterNext );
  63984. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  63985. }else{
  63986. u.br.res = 1;
  63987. assert( u.br.pC->deferredMoveto==0 );
  63988. assert( u.br.pC->pCursor );
  63989. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  63990. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  63991. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  63992. }
  63993. u.br.pC->nullRow = (u8)u.br.res;
  63994. u.br.pC->cacheStatus = CACHE_STALE;
  63995. if( u.br.res==0 ){
  63996. pc = pOp->p2 - 1;
  63997. if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
  63998. #ifdef SQLITE_TEST
  63999. sqlite3_search_count++;
  64000. #endif
  64001. }
  64002. u.br.pC->rowidIsValid = 0;
  64003. break;
  64004. }
  64005. /* Opcode: IdxInsert P1 P2 P3 * P5
  64006. **
  64007. ** Register P2 holds an SQL index key made using the
  64008. ** MakeRecord instructions. This opcode writes that key
  64009. ** into the index P1. Data for the entry is nil.
  64010. **
  64011. ** P3 is a flag that provides a hint to the b-tree layer that this
  64012. ** insert is likely to be an append.
  64013. **
  64014. ** This instruction only works for indices. The equivalent instruction
  64015. ** for tables is OP_Insert.
  64016. */
  64017. case OP_SorterInsert: /* in2 */
  64018. #ifdef SQLITE_OMIT_MERGE_SORT
  64019. pOp->opcode = OP_IdxInsert;
  64020. #endif
  64021. case OP_IdxInsert: { /* in2 */
  64022. #if 0 /* local variables moved into u.bs */
  64023. VdbeCursor *pC;
  64024. BtCursor *pCrsr;
  64025. int nKey;
  64026. const char *zKey;
  64027. #endif /* local variables moved into u.bs */
  64028. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64029. u.bs.pC = p->apCsr[pOp->p1];
  64030. assert( u.bs.pC!=0 );
  64031. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  64032. pIn2 = &aMem[pOp->p2];
  64033. assert( pIn2->flags & MEM_Blob );
  64034. u.bs.pCrsr = u.bs.pC->pCursor;
  64035. if( ALWAYS(u.bs.pCrsr!=0) ){
  64036. assert( u.bs.pC->isTable==0 );
  64037. rc = ExpandBlob(pIn2);
  64038. if( rc==SQLITE_OK ){
  64039. if( isSorter(u.bs.pC) ){
  64040. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  64041. }else{
  64042. u.bs.nKey = pIn2->n;
  64043. u.bs.zKey = pIn2->z;
  64044. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  64045. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  64046. );
  64047. assert( u.bs.pC->deferredMoveto==0 );
  64048. u.bs.pC->cacheStatus = CACHE_STALE;
  64049. }
  64050. }
  64051. }
  64052. break;
  64053. }
  64054. /* Opcode: IdxDelete P1 P2 P3 * *
  64055. **
  64056. ** The content of P3 registers starting at register P2 form
  64057. ** an unpacked index key. This opcode removes that entry from the
  64058. ** index opened by cursor P1.
  64059. */
  64060. case OP_IdxDelete: {
  64061. #if 0 /* local variables moved into u.bt */
  64062. VdbeCursor *pC;
  64063. BtCursor *pCrsr;
  64064. int res;
  64065. UnpackedRecord r;
  64066. #endif /* local variables moved into u.bt */
  64067. assert( pOp->p3>0 );
  64068. assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
  64069. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64070. u.bt.pC = p->apCsr[pOp->p1];
  64071. assert( u.bt.pC!=0 );
  64072. u.bt.pCrsr = u.bt.pC->pCursor;
  64073. if( ALWAYS(u.bt.pCrsr!=0) ){
  64074. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  64075. u.bt.r.nField = (u16)pOp->p3;
  64076. u.bt.r.flags = 0;
  64077. u.bt.r.aMem = &aMem[pOp->p2];
  64078. #ifdef SQLITE_DEBUG
  64079. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  64080. #endif
  64081. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  64082. if( rc==SQLITE_OK && u.bt.res==0 ){
  64083. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  64084. }
  64085. assert( u.bt.pC->deferredMoveto==0 );
  64086. u.bt.pC->cacheStatus = CACHE_STALE;
  64087. }
  64088. break;
  64089. }
  64090. /* Opcode: IdxRowid P1 P2 * * *
  64091. **
  64092. ** Write into register P2 an integer which is the last entry in the record at
  64093. ** the end of the index key pointed to by cursor P1. This integer should be
  64094. ** the rowid of the table entry to which this index entry points.
  64095. **
  64096. ** See also: Rowid, MakeRecord.
  64097. */
  64098. case OP_IdxRowid: { /* out2-prerelease */
  64099. #if 0 /* local variables moved into u.bu */
  64100. BtCursor *pCrsr;
  64101. VdbeCursor *pC;
  64102. i64 rowid;
  64103. #endif /* local variables moved into u.bu */
  64104. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64105. u.bu.pC = p->apCsr[pOp->p1];
  64106. assert( u.bu.pC!=0 );
  64107. u.bu.pCrsr = u.bu.pC->pCursor;
  64108. pOut->flags = MEM_Null;
  64109. if( ALWAYS(u.bu.pCrsr!=0) ){
  64110. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  64111. if( NEVER(rc) ) goto abort_due_to_error;
  64112. assert( u.bu.pC->deferredMoveto==0 );
  64113. assert( u.bu.pC->isTable==0 );
  64114. if( !u.bu.pC->nullRow ){
  64115. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  64116. if( rc!=SQLITE_OK ){
  64117. goto abort_due_to_error;
  64118. }
  64119. pOut->u.i = u.bu.rowid;
  64120. pOut->flags = MEM_Int;
  64121. }
  64122. }
  64123. break;
  64124. }
  64125. /* Opcode: IdxGE P1 P2 P3 P4 P5
  64126. **
  64127. ** The P4 register values beginning with P3 form an unpacked index
  64128. ** key that omits the ROWID. Compare this key value against the index
  64129. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  64130. **
  64131. ** If the P1 index entry is greater than or equal to the key value
  64132. ** then jump to P2. Otherwise fall through to the next instruction.
  64133. **
  64134. ** If P5 is non-zero then the key value is increased by an epsilon
  64135. ** prior to the comparison. This make the opcode work like IdxGT except
  64136. ** that if the key from register P3 is a prefix of the key in the cursor,
  64137. ** the result is false whereas it would be true with IdxGT.
  64138. */
  64139. /* Opcode: IdxLT P1 P2 P3 P4 P5
  64140. **
  64141. ** The P4 register values beginning with P3 form an unpacked index
  64142. ** key that omits the ROWID. Compare this key value against the index
  64143. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  64144. **
  64145. ** If the P1 index entry is less than the key value then jump to P2.
  64146. ** Otherwise fall through to the next instruction.
  64147. **
  64148. ** If P5 is non-zero then the key value is increased by an epsilon prior
  64149. ** to the comparison. This makes the opcode work like IdxLE.
  64150. */
  64151. case OP_IdxLT: /* jump */
  64152. case OP_IdxGE: { /* jump */
  64153. #if 0 /* local variables moved into u.bv */
  64154. VdbeCursor *pC;
  64155. int res;
  64156. UnpackedRecord r;
  64157. #endif /* local variables moved into u.bv */
  64158. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  64159. u.bv.pC = p->apCsr[pOp->p1];
  64160. assert( u.bv.pC!=0 );
  64161. assert( u.bv.pC->isOrdered );
  64162. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  64163. assert( u.bv.pC->deferredMoveto==0 );
  64164. assert( pOp->p5==0 || pOp->p5==1 );
  64165. assert( pOp->p4type==P4_INT32 );
  64166. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  64167. u.bv.r.nField = (u16)pOp->p4.i;
  64168. if( pOp->p5 ){
  64169. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  64170. }else{
  64171. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  64172. }
  64173. u.bv.r.aMem = &aMem[pOp->p3];
  64174. #ifdef SQLITE_DEBUG
  64175. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  64176. #endif
  64177. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  64178. if( pOp->opcode==OP_IdxLT ){
  64179. u.bv.res = -u.bv.res;
  64180. }else{
  64181. assert( pOp->opcode==OP_IdxGE );
  64182. u.bv.res++;
  64183. }
  64184. if( u.bv.res>0 ){
  64185. pc = pOp->p2 - 1 ;
  64186. }
  64187. }
  64188. break;
  64189. }
  64190. /* Opcode: Destroy P1 P2 P3 * *
  64191. **
  64192. ** Delete an entire database table or index whose root page in the database
  64193. ** file is given by P1.
  64194. **
  64195. ** The table being destroyed is in the main database file if P3==0. If
  64196. ** P3==1 then the table to be clear is in the auxiliary database file
  64197. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  64198. **
  64199. ** If AUTOVACUUM is enabled then it is possible that another root page
  64200. ** might be moved into the newly deleted root page in order to keep all
  64201. ** root pages contiguous at the beginning of the database. The former
  64202. ** value of the root page that moved - its value before the move occurred -
  64203. ** is stored in register P2. If no page
  64204. ** movement was required (because the table being dropped was already
  64205. ** the last one in the database) then a zero is stored in register P2.
  64206. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  64207. **
  64208. ** See also: Clear
  64209. */
  64210. case OP_Destroy: { /* out2-prerelease */
  64211. #if 0 /* local variables moved into u.bw */
  64212. int iMoved;
  64213. int iCnt;
  64214. Vdbe *pVdbe;
  64215. int iDb;
  64216. #endif /* local variables moved into u.bw */
  64217. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64218. u.bw.iCnt = 0;
  64219. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  64220. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
  64221. u.bw.iCnt++;
  64222. }
  64223. }
  64224. #else
  64225. u.bw.iCnt = db->activeVdbeCnt;
  64226. #endif
  64227. pOut->flags = MEM_Null;
  64228. if( u.bw.iCnt>1 ){
  64229. rc = SQLITE_LOCKED;
  64230. p->errorAction = OE_Abort;
  64231. }else{
  64232. u.bw.iDb = pOp->p3;
  64233. assert( u.bw.iCnt==1 );
  64234. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  64235. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  64236. pOut->flags = MEM_Int;
  64237. pOut->u.i = u.bw.iMoved;
  64238. #ifndef SQLITE_OMIT_AUTOVACUUM
  64239. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  64240. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  64241. /* All OP_Destroy operations occur on the same btree */
  64242. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  64243. resetSchemaOnFault = u.bw.iDb+1;
  64244. }
  64245. #endif
  64246. }
  64247. break;
  64248. }
  64249. /* Opcode: Clear P1 P2 P3
  64250. **
  64251. ** Delete all contents of the database table or index whose root page
  64252. ** in the database file is given by P1. But, unlike Destroy, do not
  64253. ** remove the table or index from the database file.
  64254. **
  64255. ** The table being clear is in the main database file if P2==0. If
  64256. ** P2==1 then the table to be clear is in the auxiliary database file
  64257. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  64258. **
  64259. ** If the P3 value is non-zero, then the table referred to must be an
  64260. ** intkey table (an SQL table, not an index). In this case the row change
  64261. ** count is incremented by the number of rows in the table being cleared.
  64262. ** If P3 is greater than zero, then the value stored in register P3 is
  64263. ** also incremented by the number of rows in the table being cleared.
  64264. **
  64265. ** See also: Destroy
  64266. */
  64267. case OP_Clear: {
  64268. #if 0 /* local variables moved into u.bx */
  64269. int nChange;
  64270. #endif /* local variables moved into u.bx */
  64271. u.bx.nChange = 0;
  64272. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  64273. rc = sqlite3BtreeClearTable(
  64274. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  64275. );
  64276. if( pOp->p3 ){
  64277. p->nChange += u.bx.nChange;
  64278. if( pOp->p3>0 ){
  64279. assert( memIsValid(&aMem[pOp->p3]) );
  64280. memAboutToChange(p, &aMem[pOp->p3]);
  64281. aMem[pOp->p3].u.i += u.bx.nChange;
  64282. }
  64283. }
  64284. break;
  64285. }
  64286. /* Opcode: CreateTable P1 P2 * * *
  64287. **
  64288. ** Allocate a new table in the main database file if P1==0 or in the
  64289. ** auxiliary database file if P1==1 or in an attached database if
  64290. ** P1>1. Write the root page number of the new table into
  64291. ** register P2
  64292. **
  64293. ** The difference between a table and an index is this: A table must
  64294. ** have a 4-byte integer key and can have arbitrary data. An index
  64295. ** has an arbitrary key but no data.
  64296. **
  64297. ** See also: CreateIndex
  64298. */
  64299. /* Opcode: CreateIndex P1 P2 * * *
  64300. **
  64301. ** Allocate a new index in the main database file if P1==0 or in the
  64302. ** auxiliary database file if P1==1 or in an attached database if
  64303. ** P1>1. Write the root page number of the new table into
  64304. ** register P2.
  64305. **
  64306. ** See documentation on OP_CreateTable for additional information.
  64307. */
  64308. case OP_CreateIndex: /* out2-prerelease */
  64309. case OP_CreateTable: { /* out2-prerelease */
  64310. #if 0 /* local variables moved into u.by */
  64311. int pgno;
  64312. int flags;
  64313. Db *pDb;
  64314. #endif /* local variables moved into u.by */
  64315. u.by.pgno = 0;
  64316. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64317. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  64318. u.by.pDb = &db->aDb[pOp->p1];
  64319. assert( u.by.pDb->pBt!=0 );
  64320. if( pOp->opcode==OP_CreateTable ){
  64321. /* u.by.flags = BTREE_INTKEY; */
  64322. u.by.flags = BTREE_INTKEY;
  64323. }else{
  64324. u.by.flags = BTREE_BLOBKEY;
  64325. }
  64326. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  64327. pOut->u.i = u.by.pgno;
  64328. break;
  64329. }
  64330. /* Opcode: ParseSchema P1 * * P4 *
  64331. **
  64332. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  64333. ** that match the WHERE clause P4.
  64334. **
  64335. ** This opcode invokes the parser to create a new virtual machine,
  64336. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  64337. */
  64338. case OP_ParseSchema: {
  64339. #if 0 /* local variables moved into u.bz */
  64340. int iDb;
  64341. const char *zMaster;
  64342. char *zSql;
  64343. InitData initData;
  64344. #endif /* local variables moved into u.bz */
  64345. /* Any prepared statement that invokes this opcode will hold mutexes
  64346. ** on every btree. This is a prerequisite for invoking
  64347. ** sqlite3InitCallback().
  64348. */
  64349. #ifdef SQLITE_DEBUG
  64350. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  64351. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  64352. }
  64353. #endif
  64354. u.bz.iDb = pOp->p1;
  64355. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  64356. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  64357. /* Used to be a conditional */ {
  64358. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  64359. u.bz.initData.db = db;
  64360. u.bz.initData.iDb = pOp->p1;
  64361. u.bz.initData.pzErrMsg = &p->zErrMsg;
  64362. u.bz.zSql = sqlite3MPrintf(db,
  64363. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  64364. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  64365. if( u.bz.zSql==0 ){
  64366. rc = SQLITE_NOMEM;
  64367. }else{
  64368. assert( db->init.busy==0 );
  64369. db->init.busy = 1;
  64370. u.bz.initData.rc = SQLITE_OK;
  64371. assert( !db->mallocFailed );
  64372. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  64373. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  64374. sqlite3DbFree(db, u.bz.zSql);
  64375. db->init.busy = 0;
  64376. }
  64377. }
  64378. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  64379. if( rc==SQLITE_NOMEM ){
  64380. goto no_mem;
  64381. }
  64382. break;
  64383. }
  64384. #if !defined(SQLITE_OMIT_ANALYZE)
  64385. /* Opcode: LoadAnalysis P1 * * * *
  64386. **
  64387. ** Read the sqlite_stat1 table for database P1 and load the content
  64388. ** of that table into the internal index hash table. This will cause
  64389. ** the analysis to be used when preparing all subsequent queries.
  64390. */
  64391. case OP_LoadAnalysis: {
  64392. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64393. rc = sqlite3AnalysisLoad(db, pOp->p1);
  64394. break;
  64395. }
  64396. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  64397. /* Opcode: DropTable P1 * * P4 *
  64398. **
  64399. ** Remove the internal (in-memory) data structures that describe
  64400. ** the table named P4 in database P1. This is called after a table
  64401. ** is dropped in order to keep the internal representation of the
  64402. ** schema consistent with what is on disk.
  64403. */
  64404. case OP_DropTable: {
  64405. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  64406. break;
  64407. }
  64408. /* Opcode: DropIndex P1 * * P4 *
  64409. **
  64410. ** Remove the internal (in-memory) data structures that describe
  64411. ** the index named P4 in database P1. This is called after an index
  64412. ** is dropped in order to keep the internal representation of the
  64413. ** schema consistent with what is on disk.
  64414. */
  64415. case OP_DropIndex: {
  64416. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  64417. break;
  64418. }
  64419. /* Opcode: DropTrigger P1 * * P4 *
  64420. **
  64421. ** Remove the internal (in-memory) data structures that describe
  64422. ** the trigger named P4 in database P1. This is called after a trigger
  64423. ** is dropped in order to keep the internal representation of the
  64424. ** schema consistent with what is on disk.
  64425. */
  64426. case OP_DropTrigger: {
  64427. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  64428. break;
  64429. }
  64430. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64431. /* Opcode: IntegrityCk P1 P2 P3 * P5
  64432. **
  64433. ** Do an analysis of the currently open database. Store in
  64434. ** register P1 the text of an error message describing any problems.
  64435. ** If no problems are found, store a NULL in register P1.
  64436. **
  64437. ** The register P3 contains the maximum number of allowed errors.
  64438. ** At most reg(P3) errors will be reported.
  64439. ** In other words, the analysis stops as soon as reg(P1) errors are
  64440. ** seen. Reg(P1) is updated with the number of errors remaining.
  64441. **
  64442. ** The root page numbers of all tables in the database are integer
  64443. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  64444. ** total.
  64445. **
  64446. ** If P5 is not zero, the check is done on the auxiliary database
  64447. ** file, not the main database file.
  64448. **
  64449. ** This opcode is used to implement the integrity_check pragma.
  64450. */
  64451. case OP_IntegrityCk: {
  64452. #if 0 /* local variables moved into u.ca */
  64453. int nRoot; /* Number of tables to check. (Number of root pages.) */
  64454. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  64455. int j; /* Loop counter */
  64456. int nErr; /* Number of errors reported */
  64457. char *z; /* Text of the error report */
  64458. Mem *pnErr; /* Register keeping track of errors remaining */
  64459. #endif /* local variables moved into u.ca */
  64460. u.ca.nRoot = pOp->p2;
  64461. assert( u.ca.nRoot>0 );
  64462. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  64463. if( u.ca.aRoot==0 ) goto no_mem;
  64464. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  64465. u.ca.pnErr = &aMem[pOp->p3];
  64466. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  64467. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  64468. pIn1 = &aMem[pOp->p1];
  64469. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  64470. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  64471. }
  64472. u.ca.aRoot[u.ca.j] = 0;
  64473. assert( pOp->p5<db->nDb );
  64474. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  64475. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  64476. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  64477. sqlite3DbFree(db, u.ca.aRoot);
  64478. u.ca.pnErr->u.i -= u.ca.nErr;
  64479. sqlite3VdbeMemSetNull(pIn1);
  64480. if( u.ca.nErr==0 ){
  64481. assert( u.ca.z==0 );
  64482. }else if( u.ca.z==0 ){
  64483. goto no_mem;
  64484. }else{
  64485. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  64486. }
  64487. UPDATE_MAX_BLOBSIZE(pIn1);
  64488. sqlite3VdbeChangeEncoding(pIn1, encoding);
  64489. break;
  64490. }
  64491. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64492. /* Opcode: RowSetAdd P1 P2 * * *
  64493. **
  64494. ** Insert the integer value held by register P2 into a boolean index
  64495. ** held in register P1.
  64496. **
  64497. ** An assertion fails if P2 is not an integer.
  64498. */
  64499. case OP_RowSetAdd: { /* in1, in2 */
  64500. pIn1 = &aMem[pOp->p1];
  64501. pIn2 = &aMem[pOp->p2];
  64502. assert( (pIn2->flags & MEM_Int)!=0 );
  64503. if( (pIn1->flags & MEM_RowSet)==0 ){
  64504. sqlite3VdbeMemSetRowSet(pIn1);
  64505. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  64506. }
  64507. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  64508. break;
  64509. }
  64510. /* Opcode: RowSetRead P1 P2 P3 * *
  64511. **
  64512. ** Extract the smallest value from boolean index P1 and put that value into
  64513. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  64514. ** unchanged and jump to instruction P2.
  64515. */
  64516. case OP_RowSetRead: { /* jump, in1, out3 */
  64517. #if 0 /* local variables moved into u.cb */
  64518. i64 val;
  64519. #endif /* local variables moved into u.cb */
  64520. CHECK_FOR_INTERRUPT;
  64521. pIn1 = &aMem[pOp->p1];
  64522. if( (pIn1->flags & MEM_RowSet)==0
  64523. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  64524. ){
  64525. /* The boolean index is empty */
  64526. sqlite3VdbeMemSetNull(pIn1);
  64527. pc = pOp->p2 - 1;
  64528. }else{
  64529. /* A value was pulled from the index */
  64530. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  64531. }
  64532. break;
  64533. }
  64534. /* Opcode: RowSetTest P1 P2 P3 P4
  64535. **
  64536. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  64537. ** contains a RowSet object and that RowSet object contains
  64538. ** the value held in P3, jump to register P2. Otherwise, insert the
  64539. ** integer in P3 into the RowSet and continue on to the
  64540. ** next opcode.
  64541. **
  64542. ** The RowSet object is optimized for the case where successive sets
  64543. ** of integers, where each set contains no duplicates. Each set
  64544. ** of values is identified by a unique P4 value. The first set
  64545. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  64546. ** non-negative. For non-negative values of P4 only the lower 4
  64547. ** bits are significant.
  64548. **
  64549. ** This allows optimizations: (a) when P4==0 there is no need to test
  64550. ** the rowset object for P3, as it is guaranteed not to contain it,
  64551. ** (b) when P4==-1 there is no need to insert the value, as it will
  64552. ** never be tested for, and (c) when a value that is part of set X is
  64553. ** inserted, there is no need to search to see if the same value was
  64554. ** previously inserted as part of set X (only if it was previously
  64555. ** inserted as part of some other set).
  64556. */
  64557. case OP_RowSetTest: { /* jump, in1, in3 */
  64558. #if 0 /* local variables moved into u.cc */
  64559. int iSet;
  64560. int exists;
  64561. #endif /* local variables moved into u.cc */
  64562. pIn1 = &aMem[pOp->p1];
  64563. pIn3 = &aMem[pOp->p3];
  64564. u.cc.iSet = pOp->p4.i;
  64565. assert( pIn3->flags&MEM_Int );
  64566. /* If there is anything other than a rowset object in memory cell P1,
  64567. ** delete it now and initialize P1 with an empty rowset
  64568. */
  64569. if( (pIn1->flags & MEM_RowSet)==0 ){
  64570. sqlite3VdbeMemSetRowSet(pIn1);
  64571. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  64572. }
  64573. assert( pOp->p4type==P4_INT32 );
  64574. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  64575. if( u.cc.iSet ){
  64576. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  64577. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  64578. pIn3->u.i);
  64579. if( u.cc.exists ){
  64580. pc = pOp->p2 - 1;
  64581. break;
  64582. }
  64583. }
  64584. if( u.cc.iSet>=0 ){
  64585. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  64586. }
  64587. break;
  64588. }
  64589. #ifndef SQLITE_OMIT_TRIGGER
  64590. /* Opcode: Program P1 P2 P3 P4 *
  64591. **
  64592. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  64593. **
  64594. ** P1 contains the address of the memory cell that contains the first memory
  64595. ** cell in an array of values used as arguments to the sub-program. P2
  64596. ** contains the address to jump to if the sub-program throws an IGNORE
  64597. ** exception using the RAISE() function. Register P3 contains the address
  64598. ** of a memory cell in this (the parent) VM that is used to allocate the
  64599. ** memory required by the sub-vdbe at runtime.
  64600. **
  64601. ** P4 is a pointer to the VM containing the trigger program.
  64602. */
  64603. case OP_Program: { /* jump */
  64604. #if 0 /* local variables moved into u.cd */
  64605. int nMem; /* Number of memory registers for sub-program */
  64606. int nByte; /* Bytes of runtime space required for sub-program */
  64607. Mem *pRt; /* Register to allocate runtime space */
  64608. Mem *pMem; /* Used to iterate through memory cells */
  64609. Mem *pEnd; /* Last memory cell in new array */
  64610. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  64611. SubProgram *pProgram; /* Sub-program to execute */
  64612. void *t; /* Token identifying trigger */
  64613. #endif /* local variables moved into u.cd */
  64614. u.cd.pProgram = pOp->p4.pProgram;
  64615. u.cd.pRt = &aMem[pOp->p3];
  64616. assert( u.cd.pProgram->nOp>0 );
  64617. /* If the p5 flag is clear, then recursive invocation of triggers is
  64618. ** disabled for backwards compatibility (p5 is set if this sub-program
  64619. ** is really a trigger, not a foreign key action, and the flag set
  64620. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  64621. **
  64622. ** It is recursive invocation of triggers, at the SQL level, that is
  64623. ** disabled. In some cases a single trigger may generate more than one
  64624. ** SubProgram (if the trigger may be executed with more than one different
  64625. ** ON CONFLICT algorithm). SubProgram structures associated with a
  64626. ** single trigger all have the same value for the SubProgram.token
  64627. ** variable. */
  64628. if( pOp->p5 ){
  64629. u.cd.t = u.cd.pProgram->token;
  64630. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  64631. if( u.cd.pFrame ) break;
  64632. }
  64633. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  64634. rc = SQLITE_ERROR;
  64635. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  64636. break;
  64637. }
  64638. /* Register u.cd.pRt is used to store the memory required to save the state
  64639. ** of the current program, and the memory required at runtime to execute
  64640. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  64641. ** is already allocated. Otherwise, it must be initialized. */
  64642. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  64643. /* SubProgram.nMem is set to the number of memory cells used by the
  64644. ** program stored in SubProgram.aOp. As well as these, one memory
  64645. ** cell is required for each cursor used by the program. Set local
  64646. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  64647. */
  64648. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  64649. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  64650. + u.cd.nMem * sizeof(Mem)
  64651. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  64652. + u.cd.pProgram->nOnce * sizeof(u8);
  64653. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  64654. if( !u.cd.pFrame ){
  64655. goto no_mem;
  64656. }
  64657. sqlite3VdbeMemRelease(u.cd.pRt);
  64658. u.cd.pRt->flags = MEM_Frame;
  64659. u.cd.pRt->u.pFrame = u.cd.pFrame;
  64660. u.cd.pFrame->v = p;
  64661. u.cd.pFrame->nChildMem = u.cd.nMem;
  64662. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  64663. u.cd.pFrame->pc = pc;
  64664. u.cd.pFrame->aMem = p->aMem;
  64665. u.cd.pFrame->nMem = p->nMem;
  64666. u.cd.pFrame->apCsr = p->apCsr;
  64667. u.cd.pFrame->nCursor = p->nCursor;
  64668. u.cd.pFrame->aOp = p->aOp;
  64669. u.cd.pFrame->nOp = p->nOp;
  64670. u.cd.pFrame->token = u.cd.pProgram->token;
  64671. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  64672. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  64673. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  64674. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  64675. u.cd.pMem->flags = MEM_Invalid;
  64676. u.cd.pMem->db = db;
  64677. }
  64678. }else{
  64679. u.cd.pFrame = u.cd.pRt->u.pFrame;
  64680. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  64681. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  64682. assert( pc==u.cd.pFrame->pc );
  64683. }
  64684. p->nFrame++;
  64685. u.cd.pFrame->pParent = p->pFrame;
  64686. u.cd.pFrame->lastRowid = lastRowid;
  64687. u.cd.pFrame->nChange = p->nChange;
  64688. p->nChange = 0;
  64689. p->pFrame = u.cd.pFrame;
  64690. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  64691. p->nMem = u.cd.pFrame->nChildMem;
  64692. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  64693. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  64694. p->aOp = aOp = u.cd.pProgram->aOp;
  64695. p->nOp = u.cd.pProgram->nOp;
  64696. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  64697. p->nOnceFlag = u.cd.pProgram->nOnce;
  64698. pc = -1;
  64699. memset(p->aOnceFlag, 0, p->nOnceFlag);
  64700. break;
  64701. }
  64702. /* Opcode: Param P1 P2 * * *
  64703. **
  64704. ** This opcode is only ever present in sub-programs called via the
  64705. ** OP_Program instruction. Copy a value currently stored in a memory
  64706. ** cell of the calling (parent) frame to cell P2 in the current frames
  64707. ** address space. This is used by trigger programs to access the new.*
  64708. ** and old.* values.
  64709. **
  64710. ** The address of the cell in the parent frame is determined by adding
  64711. ** the value of the P1 argument to the value of the P1 argument to the
  64712. ** calling OP_Program instruction.
  64713. */
  64714. case OP_Param: { /* out2-prerelease */
  64715. #if 0 /* local variables moved into u.ce */
  64716. VdbeFrame *pFrame;
  64717. Mem *pIn;
  64718. #endif /* local variables moved into u.ce */
  64719. u.ce.pFrame = p->pFrame;
  64720. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  64721. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  64722. break;
  64723. }
  64724. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  64725. #ifndef SQLITE_OMIT_FOREIGN_KEY
  64726. /* Opcode: FkCounter P1 P2 * * *
  64727. **
  64728. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  64729. ** If P1 is non-zero, the database constraint counter is incremented
  64730. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  64731. ** statement counter is incremented (immediate foreign key constraints).
  64732. */
  64733. case OP_FkCounter: {
  64734. if( pOp->p1 ){
  64735. db->nDeferredCons += pOp->p2;
  64736. }else{
  64737. p->nFkConstraint += pOp->p2;
  64738. }
  64739. break;
  64740. }
  64741. /* Opcode: FkIfZero P1 P2 * * *
  64742. **
  64743. ** This opcode tests if a foreign key constraint-counter is currently zero.
  64744. ** If so, jump to instruction P2. Otherwise, fall through to the next
  64745. ** instruction.
  64746. **
  64747. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  64748. ** is zero (the one that counts deferred constraint violations). If P1 is
  64749. ** zero, the jump is taken if the statement constraint-counter is zero
  64750. ** (immediate foreign key constraint violations).
  64751. */
  64752. case OP_FkIfZero: { /* jump */
  64753. if( pOp->p1 ){
  64754. if( db->nDeferredCons==0 ) pc = pOp->p2-1;
  64755. }else{
  64756. if( p->nFkConstraint==0 ) pc = pOp->p2-1;
  64757. }
  64758. break;
  64759. }
  64760. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  64761. #ifndef SQLITE_OMIT_AUTOINCREMENT
  64762. /* Opcode: MemMax P1 P2 * * *
  64763. **
  64764. ** P1 is a register in the root frame of this VM (the root frame is
  64765. ** different from the current frame if this instruction is being executed
  64766. ** within a sub-program). Set the value of register P1 to the maximum of
  64767. ** its current value and the value in register P2.
  64768. **
  64769. ** This instruction throws an error if the memory cell is not initially
  64770. ** an integer.
  64771. */
  64772. case OP_MemMax: { /* in2 */
  64773. #if 0 /* local variables moved into u.cf */
  64774. Mem *pIn1;
  64775. VdbeFrame *pFrame;
  64776. #endif /* local variables moved into u.cf */
  64777. if( p->pFrame ){
  64778. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  64779. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  64780. }else{
  64781. u.cf.pIn1 = &aMem[pOp->p1];
  64782. }
  64783. assert( memIsValid(u.cf.pIn1) );
  64784. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  64785. pIn2 = &aMem[pOp->p2];
  64786. sqlite3VdbeMemIntegerify(pIn2);
  64787. if( u.cf.pIn1->u.i<pIn2->u.i){
  64788. u.cf.pIn1->u.i = pIn2->u.i;
  64789. }
  64790. break;
  64791. }
  64792. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  64793. /* Opcode: IfPos P1 P2 * * *
  64794. **
  64795. ** If the value of register P1 is 1 or greater, jump to P2.
  64796. **
  64797. ** It is illegal to use this instruction on a register that does
  64798. ** not contain an integer. An assertion fault will result if you try.
  64799. */
  64800. case OP_IfPos: { /* jump, in1 */
  64801. pIn1 = &aMem[pOp->p1];
  64802. assert( pIn1->flags&MEM_Int );
  64803. if( pIn1->u.i>0 ){
  64804. pc = pOp->p2 - 1;
  64805. }
  64806. break;
  64807. }
  64808. /* Opcode: IfNeg P1 P2 * * *
  64809. **
  64810. ** If the value of register P1 is less than zero, jump to P2.
  64811. **
  64812. ** It is illegal to use this instruction on a register that does
  64813. ** not contain an integer. An assertion fault will result if you try.
  64814. */
  64815. case OP_IfNeg: { /* jump, in1 */
  64816. pIn1 = &aMem[pOp->p1];
  64817. assert( pIn1->flags&MEM_Int );
  64818. if( pIn1->u.i<0 ){
  64819. pc = pOp->p2 - 1;
  64820. }
  64821. break;
  64822. }
  64823. /* Opcode: IfZero P1 P2 P3 * *
  64824. **
  64825. ** The register P1 must contain an integer. Add literal P3 to the
  64826. ** value in register P1. If the result is exactly 0, jump to P2.
  64827. **
  64828. ** It is illegal to use this instruction on a register that does
  64829. ** not contain an integer. An assertion fault will result if you try.
  64830. */
  64831. case OP_IfZero: { /* jump, in1 */
  64832. pIn1 = &aMem[pOp->p1];
  64833. assert( pIn1->flags&MEM_Int );
  64834. pIn1->u.i += pOp->p3;
  64835. if( pIn1->u.i==0 ){
  64836. pc = pOp->p2 - 1;
  64837. }
  64838. break;
  64839. }
  64840. /* Opcode: AggStep * P2 P3 P4 P5
  64841. **
  64842. ** Execute the step function for an aggregate. The
  64843. ** function has P5 arguments. P4 is a pointer to the FuncDef
  64844. ** structure that specifies the function. Use register
  64845. ** P3 as the accumulator.
  64846. **
  64847. ** The P5 arguments are taken from register P2 and its
  64848. ** successors.
  64849. */
  64850. case OP_AggStep: {
  64851. #if 0 /* local variables moved into u.cg */
  64852. int n;
  64853. int i;
  64854. Mem *pMem;
  64855. Mem *pRec;
  64856. sqlite3_context ctx;
  64857. sqlite3_value **apVal;
  64858. #endif /* local variables moved into u.cg */
  64859. u.cg.n = pOp->p5;
  64860. assert( u.cg.n>=0 );
  64861. u.cg.pRec = &aMem[pOp->p2];
  64862. u.cg.apVal = p->apArg;
  64863. assert( u.cg.apVal || u.cg.n==0 );
  64864. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  64865. assert( memIsValid(u.cg.pRec) );
  64866. u.cg.apVal[u.cg.i] = u.cg.pRec;
  64867. memAboutToChange(p, u.cg.pRec);
  64868. sqlite3VdbeMemStoreType(u.cg.pRec);
  64869. }
  64870. u.cg.ctx.pFunc = pOp->p4.pFunc;
  64871. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  64872. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  64873. u.cg.pMem->n++;
  64874. u.cg.ctx.s.flags = MEM_Null;
  64875. u.cg.ctx.s.z = 0;
  64876. u.cg.ctx.s.zMalloc = 0;
  64877. u.cg.ctx.s.xDel = 0;
  64878. u.cg.ctx.s.db = db;
  64879. u.cg.ctx.isError = 0;
  64880. u.cg.ctx.pColl = 0;
  64881. u.cg.ctx.skipFlag = 0;
  64882. if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  64883. assert( pOp>p->aOp );
  64884. assert( pOp[-1].p4type==P4_COLLSEQ );
  64885. assert( pOp[-1].opcode==OP_CollSeq );
  64886. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  64887. }
  64888. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  64889. if( u.cg.ctx.isError ){
  64890. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  64891. rc = u.cg.ctx.isError;
  64892. }
  64893. if( u.cg.ctx.skipFlag ){
  64894. assert( pOp[-1].opcode==OP_CollSeq );
  64895. u.cg.i = pOp[-1].p1;
  64896. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  64897. }
  64898. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  64899. break;
  64900. }
  64901. /* Opcode: AggFinal P1 P2 * P4 *
  64902. **
  64903. ** Execute the finalizer function for an aggregate. P1 is
  64904. ** the memory location that is the accumulator for the aggregate.
  64905. **
  64906. ** P2 is the number of arguments that the step function takes and
  64907. ** P4 is a pointer to the FuncDef for this function. The P2
  64908. ** argument is not used by this opcode. It is only there to disambiguate
  64909. ** functions that can take varying numbers of arguments. The
  64910. ** P4 argument is only needed for the degenerate case where
  64911. ** the step function was not previously called.
  64912. */
  64913. case OP_AggFinal: {
  64914. #if 0 /* local variables moved into u.ch */
  64915. Mem *pMem;
  64916. #endif /* local variables moved into u.ch */
  64917. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  64918. u.ch.pMem = &aMem[pOp->p1];
  64919. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  64920. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  64921. if( rc ){
  64922. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  64923. }
  64924. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  64925. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  64926. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  64927. goto too_big;
  64928. }
  64929. break;
  64930. }
  64931. #ifndef SQLITE_OMIT_WAL
  64932. /* Opcode: Checkpoint P1 P2 P3 * *
  64933. **
  64934. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  64935. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  64936. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  64937. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  64938. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  64939. ** in the WAL that have been checkpointed after the checkpoint
  64940. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  64941. ** mem[P3+2] are initialized to -1.
  64942. */
  64943. case OP_Checkpoint: {
  64944. #if 0 /* local variables moved into u.ci */
  64945. int i; /* Loop counter */
  64946. int aRes[3]; /* Results */
  64947. Mem *pMem; /* Write results here */
  64948. #endif /* local variables moved into u.ci */
  64949. u.ci.aRes[0] = 0;
  64950. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  64951. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  64952. || pOp->p2==SQLITE_CHECKPOINT_FULL
  64953. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  64954. );
  64955. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  64956. if( rc==SQLITE_BUSY ){
  64957. rc = SQLITE_OK;
  64958. u.ci.aRes[0] = 1;
  64959. }
  64960. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  64961. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  64962. }
  64963. break;
  64964. };
  64965. #endif
  64966. #ifndef SQLITE_OMIT_PRAGMA
  64967. /* Opcode: JournalMode P1 P2 P3 * P5
  64968. **
  64969. ** Change the journal mode of database P1 to P3. P3 must be one of the
  64970. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  64971. ** modes (delete, truncate, persist, off and memory), this is a simple
  64972. ** operation. No IO is required.
  64973. **
  64974. ** If changing into or out of WAL mode the procedure is more complicated.
  64975. **
  64976. ** Write a string containing the final journal-mode to register P2.
  64977. */
  64978. case OP_JournalMode: { /* out2-prerelease */
  64979. #if 0 /* local variables moved into u.cj */
  64980. Btree *pBt; /* Btree to change journal mode of */
  64981. Pager *pPager; /* Pager associated with pBt */
  64982. int eNew; /* New journal mode */
  64983. int eOld; /* The old journal mode */
  64984. #ifndef SQLITE_OMIT_WAL
  64985. const char *zFilename; /* Name of database file for pPager */
  64986. #endif
  64987. #endif /* local variables moved into u.cj */
  64988. u.cj.eNew = pOp->p3;
  64989. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  64990. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  64991. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  64992. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  64993. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  64994. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  64995. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  64996. );
  64997. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  64998. u.cj.pBt = db->aDb[pOp->p1].pBt;
  64999. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  65000. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  65001. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  65002. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  65003. #ifndef SQLITE_OMIT_WAL
  65004. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  65005. /* Do not allow a transition to journal_mode=WAL for a database
  65006. ** in temporary storage or if the VFS does not support shared memory
  65007. */
  65008. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  65009. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  65010. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  65011. ){
  65012. u.cj.eNew = u.cj.eOld;
  65013. }
  65014. if( (u.cj.eNew!=u.cj.eOld)
  65015. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  65016. ){
  65017. if( !db->autoCommit || db->activeVdbeCnt>1 ){
  65018. rc = SQLITE_ERROR;
  65019. sqlite3SetString(&p->zErrMsg, db,
  65020. "cannot change %s wal mode from within a transaction",
  65021. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  65022. );
  65023. break;
  65024. }else{
  65025. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  65026. /* If leaving WAL mode, close the log file. If successful, the call
  65027. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  65028. ** file. An EXCLUSIVE lock may still be held on the database file
  65029. ** after a successful return.
  65030. */
  65031. rc = sqlite3PagerCloseWal(u.cj.pPager);
  65032. if( rc==SQLITE_OK ){
  65033. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  65034. }
  65035. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  65036. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  65037. ** as an intermediate */
  65038. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  65039. }
  65040. /* Open a transaction on the database file. Regardless of the journal
  65041. ** mode, this transaction always uses a rollback journal.
  65042. */
  65043. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  65044. if( rc==SQLITE_OK ){
  65045. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  65046. }
  65047. }
  65048. }
  65049. #endif /* ifndef SQLITE_OMIT_WAL */
  65050. if( rc ){
  65051. u.cj.eNew = u.cj.eOld;
  65052. }
  65053. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  65054. pOut = &aMem[pOp->p2];
  65055. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  65056. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  65057. pOut->n = sqlite3Strlen30(pOut->z);
  65058. pOut->enc = SQLITE_UTF8;
  65059. sqlite3VdbeChangeEncoding(pOut, encoding);
  65060. break;
  65061. };
  65062. #endif /* SQLITE_OMIT_PRAGMA */
  65063. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  65064. /* Opcode: Vacuum * * * * *
  65065. **
  65066. ** Vacuum the entire database. This opcode will cause other virtual
  65067. ** machines to be created and run. It may not be called from within
  65068. ** a transaction.
  65069. */
  65070. case OP_Vacuum: {
  65071. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  65072. break;
  65073. }
  65074. #endif
  65075. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  65076. /* Opcode: IncrVacuum P1 P2 * * *
  65077. **
  65078. ** Perform a single step of the incremental vacuum procedure on
  65079. ** the P1 database. If the vacuum has finished, jump to instruction
  65080. ** P2. Otherwise, fall through to the next instruction.
  65081. */
  65082. case OP_IncrVacuum: { /* jump */
  65083. #if 0 /* local variables moved into u.ck */
  65084. Btree *pBt;
  65085. #endif /* local variables moved into u.ck */
  65086. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  65087. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  65088. u.ck.pBt = db->aDb[pOp->p1].pBt;
  65089. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  65090. if( rc==SQLITE_DONE ){
  65091. pc = pOp->p2 - 1;
  65092. rc = SQLITE_OK;
  65093. }
  65094. break;
  65095. }
  65096. #endif
  65097. /* Opcode: Expire P1 * * * *
  65098. **
  65099. ** Cause precompiled statements to become expired. An expired statement
  65100. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  65101. ** (via sqlite3_step()).
  65102. **
  65103. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  65104. ** then only the currently executing statement is affected.
  65105. */
  65106. case OP_Expire: {
  65107. if( !pOp->p1 ){
  65108. sqlite3ExpirePreparedStatements(db);
  65109. }else{
  65110. p->expired = 1;
  65111. }
  65112. break;
  65113. }
  65114. #ifndef SQLITE_OMIT_SHARED_CACHE
  65115. /* Opcode: TableLock P1 P2 P3 P4 *
  65116. **
  65117. ** Obtain a lock on a particular table. This instruction is only used when
  65118. ** the shared-cache feature is enabled.
  65119. **
  65120. ** P1 is the index of the database in sqlite3.aDb[] of the database
  65121. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  65122. ** a write lock if P3==1.
  65123. **
  65124. ** P2 contains the root-page of the table to lock.
  65125. **
  65126. ** P4 contains a pointer to the name of the table being locked. This is only
  65127. ** used to generate an error message if the lock cannot be obtained.
  65128. */
  65129. case OP_TableLock: {
  65130. u8 isWriteLock = (u8)pOp->p3;
  65131. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  65132. int p1 = pOp->p1;
  65133. assert( p1>=0 && p1<db->nDb );
  65134. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  65135. assert( isWriteLock==0 || isWriteLock==1 );
  65136. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  65137. if( (rc&0xFF)==SQLITE_LOCKED ){
  65138. const char *z = pOp->p4.z;
  65139. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  65140. }
  65141. }
  65142. break;
  65143. }
  65144. #endif /* SQLITE_OMIT_SHARED_CACHE */
  65145. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65146. /* Opcode: VBegin * * * P4 *
  65147. **
  65148. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  65149. ** xBegin method for that table.
  65150. **
  65151. ** Also, whether or not P4 is set, check that this is not being called from
  65152. ** within a callback to a virtual table xSync() method. If it is, the error
  65153. ** code will be set to SQLITE_LOCKED.
  65154. */
  65155. case OP_VBegin: {
  65156. #if 0 /* local variables moved into u.cl */
  65157. VTable *pVTab;
  65158. #endif /* local variables moved into u.cl */
  65159. u.cl.pVTab = pOp->p4.pVtab;
  65160. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  65161. if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
  65162. break;
  65163. }
  65164. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65165. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65166. /* Opcode: VCreate P1 * * P4 *
  65167. **
  65168. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  65169. ** for that table.
  65170. */
  65171. case OP_VCreate: {
  65172. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  65173. break;
  65174. }
  65175. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65176. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65177. /* Opcode: VDestroy P1 * * P4 *
  65178. **
  65179. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  65180. ** of that table.
  65181. */
  65182. case OP_VDestroy: {
  65183. p->inVtabMethod = 2;
  65184. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  65185. p->inVtabMethod = 0;
  65186. break;
  65187. }
  65188. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65189. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65190. /* Opcode: VOpen P1 * * P4 *
  65191. **
  65192. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  65193. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  65194. ** table and stores that cursor in P1.
  65195. */
  65196. case OP_VOpen: {
  65197. #if 0 /* local variables moved into u.cm */
  65198. VdbeCursor *pCur;
  65199. sqlite3_vtab_cursor *pVtabCursor;
  65200. sqlite3_vtab *pVtab;
  65201. sqlite3_module *pModule;
  65202. #endif /* local variables moved into u.cm */
  65203. u.cm.pCur = 0;
  65204. u.cm.pVtabCursor = 0;
  65205. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  65206. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  65207. assert(u.cm.pVtab && u.cm.pModule);
  65208. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  65209. importVtabErrMsg(p, u.cm.pVtab);
  65210. if( SQLITE_OK==rc ){
  65211. /* Initialize sqlite3_vtab_cursor base class */
  65212. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  65213. /* Initialise vdbe cursor object */
  65214. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  65215. if( u.cm.pCur ){
  65216. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  65217. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  65218. }else{
  65219. db->mallocFailed = 1;
  65220. u.cm.pModule->xClose(u.cm.pVtabCursor);
  65221. }
  65222. }
  65223. break;
  65224. }
  65225. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65226. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65227. /* Opcode: VFilter P1 P2 P3 P4 *
  65228. **
  65229. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  65230. ** the filtered result set is empty.
  65231. **
  65232. ** P4 is either NULL or a string that was generated by the xBestIndex
  65233. ** method of the module. The interpretation of the P4 string is left
  65234. ** to the module implementation.
  65235. **
  65236. ** This opcode invokes the xFilter method on the virtual table specified
  65237. ** by P1. The integer query plan parameter to xFilter is stored in register
  65238. ** P3. Register P3+1 stores the argc parameter to be passed to the
  65239. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  65240. ** additional parameters which are passed to
  65241. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  65242. **
  65243. ** A jump is made to P2 if the result set after filtering would be empty.
  65244. */
  65245. case OP_VFilter: { /* jump */
  65246. #if 0 /* local variables moved into u.cn */
  65247. int nArg;
  65248. int iQuery;
  65249. const sqlite3_module *pModule;
  65250. Mem *pQuery;
  65251. Mem *pArgc;
  65252. sqlite3_vtab_cursor *pVtabCursor;
  65253. sqlite3_vtab *pVtab;
  65254. VdbeCursor *pCur;
  65255. int res;
  65256. int i;
  65257. Mem **apArg;
  65258. #endif /* local variables moved into u.cn */
  65259. u.cn.pQuery = &aMem[pOp->p3];
  65260. u.cn.pArgc = &u.cn.pQuery[1];
  65261. u.cn.pCur = p->apCsr[pOp->p1];
  65262. assert( memIsValid(u.cn.pQuery) );
  65263. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  65264. assert( u.cn.pCur->pVtabCursor );
  65265. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  65266. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  65267. u.cn.pModule = u.cn.pVtab->pModule;
  65268. /* Grab the index number and argc parameters */
  65269. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  65270. u.cn.nArg = (int)u.cn.pArgc->u.i;
  65271. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  65272. /* Invoke the xFilter method */
  65273. {
  65274. u.cn.res = 0;
  65275. u.cn.apArg = p->apArg;
  65276. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  65277. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  65278. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  65279. }
  65280. p->inVtabMethod = 1;
  65281. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  65282. p->inVtabMethod = 0;
  65283. importVtabErrMsg(p, u.cn.pVtab);
  65284. if( rc==SQLITE_OK ){
  65285. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  65286. }
  65287. if( u.cn.res ){
  65288. pc = pOp->p2 - 1;
  65289. }
  65290. }
  65291. u.cn.pCur->nullRow = 0;
  65292. break;
  65293. }
  65294. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65295. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65296. /* Opcode: VColumn P1 P2 P3 * *
  65297. **
  65298. ** Store the value of the P2-th column of
  65299. ** the row of the virtual-table that the
  65300. ** P1 cursor is pointing to into register P3.
  65301. */
  65302. case OP_VColumn: {
  65303. #if 0 /* local variables moved into u.co */
  65304. sqlite3_vtab *pVtab;
  65305. const sqlite3_module *pModule;
  65306. Mem *pDest;
  65307. sqlite3_context sContext;
  65308. #endif /* local variables moved into u.co */
  65309. VdbeCursor *pCur = p->apCsr[pOp->p1];
  65310. assert( pCur->pVtabCursor );
  65311. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  65312. u.co.pDest = &aMem[pOp->p3];
  65313. memAboutToChange(p, u.co.pDest);
  65314. if( pCur->nullRow ){
  65315. sqlite3VdbeMemSetNull(u.co.pDest);
  65316. break;
  65317. }
  65318. u.co.pVtab = pCur->pVtabCursor->pVtab;
  65319. u.co.pModule = u.co.pVtab->pModule;
  65320. assert( u.co.pModule->xColumn );
  65321. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  65322. /* The output cell may already have a buffer allocated. Move
  65323. ** the current contents to u.co.sContext.s so in case the user-function
  65324. ** can use the already allocated buffer instead of allocating a
  65325. ** new one.
  65326. */
  65327. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  65328. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  65329. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  65330. importVtabErrMsg(p, u.co.pVtab);
  65331. if( u.co.sContext.isError ){
  65332. rc = u.co.sContext.isError;
  65333. }
  65334. /* Copy the result of the function to the P3 register. We
  65335. ** do this regardless of whether or not an error occurred to ensure any
  65336. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  65337. */
  65338. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  65339. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  65340. REGISTER_TRACE(pOp->p3, u.co.pDest);
  65341. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  65342. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  65343. goto too_big;
  65344. }
  65345. break;
  65346. }
  65347. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65348. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65349. /* Opcode: VNext P1 P2 * * *
  65350. **
  65351. ** Advance virtual table P1 to the next row in its result set and
  65352. ** jump to instruction P2. Or, if the virtual table has reached
  65353. ** the end of its result set, then fall through to the next instruction.
  65354. */
  65355. case OP_VNext: { /* jump */
  65356. #if 0 /* local variables moved into u.cp */
  65357. sqlite3_vtab *pVtab;
  65358. const sqlite3_module *pModule;
  65359. int res;
  65360. VdbeCursor *pCur;
  65361. #endif /* local variables moved into u.cp */
  65362. u.cp.res = 0;
  65363. u.cp.pCur = p->apCsr[pOp->p1];
  65364. assert( u.cp.pCur->pVtabCursor );
  65365. if( u.cp.pCur->nullRow ){
  65366. break;
  65367. }
  65368. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  65369. u.cp.pModule = u.cp.pVtab->pModule;
  65370. assert( u.cp.pModule->xNext );
  65371. /* Invoke the xNext() method of the module. There is no way for the
  65372. ** underlying implementation to return an error if one occurs during
  65373. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  65374. ** data is available) and the error code returned when xColumn or
  65375. ** some other method is next invoked on the save virtual table cursor.
  65376. */
  65377. p->inVtabMethod = 1;
  65378. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  65379. p->inVtabMethod = 0;
  65380. importVtabErrMsg(p, u.cp.pVtab);
  65381. if( rc==SQLITE_OK ){
  65382. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  65383. }
  65384. if( !u.cp.res ){
  65385. /* If there is data, jump to P2 */
  65386. pc = pOp->p2 - 1;
  65387. }
  65388. break;
  65389. }
  65390. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65391. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65392. /* Opcode: VRename P1 * * P4 *
  65393. **
  65394. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  65395. ** This opcode invokes the corresponding xRename method. The value
  65396. ** in register P1 is passed as the zName argument to the xRename method.
  65397. */
  65398. case OP_VRename: {
  65399. #if 0 /* local variables moved into u.cq */
  65400. sqlite3_vtab *pVtab;
  65401. Mem *pName;
  65402. #endif /* local variables moved into u.cq */
  65403. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  65404. u.cq.pName = &aMem[pOp->p1];
  65405. assert( u.cq.pVtab->pModule->xRename );
  65406. assert( memIsValid(u.cq.pName) );
  65407. REGISTER_TRACE(pOp->p1, u.cq.pName);
  65408. assert( u.cq.pName->flags & MEM_Str );
  65409. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  65410. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  65411. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  65412. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  65413. if( rc==SQLITE_OK ){
  65414. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  65415. importVtabErrMsg(p, u.cq.pVtab);
  65416. p->expired = 0;
  65417. }
  65418. break;
  65419. }
  65420. #endif
  65421. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65422. /* Opcode: VUpdate P1 P2 P3 P4 *
  65423. **
  65424. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  65425. ** This opcode invokes the corresponding xUpdate method. P2 values
  65426. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  65427. ** invocation. The value in register (P3+P2-1) corresponds to the
  65428. ** p2th element of the argv array passed to xUpdate.
  65429. **
  65430. ** The xUpdate method will do a DELETE or an INSERT or both.
  65431. ** The argv[0] element (which corresponds to memory cell P3)
  65432. ** is the rowid of a row to delete. If argv[0] is NULL then no
  65433. ** deletion occurs. The argv[1] element is the rowid of the new
  65434. ** row. This can be NULL to have the virtual table select the new
  65435. ** rowid for itself. The subsequent elements in the array are
  65436. ** the values of columns in the new row.
  65437. **
  65438. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  65439. ** a row to delete.
  65440. **
  65441. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  65442. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  65443. ** is set to the value of the rowid for the row just inserted.
  65444. */
  65445. case OP_VUpdate: {
  65446. #if 0 /* local variables moved into u.cr */
  65447. sqlite3_vtab *pVtab;
  65448. sqlite3_module *pModule;
  65449. int nArg;
  65450. int i;
  65451. sqlite_int64 rowid;
  65452. Mem **apArg;
  65453. Mem *pX;
  65454. #endif /* local variables moved into u.cr */
  65455. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  65456. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  65457. );
  65458. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  65459. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  65460. u.cr.nArg = pOp->p2;
  65461. assert( pOp->p4type==P4_VTAB );
  65462. if( ALWAYS(u.cr.pModule->xUpdate) ){
  65463. u8 vtabOnConflict = db->vtabOnConflict;
  65464. u.cr.apArg = p->apArg;
  65465. u.cr.pX = &aMem[pOp->p3];
  65466. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  65467. assert( memIsValid(u.cr.pX) );
  65468. memAboutToChange(p, u.cr.pX);
  65469. sqlite3VdbeMemStoreType(u.cr.pX);
  65470. u.cr.apArg[u.cr.i] = u.cr.pX;
  65471. u.cr.pX++;
  65472. }
  65473. db->vtabOnConflict = pOp->p5;
  65474. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  65475. db->vtabOnConflict = vtabOnConflict;
  65476. importVtabErrMsg(p, u.cr.pVtab);
  65477. if( rc==SQLITE_OK && pOp->p1 ){
  65478. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  65479. db->lastRowid = lastRowid = u.cr.rowid;
  65480. }
  65481. if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  65482. if( pOp->p5==OE_Ignore ){
  65483. rc = SQLITE_OK;
  65484. }else{
  65485. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  65486. }
  65487. }else{
  65488. p->nChange++;
  65489. }
  65490. }
  65491. break;
  65492. }
  65493. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65494. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  65495. /* Opcode: Pagecount P1 P2 * * *
  65496. **
  65497. ** Write the current number of pages in database P1 to memory cell P2.
  65498. */
  65499. case OP_Pagecount: { /* out2-prerelease */
  65500. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  65501. break;
  65502. }
  65503. #endif
  65504. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  65505. /* Opcode: MaxPgcnt P1 P2 P3 * *
  65506. **
  65507. ** Try to set the maximum page count for database P1 to the value in P3.
  65508. ** Do not let the maximum page count fall below the current page count and
  65509. ** do not change the maximum page count value if P3==0.
  65510. **
  65511. ** Store the maximum page count after the change in register P2.
  65512. */
  65513. case OP_MaxPgcnt: { /* out2-prerelease */
  65514. unsigned int newMax;
  65515. Btree *pBt;
  65516. pBt = db->aDb[pOp->p1].pBt;
  65517. newMax = 0;
  65518. if( pOp->p3 ){
  65519. newMax = sqlite3BtreeLastPage(pBt);
  65520. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  65521. }
  65522. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  65523. break;
  65524. }
  65525. #endif
  65526. #ifndef SQLITE_OMIT_TRACE
  65527. /* Opcode: Trace * * * P4 *
  65528. **
  65529. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  65530. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  65531. */
  65532. case OP_Trace: {
  65533. #if 0 /* local variables moved into u.cs */
  65534. char *zTrace;
  65535. char *z;
  65536. #endif /* local variables moved into u.cs */
  65537. if( db->xTrace
  65538. && !p->doingRerun
  65539. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  65540. ){
  65541. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  65542. db->xTrace(db->pTraceArg, u.cs.z);
  65543. sqlite3DbFree(db, u.cs.z);
  65544. }
  65545. #ifdef SQLITE_DEBUG
  65546. if( (db->flags & SQLITE_SqlTrace)!=0
  65547. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  65548. ){
  65549. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  65550. }
  65551. #endif /* SQLITE_DEBUG */
  65552. break;
  65553. }
  65554. #endif
  65555. /* Opcode: Noop * * * * *
  65556. **
  65557. ** Do nothing. This instruction is often useful as a jump
  65558. ** destination.
  65559. */
  65560. /*
  65561. ** The magic Explain opcode are only inserted when explain==2 (which
  65562. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  65563. ** This opcode records information from the optimizer. It is the
  65564. ** the same as a no-op. This opcodesnever appears in a real VM program.
  65565. */
  65566. default: { /* This is really OP_Noop and OP_Explain */
  65567. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  65568. break;
  65569. }
  65570. /*****************************************************************************
  65571. ** The cases of the switch statement above this line should all be indented
  65572. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  65573. ** readability. From this point on down, the normal indentation rules are
  65574. ** restored.
  65575. *****************************************************************************/
  65576. }
  65577. #ifdef VDBE_PROFILE
  65578. {
  65579. u64 elapsed = sqlite3Hwtime() - start;
  65580. pOp->cycles += elapsed;
  65581. pOp->cnt++;
  65582. #if 0
  65583. fprintf(stdout, "%10llu ", elapsed);
  65584. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  65585. #endif
  65586. }
  65587. #endif
  65588. /* The following code adds nothing to the actual functionality
  65589. ** of the program. It is only here for testing and debugging.
  65590. ** On the other hand, it does burn CPU cycles every time through
  65591. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  65592. */
  65593. #ifndef NDEBUG
  65594. assert( pc>=-1 && pc<p->nOp );
  65595. #ifdef SQLITE_DEBUG
  65596. if( p->trace ){
  65597. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  65598. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  65599. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  65600. }
  65601. if( pOp->opflags & OPFLG_OUT3 ){
  65602. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  65603. }
  65604. }
  65605. #endif /* SQLITE_DEBUG */
  65606. #endif /* NDEBUG */
  65607. } /* The end of the for(;;) loop the loops through opcodes */
  65608. /* If we reach this point, it means that execution is finished with
  65609. ** an error of some kind.
  65610. */
  65611. vdbe_error_halt:
  65612. assert( rc );
  65613. p->rc = rc;
  65614. testcase( sqlite3GlobalConfig.xLog!=0 );
  65615. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  65616. pc, p->zSql, p->zErrMsg);
  65617. sqlite3VdbeHalt(p);
  65618. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  65619. rc = SQLITE_ERROR;
  65620. if( resetSchemaOnFault>0 ){
  65621. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  65622. }
  65623. /* This is the only way out of this procedure. We have to
  65624. ** release the mutexes on btrees that were acquired at the
  65625. ** top. */
  65626. vdbe_return:
  65627. db->lastRowid = lastRowid;
  65628. sqlite3VdbeLeave(p);
  65629. return rc;
  65630. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  65631. ** is encountered.
  65632. */
  65633. too_big:
  65634. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  65635. rc = SQLITE_TOOBIG;
  65636. goto vdbe_error_halt;
  65637. /* Jump to here if a malloc() fails.
  65638. */
  65639. no_mem:
  65640. db->mallocFailed = 1;
  65641. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  65642. rc = SQLITE_NOMEM;
  65643. goto vdbe_error_halt;
  65644. /* Jump to here for any other kind of fatal error. The "rc" variable
  65645. ** should hold the error number.
  65646. */
  65647. abort_due_to_error:
  65648. assert( p->zErrMsg==0 );
  65649. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  65650. if( rc!=SQLITE_IOERR_NOMEM ){
  65651. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  65652. }
  65653. goto vdbe_error_halt;
  65654. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  65655. ** flag.
  65656. */
  65657. abort_due_to_interrupt:
  65658. assert( db->u1.isInterrupted );
  65659. rc = SQLITE_INTERRUPT;
  65660. p->rc = rc;
  65661. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  65662. goto vdbe_error_halt;
  65663. }
  65664. /************** End of vdbe.c ************************************************/
  65665. /************** Begin file vdbeblob.c ****************************************/
  65666. /*
  65667. ** 2007 May 1
  65668. **
  65669. ** The author disclaims copyright to this source code. In place of
  65670. ** a legal notice, here is a blessing:
  65671. **
  65672. ** May you do good and not evil.
  65673. ** May you find forgiveness for yourself and forgive others.
  65674. ** May you share freely, never taking more than you give.
  65675. **
  65676. *************************************************************************
  65677. **
  65678. ** This file contains code used to implement incremental BLOB I/O.
  65679. */
  65680. #ifndef SQLITE_OMIT_INCRBLOB
  65681. /*
  65682. ** Valid sqlite3_blob* handles point to Incrblob structures.
  65683. */
  65684. typedef struct Incrblob Incrblob;
  65685. struct Incrblob {
  65686. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  65687. int nByte; /* Size of open blob, in bytes */
  65688. int iOffset; /* Byte offset of blob in cursor data */
  65689. int iCol; /* Table column this handle is open on */
  65690. BtCursor *pCsr; /* Cursor pointing at blob row */
  65691. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  65692. sqlite3 *db; /* The associated database */
  65693. };
  65694. /*
  65695. ** This function is used by both blob_open() and blob_reopen(). It seeks
  65696. ** the b-tree cursor associated with blob handle p to point to row iRow.
  65697. ** If successful, SQLITE_OK is returned and subsequent calls to
  65698. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  65699. **
  65700. ** If an error occurs, or if the specified row does not exist or does not
  65701. ** contain a value of type TEXT or BLOB in the column nominated when the
  65702. ** blob handle was opened, then an error code is returned and *pzErr may
  65703. ** be set to point to a buffer containing an error message. It is the
  65704. ** responsibility of the caller to free the error message buffer using
  65705. ** sqlite3DbFree().
  65706. **
  65707. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  65708. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  65709. ** immediately return SQLITE_ABORT.
  65710. */
  65711. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  65712. int rc; /* Error code */
  65713. char *zErr = 0; /* Error message */
  65714. Vdbe *v = (Vdbe *)p->pStmt;
  65715. /* Set the value of the SQL statements only variable to integer iRow.
  65716. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  65717. ** triggering asserts related to mutexes.
  65718. */
  65719. assert( v->aVar[0].flags&MEM_Int );
  65720. v->aVar[0].u.i = iRow;
  65721. rc = sqlite3_step(p->pStmt);
  65722. if( rc==SQLITE_ROW ){
  65723. u32 type = v->apCsr[0]->aType[p->iCol];
  65724. if( type<12 ){
  65725. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  65726. type==0?"null": type==7?"real": "integer"
  65727. );
  65728. rc = SQLITE_ERROR;
  65729. sqlite3_finalize(p->pStmt);
  65730. p->pStmt = 0;
  65731. }else{
  65732. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  65733. p->nByte = sqlite3VdbeSerialTypeLen(type);
  65734. p->pCsr = v->apCsr[0]->pCursor;
  65735. sqlite3BtreeEnterCursor(p->pCsr);
  65736. sqlite3BtreeCacheOverflow(p->pCsr);
  65737. sqlite3BtreeLeaveCursor(p->pCsr);
  65738. }
  65739. }
  65740. if( rc==SQLITE_ROW ){
  65741. rc = SQLITE_OK;
  65742. }else if( p->pStmt ){
  65743. rc = sqlite3_finalize(p->pStmt);
  65744. p->pStmt = 0;
  65745. if( rc==SQLITE_OK ){
  65746. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  65747. rc = SQLITE_ERROR;
  65748. }else{
  65749. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  65750. }
  65751. }
  65752. assert( rc!=SQLITE_OK || zErr==0 );
  65753. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  65754. *pzErr = zErr;
  65755. return rc;
  65756. }
  65757. /*
  65758. ** Open a blob handle.
  65759. */
  65760. SQLITE_API int sqlite3_blob_open(
  65761. sqlite3* db, /* The database connection */
  65762. const char *zDb, /* The attached database containing the blob */
  65763. const char *zTable, /* The table containing the blob */
  65764. const char *zColumn, /* The column containing the blob */
  65765. sqlite_int64 iRow, /* The row containing the glob */
  65766. int flags, /* True -> read/write access, false -> read-only */
  65767. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  65768. ){
  65769. int nAttempt = 0;
  65770. int iCol; /* Index of zColumn in row-record */
  65771. /* This VDBE program seeks a btree cursor to the identified
  65772. ** db/table/row entry. The reason for using a vdbe program instead
  65773. ** of writing code to use the b-tree layer directly is that the
  65774. ** vdbe program will take advantage of the various transaction,
  65775. ** locking and error handling infrastructure built into the vdbe.
  65776. **
  65777. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  65778. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  65779. ** uses it to implement the blob_read(), blob_write() and
  65780. ** blob_bytes() functions.
  65781. **
  65782. ** The sqlite3_blob_close() function finalizes the vdbe program,
  65783. ** which closes the b-tree cursor and (possibly) commits the
  65784. ** transaction.
  65785. */
  65786. static const VdbeOpList openBlob[] = {
  65787. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  65788. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  65789. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  65790. /* One of the following two instructions is replaced by an OP_Noop. */
  65791. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  65792. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  65793. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  65794. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  65795. {OP_Column, 0, 0, 1}, /* 7 */
  65796. {OP_ResultRow, 1, 0, 0}, /* 8 */
  65797. {OP_Goto, 0, 5, 0}, /* 9 */
  65798. {OP_Close, 0, 0, 0}, /* 10 */
  65799. {OP_Halt, 0, 0, 0}, /* 11 */
  65800. };
  65801. int rc = SQLITE_OK;
  65802. char *zErr = 0;
  65803. Table *pTab;
  65804. Parse *pParse = 0;
  65805. Incrblob *pBlob = 0;
  65806. flags = !!flags; /* flags = (flags ? 1 : 0); */
  65807. *ppBlob = 0;
  65808. sqlite3_mutex_enter(db->mutex);
  65809. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  65810. if( !pBlob ) goto blob_open_out;
  65811. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  65812. if( !pParse ) goto blob_open_out;
  65813. do {
  65814. memset(pParse, 0, sizeof(Parse));
  65815. pParse->db = db;
  65816. sqlite3DbFree(db, zErr);
  65817. zErr = 0;
  65818. sqlite3BtreeEnterAll(db);
  65819. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  65820. if( pTab && IsVirtual(pTab) ){
  65821. pTab = 0;
  65822. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  65823. }
  65824. #ifndef SQLITE_OMIT_VIEW
  65825. if( pTab && pTab->pSelect ){
  65826. pTab = 0;
  65827. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  65828. }
  65829. #endif
  65830. if( !pTab ){
  65831. if( pParse->zErrMsg ){
  65832. sqlite3DbFree(db, zErr);
  65833. zErr = pParse->zErrMsg;
  65834. pParse->zErrMsg = 0;
  65835. }
  65836. rc = SQLITE_ERROR;
  65837. sqlite3BtreeLeaveAll(db);
  65838. goto blob_open_out;
  65839. }
  65840. /* Now search pTab for the exact column. */
  65841. for(iCol=0; iCol<pTab->nCol; iCol++) {
  65842. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  65843. break;
  65844. }
  65845. }
  65846. if( iCol==pTab->nCol ){
  65847. sqlite3DbFree(db, zErr);
  65848. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  65849. rc = SQLITE_ERROR;
  65850. sqlite3BtreeLeaveAll(db);
  65851. goto blob_open_out;
  65852. }
  65853. /* If the value is being opened for writing, check that the
  65854. ** column is not indexed, and that it is not part of a foreign key.
  65855. ** It is against the rules to open a column to which either of these
  65856. ** descriptions applies for writing. */
  65857. if( flags ){
  65858. const char *zFault = 0;
  65859. Index *pIdx;
  65860. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65861. if( db->flags&SQLITE_ForeignKeys ){
  65862. /* Check that the column is not part of an FK child key definition. It
  65863. ** is not necessary to check if it is part of a parent key, as parent
  65864. ** key columns must be indexed. The check below will pick up this
  65865. ** case. */
  65866. FKey *pFKey;
  65867. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  65868. int j;
  65869. for(j=0; j<pFKey->nCol; j++){
  65870. if( pFKey->aCol[j].iFrom==iCol ){
  65871. zFault = "foreign key";
  65872. }
  65873. }
  65874. }
  65875. }
  65876. #endif
  65877. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  65878. int j;
  65879. for(j=0; j<pIdx->nColumn; j++){
  65880. if( pIdx->aiColumn[j]==iCol ){
  65881. zFault = "indexed";
  65882. }
  65883. }
  65884. }
  65885. if( zFault ){
  65886. sqlite3DbFree(db, zErr);
  65887. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  65888. rc = SQLITE_ERROR;
  65889. sqlite3BtreeLeaveAll(db);
  65890. goto blob_open_out;
  65891. }
  65892. }
  65893. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  65894. assert( pBlob->pStmt || db->mallocFailed );
  65895. if( pBlob->pStmt ){
  65896. Vdbe *v = (Vdbe *)pBlob->pStmt;
  65897. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  65898. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  65899. /* Configure the OP_Transaction */
  65900. sqlite3VdbeChangeP1(v, 0, iDb);
  65901. sqlite3VdbeChangeP2(v, 0, flags);
  65902. /* Configure the OP_VerifyCookie */
  65903. sqlite3VdbeChangeP1(v, 1, iDb);
  65904. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  65905. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  65906. /* Make sure a mutex is held on the table to be accessed */
  65907. sqlite3VdbeUsesBtree(v, iDb);
  65908. /* Configure the OP_TableLock instruction */
  65909. #ifdef SQLITE_OMIT_SHARED_CACHE
  65910. sqlite3VdbeChangeToNoop(v, 2);
  65911. #else
  65912. sqlite3VdbeChangeP1(v, 2, iDb);
  65913. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  65914. sqlite3VdbeChangeP3(v, 2, flags);
  65915. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  65916. #endif
  65917. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  65918. ** parameter of the other to pTab->tnum. */
  65919. sqlite3VdbeChangeToNoop(v, 4 - flags);
  65920. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  65921. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  65922. /* Configure the number of columns. Configure the cursor to
  65923. ** think that the table has one more column than it really
  65924. ** does. An OP_Column to retrieve this imaginary column will
  65925. ** always return an SQL NULL. This is useful because it means
  65926. ** we can invoke OP_Column to fill in the vdbe cursors type
  65927. ** and offset cache without causing any IO.
  65928. */
  65929. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  65930. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  65931. if( !db->mallocFailed ){
  65932. pParse->nVar = 1;
  65933. pParse->nMem = 1;
  65934. pParse->nTab = 1;
  65935. sqlite3VdbeMakeReady(v, pParse);
  65936. }
  65937. }
  65938. pBlob->flags = flags;
  65939. pBlob->iCol = iCol;
  65940. pBlob->db = db;
  65941. sqlite3BtreeLeaveAll(db);
  65942. if( db->mallocFailed ){
  65943. goto blob_open_out;
  65944. }
  65945. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  65946. rc = blobSeekToRow(pBlob, iRow, &zErr);
  65947. } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
  65948. blob_open_out:
  65949. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  65950. *ppBlob = (sqlite3_blob *)pBlob;
  65951. }else{
  65952. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  65953. sqlite3DbFree(db, pBlob);
  65954. }
  65955. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  65956. sqlite3DbFree(db, zErr);
  65957. sqlite3StackFree(db, pParse);
  65958. rc = sqlite3ApiExit(db, rc);
  65959. sqlite3_mutex_leave(db->mutex);
  65960. return rc;
  65961. }
  65962. /*
  65963. ** Close a blob handle that was previously created using
  65964. ** sqlite3_blob_open().
  65965. */
  65966. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  65967. Incrblob *p = (Incrblob *)pBlob;
  65968. int rc;
  65969. sqlite3 *db;
  65970. if( p ){
  65971. db = p->db;
  65972. sqlite3_mutex_enter(db->mutex);
  65973. rc = sqlite3_finalize(p->pStmt);
  65974. sqlite3DbFree(db, p);
  65975. sqlite3_mutex_leave(db->mutex);
  65976. }else{
  65977. rc = SQLITE_OK;
  65978. }
  65979. return rc;
  65980. }
  65981. /*
  65982. ** Perform a read or write operation on a blob
  65983. */
  65984. static int blobReadWrite(
  65985. sqlite3_blob *pBlob,
  65986. void *z,
  65987. int n,
  65988. int iOffset,
  65989. int (*xCall)(BtCursor*, u32, u32, void*)
  65990. ){
  65991. int rc;
  65992. Incrblob *p = (Incrblob *)pBlob;
  65993. Vdbe *v;
  65994. sqlite3 *db;
  65995. if( p==0 ) return SQLITE_MISUSE_BKPT;
  65996. db = p->db;
  65997. sqlite3_mutex_enter(db->mutex);
  65998. v = (Vdbe*)p->pStmt;
  65999. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  66000. /* Request is out of range. Return a transient error. */
  66001. rc = SQLITE_ERROR;
  66002. sqlite3Error(db, SQLITE_ERROR, 0);
  66003. }else if( v==0 ){
  66004. /* If there is no statement handle, then the blob-handle has
  66005. ** already been invalidated. Return SQLITE_ABORT in this case.
  66006. */
  66007. rc = SQLITE_ABORT;
  66008. }else{
  66009. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  66010. ** returned, clean-up the statement handle.
  66011. */
  66012. assert( db == v->db );
  66013. sqlite3BtreeEnterCursor(p->pCsr);
  66014. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  66015. sqlite3BtreeLeaveCursor(p->pCsr);
  66016. if( rc==SQLITE_ABORT ){
  66017. sqlite3VdbeFinalize(v);
  66018. p->pStmt = 0;
  66019. }else{
  66020. db->errCode = rc;
  66021. v->rc = rc;
  66022. }
  66023. }
  66024. rc = sqlite3ApiExit(db, rc);
  66025. sqlite3_mutex_leave(db->mutex);
  66026. return rc;
  66027. }
  66028. /*
  66029. ** Read data from a blob handle.
  66030. */
  66031. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  66032. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  66033. }
  66034. /*
  66035. ** Write data to a blob handle.
  66036. */
  66037. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  66038. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  66039. }
  66040. /*
  66041. ** Query a blob handle for the size of the data.
  66042. **
  66043. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  66044. ** so no mutex is required for access.
  66045. */
  66046. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  66047. Incrblob *p = (Incrblob *)pBlob;
  66048. return (p && p->pStmt) ? p->nByte : 0;
  66049. }
  66050. /*
  66051. ** Move an existing blob handle to point to a different row of the same
  66052. ** database table.
  66053. **
  66054. ** If an error occurs, or if the specified row does not exist or does not
  66055. ** contain a blob or text value, then an error code is returned and the
  66056. ** database handle error code and message set. If this happens, then all
  66057. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  66058. ** immediately return SQLITE_ABORT.
  66059. */
  66060. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  66061. int rc;
  66062. Incrblob *p = (Incrblob *)pBlob;
  66063. sqlite3 *db;
  66064. if( p==0 ) return SQLITE_MISUSE_BKPT;
  66065. db = p->db;
  66066. sqlite3_mutex_enter(db->mutex);
  66067. if( p->pStmt==0 ){
  66068. /* If there is no statement handle, then the blob-handle has
  66069. ** already been invalidated. Return SQLITE_ABORT in this case.
  66070. */
  66071. rc = SQLITE_ABORT;
  66072. }else{
  66073. char *zErr;
  66074. rc = blobSeekToRow(p, iRow, &zErr);
  66075. if( rc!=SQLITE_OK ){
  66076. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  66077. sqlite3DbFree(db, zErr);
  66078. }
  66079. assert( rc!=SQLITE_SCHEMA );
  66080. }
  66081. rc = sqlite3ApiExit(db, rc);
  66082. assert( rc==SQLITE_OK || p->pStmt==0 );
  66083. sqlite3_mutex_leave(db->mutex);
  66084. return rc;
  66085. }
  66086. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  66087. /************** End of vdbeblob.c ********************************************/
  66088. /************** Begin file vdbesort.c ****************************************/
  66089. /*
  66090. ** 2011 July 9
  66091. **
  66092. ** The author disclaims copyright to this source code. In place of
  66093. ** a legal notice, here is a blessing:
  66094. **
  66095. ** May you do good and not evil.
  66096. ** May you find forgiveness for yourself and forgive others.
  66097. ** May you share freely, never taking more than you give.
  66098. **
  66099. *************************************************************************
  66100. ** This file contains code for the VdbeSorter object, used in concert with
  66101. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  66102. ** example, by CREATE INDEX statements on tables too large to fit in main
  66103. ** memory).
  66104. */
  66105. #ifndef SQLITE_OMIT_MERGE_SORT
  66106. typedef struct VdbeSorterIter VdbeSorterIter;
  66107. typedef struct SorterRecord SorterRecord;
  66108. typedef struct FileWriter FileWriter;
  66109. /*
  66110. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  66111. **
  66112. ** As keys are added to the sorter, they are written to disk in a series
  66113. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  66114. ** the same as the cache-size allowed for temporary databases. In order
  66115. ** to allow the caller to extract keys from the sorter in sorted order,
  66116. ** all PMAs currently stored on disk must be merged together. This comment
  66117. ** describes the data structure used to do so. The structure supports
  66118. ** merging any number of arrays in a single pass with no redundant comparison
  66119. ** operations.
  66120. **
  66121. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  66122. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  66123. ** the purposes of the paragraphs below, we assume that the array is actually
  66124. ** N elements in size, where N is the smallest power of 2 greater to or equal
  66125. ** to the number of iterators being merged. The extra aIter[] elements are
  66126. ** treated as if they are empty (always at EOF).
  66127. **
  66128. ** The aTree[] array is also N elements in size. The value of N is stored in
  66129. ** the VdbeSorter.nTree variable.
  66130. **
  66131. ** The final (N/2) elements of aTree[] contain the results of comparing
  66132. ** pairs of iterator keys together. Element i contains the result of
  66133. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  66134. ** aTree element is set to the index of it.
  66135. **
  66136. ** For the purposes of this comparison, EOF is considered greater than any
  66137. ** other key value. If the keys are equal (only possible with two EOF
  66138. ** values), it doesn't matter which index is stored.
  66139. **
  66140. ** The (N/4) elements of aTree[] that preceed the final (N/2) described
  66141. ** above contains the index of the smallest of each block of 4 iterators.
  66142. ** And so on. So that aTree[1] contains the index of the iterator that
  66143. ** currently points to the smallest key value. aTree[0] is unused.
  66144. **
  66145. ** Example:
  66146. **
  66147. ** aIter[0] -> Banana
  66148. ** aIter[1] -> Feijoa
  66149. ** aIter[2] -> Elderberry
  66150. ** aIter[3] -> Currant
  66151. ** aIter[4] -> Grapefruit
  66152. ** aIter[5] -> Apple
  66153. ** aIter[6] -> Durian
  66154. ** aIter[7] -> EOF
  66155. **
  66156. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  66157. **
  66158. ** The current element is "Apple" (the value of the key indicated by
  66159. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  66160. ** be advanced to the next key in its segment. Say the next key is
  66161. ** "Eggplant":
  66162. **
  66163. ** aIter[5] -> Eggplant
  66164. **
  66165. ** The contents of aTree[] are updated first by comparing the new iterator
  66166. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  66167. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  66168. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  66169. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  66170. ** so the value written into element 1 of the array is 0. As follows:
  66171. **
  66172. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  66173. **
  66174. ** In other words, each time we advance to the next sorter element, log2(N)
  66175. ** key comparison operations are required, where N is the number of segments
  66176. ** being merged (rounded up to the next power of 2).
  66177. */
  66178. struct VdbeSorter {
  66179. i64 iWriteOff; /* Current write offset within file pTemp1 */
  66180. i64 iReadOff; /* Current read offset within file pTemp1 */
  66181. int nInMemory; /* Current size of pRecord list as PMA */
  66182. int nTree; /* Used size of aTree/aIter (power of 2) */
  66183. int nPMA; /* Number of PMAs stored in pTemp1 */
  66184. int mnPmaSize; /* Minimum PMA size, in bytes */
  66185. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  66186. VdbeSorterIter *aIter; /* Array of iterators to merge */
  66187. int *aTree; /* Current state of incremental merge */
  66188. sqlite3_file *pTemp1; /* PMA file 1 */
  66189. SorterRecord *pRecord; /* Head of in-memory record list */
  66190. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  66191. };
  66192. /*
  66193. ** The following type is an iterator for a PMA. It caches the current key in
  66194. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  66195. */
  66196. struct VdbeSorterIter {
  66197. i64 iReadOff; /* Current read offset */
  66198. i64 iEof; /* 1 byte past EOF for this iterator */
  66199. int nAlloc; /* Bytes of space at aAlloc */
  66200. int nKey; /* Number of bytes in key */
  66201. sqlite3_file *pFile; /* File iterator is reading from */
  66202. u8 *aAlloc; /* Allocated space */
  66203. u8 *aKey; /* Pointer to current key */
  66204. u8 *aBuffer; /* Current read buffer */
  66205. int nBuffer; /* Size of read buffer in bytes */
  66206. };
  66207. /*
  66208. ** An instance of this structure is used to organize the stream of records
  66209. ** being written to files by the merge-sort code into aligned, page-sized
  66210. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  66211. ** faster on many operating systems.
  66212. */
  66213. struct FileWriter {
  66214. int eFWErr; /* Non-zero if in an error state */
  66215. u8 *aBuffer; /* Pointer to write buffer */
  66216. int nBuffer; /* Size of write buffer in bytes */
  66217. int iBufStart; /* First byte of buffer to write */
  66218. int iBufEnd; /* Last byte of buffer to write */
  66219. i64 iWriteOff; /* Offset of start of buffer in file */
  66220. sqlite3_file *pFile; /* File to write to */
  66221. };
  66222. /*
  66223. ** A structure to store a single record. All in-memory records are connected
  66224. ** together into a linked list headed at VdbeSorter.pRecord using the
  66225. ** SorterRecord.pNext pointer.
  66226. */
  66227. struct SorterRecord {
  66228. void *pVal;
  66229. int nVal;
  66230. SorterRecord *pNext;
  66231. };
  66232. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  66233. #define SORTER_MIN_WORKING 10
  66234. /* Maximum number of segments to merge in a single pass. */
  66235. #define SORTER_MAX_MERGE_COUNT 16
  66236. /*
  66237. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  66238. ** argument. All structure fields are set to zero before returning.
  66239. */
  66240. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  66241. sqlite3DbFree(db, pIter->aAlloc);
  66242. sqlite3DbFree(db, pIter->aBuffer);
  66243. memset(pIter, 0, sizeof(VdbeSorterIter));
  66244. }
  66245. /*
  66246. ** Read nByte bytes of data from the stream of data iterated by object p.
  66247. ** If successful, set *ppOut to point to a buffer containing the data
  66248. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  66249. ** error code.
  66250. **
  66251. ** The buffer indicated by *ppOut may only be considered valid until the
  66252. ** next call to this function.
  66253. */
  66254. static int vdbeSorterIterRead(
  66255. sqlite3 *db, /* Database handle (for malloc) */
  66256. VdbeSorterIter *p, /* Iterator */
  66257. int nByte, /* Bytes of data to read */
  66258. u8 **ppOut /* OUT: Pointer to buffer containing data */
  66259. ){
  66260. int iBuf; /* Offset within buffer to read from */
  66261. int nAvail; /* Bytes of data available in buffer */
  66262. assert( p->aBuffer );
  66263. /* If there is no more data to be read from the buffer, read the next
  66264. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  66265. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  66266. iBuf = p->iReadOff % p->nBuffer;
  66267. if( iBuf==0 ){
  66268. int nRead; /* Bytes to read from disk */
  66269. int rc; /* sqlite3OsRead() return code */
  66270. /* Determine how many bytes of data to read. */
  66271. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  66272. nRead = p->nBuffer;
  66273. }else{
  66274. nRead = (int)(p->iEof - p->iReadOff);
  66275. }
  66276. assert( nRead>0 );
  66277. /* Read data from the file. Return early if an error occurs. */
  66278. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  66279. assert( rc!=SQLITE_IOERR_SHORT_READ );
  66280. if( rc!=SQLITE_OK ) return rc;
  66281. }
  66282. nAvail = p->nBuffer - iBuf;
  66283. if( nByte<=nAvail ){
  66284. /* The requested data is available in the in-memory buffer. In this
  66285. ** case there is no need to make a copy of the data, just return a
  66286. ** pointer into the buffer to the caller. */
  66287. *ppOut = &p->aBuffer[iBuf];
  66288. p->iReadOff += nByte;
  66289. }else{
  66290. /* The requested data is not all available in the in-memory buffer.
  66291. ** In this case, allocate space at p->aAlloc[] to copy the requested
  66292. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  66293. int nRem; /* Bytes remaining to copy */
  66294. /* Extend the p->aAlloc[] allocation if required. */
  66295. if( p->nAlloc<nByte ){
  66296. int nNew = p->nAlloc*2;
  66297. while( nByte>nNew ) nNew = nNew*2;
  66298. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  66299. if( !p->aAlloc ) return SQLITE_NOMEM;
  66300. p->nAlloc = nNew;
  66301. }
  66302. /* Copy as much data as is available in the buffer into the start of
  66303. ** p->aAlloc[]. */
  66304. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  66305. p->iReadOff += nAvail;
  66306. nRem = nByte - nAvail;
  66307. /* The following loop copies up to p->nBuffer bytes per iteration into
  66308. ** the p->aAlloc[] buffer. */
  66309. while( nRem>0 ){
  66310. int rc; /* vdbeSorterIterRead() return code */
  66311. int nCopy; /* Number of bytes to copy */
  66312. u8 *aNext; /* Pointer to buffer to copy data from */
  66313. nCopy = nRem;
  66314. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  66315. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  66316. if( rc!=SQLITE_OK ) return rc;
  66317. assert( aNext!=p->aAlloc );
  66318. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  66319. nRem -= nCopy;
  66320. }
  66321. *ppOut = p->aAlloc;
  66322. }
  66323. return SQLITE_OK;
  66324. }
  66325. /*
  66326. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  66327. ** the value read.
  66328. */
  66329. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  66330. int iBuf;
  66331. iBuf = p->iReadOff % p->nBuffer;
  66332. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  66333. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  66334. }else{
  66335. u8 aVarint[16], *a;
  66336. int i = 0, rc;
  66337. do{
  66338. rc = vdbeSorterIterRead(db, p, 1, &a);
  66339. if( rc ) return rc;
  66340. aVarint[(i++)&0xf] = a[0];
  66341. }while( (a[0]&0x80)!=0 );
  66342. sqlite3GetVarint(aVarint, pnOut);
  66343. }
  66344. return SQLITE_OK;
  66345. }
  66346. /*
  66347. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  66348. ** no error occurs, or an SQLite error code if one does.
  66349. */
  66350. static int vdbeSorterIterNext(
  66351. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  66352. VdbeSorterIter *pIter /* Iterator to advance */
  66353. ){
  66354. int rc; /* Return Code */
  66355. u64 nRec = 0; /* Size of record in bytes */
  66356. if( pIter->iReadOff>=pIter->iEof ){
  66357. /* This is an EOF condition */
  66358. vdbeSorterIterZero(db, pIter);
  66359. return SQLITE_OK;
  66360. }
  66361. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  66362. if( rc==SQLITE_OK ){
  66363. pIter->nKey = (int)nRec;
  66364. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  66365. }
  66366. return rc;
  66367. }
  66368. /*
  66369. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  66370. ** starting at offset iStart and ending at offset iEof-1. This function
  66371. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  66372. ** PMA is empty).
  66373. */
  66374. static int vdbeSorterIterInit(
  66375. sqlite3 *db, /* Database handle */
  66376. const VdbeSorter *pSorter, /* Sorter object */
  66377. i64 iStart, /* Start offset in pFile */
  66378. VdbeSorterIter *pIter, /* Iterator to populate */
  66379. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  66380. ){
  66381. int rc = SQLITE_OK;
  66382. int nBuf;
  66383. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  66384. assert( pSorter->iWriteOff>iStart );
  66385. assert( pIter->aAlloc==0 );
  66386. assert( pIter->aBuffer==0 );
  66387. pIter->pFile = pSorter->pTemp1;
  66388. pIter->iReadOff = iStart;
  66389. pIter->nAlloc = 128;
  66390. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  66391. pIter->nBuffer = nBuf;
  66392. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  66393. if( !pIter->aBuffer ){
  66394. rc = SQLITE_NOMEM;
  66395. }else{
  66396. int iBuf;
  66397. iBuf = iStart % nBuf;
  66398. if( iBuf ){
  66399. int nRead = nBuf - iBuf;
  66400. if( (iStart + nRead) > pSorter->iWriteOff ){
  66401. nRead = (int)(pSorter->iWriteOff - iStart);
  66402. }
  66403. rc = sqlite3OsRead(
  66404. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  66405. );
  66406. assert( rc!=SQLITE_IOERR_SHORT_READ );
  66407. }
  66408. if( rc==SQLITE_OK ){
  66409. u64 nByte; /* Size of PMA in bytes */
  66410. pIter->iEof = pSorter->iWriteOff;
  66411. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  66412. pIter->iEof = pIter->iReadOff + nByte;
  66413. *pnByte += nByte;
  66414. }
  66415. }
  66416. if( rc==SQLITE_OK ){
  66417. rc = vdbeSorterIterNext(db, pIter);
  66418. }
  66419. return rc;
  66420. }
  66421. /*
  66422. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  66423. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  66424. ** used by the comparison. If an error occurs, return an SQLite error code.
  66425. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  66426. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  66427. **
  66428. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  66429. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  66430. ** is true and key1 contains even a single NULL value, it is considered to
  66431. ** be less than key2. Even if key2 also contains NULL values.
  66432. **
  66433. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  66434. ** has been allocated and contains an unpacked record that is used as key2.
  66435. */
  66436. static void vdbeSorterCompare(
  66437. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  66438. int bOmitRowid, /* Ignore rowid field at end of keys */
  66439. const void *pKey1, int nKey1, /* Left side of comparison */
  66440. const void *pKey2, int nKey2, /* Right side of comparison */
  66441. int *pRes /* OUT: Result of comparison */
  66442. ){
  66443. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  66444. VdbeSorter *pSorter = pCsr->pSorter;
  66445. UnpackedRecord *r2 = pSorter->pUnpacked;
  66446. int i;
  66447. if( pKey2 ){
  66448. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  66449. }
  66450. if( bOmitRowid ){
  66451. r2->nField = pKeyInfo->nField;
  66452. assert( r2->nField>0 );
  66453. for(i=0; i<r2->nField; i++){
  66454. if( r2->aMem[i].flags & MEM_Null ){
  66455. *pRes = -1;
  66456. return;
  66457. }
  66458. }
  66459. r2->flags |= UNPACKED_PREFIX_MATCH;
  66460. }
  66461. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  66462. }
  66463. /*
  66464. ** This function is called to compare two iterator keys when merging
  66465. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  66466. ** value to recalculate.
  66467. */
  66468. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  66469. VdbeSorter *pSorter = pCsr->pSorter;
  66470. int i1;
  66471. int i2;
  66472. int iRes;
  66473. VdbeSorterIter *p1;
  66474. VdbeSorterIter *p2;
  66475. assert( iOut<pSorter->nTree && iOut>0 );
  66476. if( iOut>=(pSorter->nTree/2) ){
  66477. i1 = (iOut - pSorter->nTree/2) * 2;
  66478. i2 = i1 + 1;
  66479. }else{
  66480. i1 = pSorter->aTree[iOut*2];
  66481. i2 = pSorter->aTree[iOut*2+1];
  66482. }
  66483. p1 = &pSorter->aIter[i1];
  66484. p2 = &pSorter->aIter[i2];
  66485. if( p1->pFile==0 ){
  66486. iRes = i2;
  66487. }else if( p2->pFile==0 ){
  66488. iRes = i1;
  66489. }else{
  66490. int res;
  66491. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  66492. vdbeSorterCompare(
  66493. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  66494. );
  66495. if( res<=0 ){
  66496. iRes = i1;
  66497. }else{
  66498. iRes = i2;
  66499. }
  66500. }
  66501. pSorter->aTree[iOut] = iRes;
  66502. return SQLITE_OK;
  66503. }
  66504. /*
  66505. ** Initialize the temporary index cursor just opened as a sorter cursor.
  66506. */
  66507. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  66508. int pgsz; /* Page size of main database */
  66509. int mxCache; /* Cache size */
  66510. VdbeSorter *pSorter; /* The new sorter */
  66511. char *d; /* Dummy */
  66512. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  66513. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  66514. if( pSorter==0 ){
  66515. return SQLITE_NOMEM;
  66516. }
  66517. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  66518. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  66519. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  66520. if( !sqlite3TempInMemory(db) ){
  66521. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  66522. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  66523. mxCache = db->aDb[0].pSchema->cache_size;
  66524. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  66525. pSorter->mxPmaSize = mxCache * pgsz;
  66526. }
  66527. return SQLITE_OK;
  66528. }
  66529. /*
  66530. ** Free the list of sorted records starting at pRecord.
  66531. */
  66532. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  66533. SorterRecord *p;
  66534. SorterRecord *pNext;
  66535. for(p=pRecord; p; p=pNext){
  66536. pNext = p->pNext;
  66537. sqlite3DbFree(db, p);
  66538. }
  66539. }
  66540. /*
  66541. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  66542. */
  66543. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  66544. VdbeSorter *pSorter = pCsr->pSorter;
  66545. if( pSorter ){
  66546. if( pSorter->aIter ){
  66547. int i;
  66548. for(i=0; i<pSorter->nTree; i++){
  66549. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  66550. }
  66551. sqlite3DbFree(db, pSorter->aIter);
  66552. }
  66553. if( pSorter->pTemp1 ){
  66554. sqlite3OsCloseFree(pSorter->pTemp1);
  66555. }
  66556. vdbeSorterRecordFree(db, pSorter->pRecord);
  66557. sqlite3DbFree(db, pSorter->pUnpacked);
  66558. sqlite3DbFree(db, pSorter);
  66559. pCsr->pSorter = 0;
  66560. }
  66561. }
  66562. /*
  66563. ** Allocate space for a file-handle and open a temporary file. If successful,
  66564. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  66565. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  66566. */
  66567. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  66568. int dummy;
  66569. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  66570. SQLITE_OPEN_TEMP_JOURNAL |
  66571. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  66572. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  66573. );
  66574. }
  66575. /*
  66576. ** Merge the two sorted lists p1 and p2 into a single list.
  66577. ** Set *ppOut to the head of the new list.
  66578. */
  66579. static void vdbeSorterMerge(
  66580. const VdbeCursor *pCsr, /* For pKeyInfo */
  66581. SorterRecord *p1, /* First list to merge */
  66582. SorterRecord *p2, /* Second list to merge */
  66583. SorterRecord **ppOut /* OUT: Head of merged list */
  66584. ){
  66585. SorterRecord *pFinal = 0;
  66586. SorterRecord **pp = &pFinal;
  66587. void *pVal2 = p2 ? p2->pVal : 0;
  66588. while( p1 && p2 ){
  66589. int res;
  66590. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  66591. if( res<=0 ){
  66592. *pp = p1;
  66593. pp = &p1->pNext;
  66594. p1 = p1->pNext;
  66595. pVal2 = 0;
  66596. }else{
  66597. *pp = p2;
  66598. pp = &p2->pNext;
  66599. p2 = p2->pNext;
  66600. if( p2==0 ) break;
  66601. pVal2 = p2->pVal;
  66602. }
  66603. }
  66604. *pp = p1 ? p1 : p2;
  66605. *ppOut = pFinal;
  66606. }
  66607. /*
  66608. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  66609. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  66610. ** occurs.
  66611. */
  66612. static int vdbeSorterSort(const VdbeCursor *pCsr){
  66613. int i;
  66614. SorterRecord **aSlot;
  66615. SorterRecord *p;
  66616. VdbeSorter *pSorter = pCsr->pSorter;
  66617. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  66618. if( !aSlot ){
  66619. return SQLITE_NOMEM;
  66620. }
  66621. p = pSorter->pRecord;
  66622. while( p ){
  66623. SorterRecord *pNext = p->pNext;
  66624. p->pNext = 0;
  66625. for(i=0; aSlot[i]; i++){
  66626. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  66627. aSlot[i] = 0;
  66628. }
  66629. aSlot[i] = p;
  66630. p = pNext;
  66631. }
  66632. p = 0;
  66633. for(i=0; i<64; i++){
  66634. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  66635. }
  66636. pSorter->pRecord = p;
  66637. sqlite3_free(aSlot);
  66638. return SQLITE_OK;
  66639. }
  66640. /*
  66641. ** Initialize a file-writer object.
  66642. */
  66643. static void fileWriterInit(
  66644. sqlite3 *db, /* Database (for malloc) */
  66645. sqlite3_file *pFile, /* File to write to */
  66646. FileWriter *p, /* Object to populate */
  66647. i64 iStart /* Offset of pFile to begin writing at */
  66648. ){
  66649. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  66650. memset(p, 0, sizeof(FileWriter));
  66651. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  66652. if( !p->aBuffer ){
  66653. p->eFWErr = SQLITE_NOMEM;
  66654. }else{
  66655. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  66656. p->iWriteOff = iStart - p->iBufStart;
  66657. p->nBuffer = nBuf;
  66658. p->pFile = pFile;
  66659. }
  66660. }
  66661. /*
  66662. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  66663. ** if successful, or an SQLite error code if an error occurs.
  66664. */
  66665. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  66666. int nRem = nData;
  66667. while( nRem>0 && p->eFWErr==0 ){
  66668. int nCopy = nRem;
  66669. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  66670. nCopy = p->nBuffer - p->iBufEnd;
  66671. }
  66672. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  66673. p->iBufEnd += nCopy;
  66674. if( p->iBufEnd==p->nBuffer ){
  66675. p->eFWErr = sqlite3OsWrite(p->pFile,
  66676. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  66677. p->iWriteOff + p->iBufStart
  66678. );
  66679. p->iBufStart = p->iBufEnd = 0;
  66680. p->iWriteOff += p->nBuffer;
  66681. }
  66682. assert( p->iBufEnd<p->nBuffer );
  66683. nRem -= nCopy;
  66684. }
  66685. }
  66686. /*
  66687. ** Flush any buffered data to disk and clean up the file-writer object.
  66688. ** The results of using the file-writer after this call are undefined.
  66689. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  66690. ** required. Otherwise, return an SQLite error code.
  66691. **
  66692. ** Before returning, set *piEof to the offset immediately following the
  66693. ** last byte written to the file.
  66694. */
  66695. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  66696. int rc;
  66697. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  66698. p->eFWErr = sqlite3OsWrite(p->pFile,
  66699. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  66700. p->iWriteOff + p->iBufStart
  66701. );
  66702. }
  66703. *piEof = (p->iWriteOff + p->iBufEnd);
  66704. sqlite3DbFree(db, p->aBuffer);
  66705. rc = p->eFWErr;
  66706. memset(p, 0, sizeof(FileWriter));
  66707. return rc;
  66708. }
  66709. /*
  66710. ** Write value iVal encoded as a varint to the file-write object. Return
  66711. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  66712. */
  66713. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  66714. int nByte;
  66715. u8 aByte[10];
  66716. nByte = sqlite3PutVarint(aByte, iVal);
  66717. fileWriterWrite(p, aByte, nByte);
  66718. }
  66719. /*
  66720. ** Write the current contents of the in-memory linked-list to a PMA. Return
  66721. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  66722. **
  66723. ** The format of a PMA is:
  66724. **
  66725. ** * A varint. This varint contains the total number of bytes of content
  66726. ** in the PMA (not including the varint itself).
  66727. **
  66728. ** * One or more records packed end-to-end in order of ascending keys.
  66729. ** Each record consists of a varint followed by a blob of data (the
  66730. ** key). The varint is the number of bytes in the blob of data.
  66731. */
  66732. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  66733. int rc = SQLITE_OK; /* Return code */
  66734. VdbeSorter *pSorter = pCsr->pSorter;
  66735. FileWriter writer;
  66736. memset(&writer, 0, sizeof(FileWriter));
  66737. if( pSorter->nInMemory==0 ){
  66738. assert( pSorter->pRecord==0 );
  66739. return rc;
  66740. }
  66741. rc = vdbeSorterSort(pCsr);
  66742. /* If the first temporary PMA file has not been opened, open it now. */
  66743. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  66744. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  66745. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  66746. assert( pSorter->iWriteOff==0 );
  66747. assert( pSorter->nPMA==0 );
  66748. }
  66749. if( rc==SQLITE_OK ){
  66750. SorterRecord *p;
  66751. SorterRecord *pNext = 0;
  66752. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  66753. pSorter->nPMA++;
  66754. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  66755. for(p=pSorter->pRecord; p; p=pNext){
  66756. pNext = p->pNext;
  66757. fileWriterWriteVarint(&writer, p->nVal);
  66758. fileWriterWrite(&writer, p->pVal, p->nVal);
  66759. sqlite3DbFree(db, p);
  66760. }
  66761. pSorter->pRecord = p;
  66762. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  66763. }
  66764. return rc;
  66765. }
  66766. /*
  66767. ** Add a record to the sorter.
  66768. */
  66769. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  66770. sqlite3 *db, /* Database handle */
  66771. const VdbeCursor *pCsr, /* Sorter cursor */
  66772. Mem *pVal /* Memory cell containing record */
  66773. ){
  66774. VdbeSorter *pSorter = pCsr->pSorter;
  66775. int rc = SQLITE_OK; /* Return Code */
  66776. SorterRecord *pNew; /* New list element */
  66777. assert( pSorter );
  66778. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  66779. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  66780. if( pNew==0 ){
  66781. rc = SQLITE_NOMEM;
  66782. }else{
  66783. pNew->pVal = (void *)&pNew[1];
  66784. memcpy(pNew->pVal, pVal->z, pVal->n);
  66785. pNew->nVal = pVal->n;
  66786. pNew->pNext = pSorter->pRecord;
  66787. pSorter->pRecord = pNew;
  66788. }
  66789. /* See if the contents of the sorter should now be written out. They
  66790. ** are written out when either of the following are true:
  66791. **
  66792. ** * The total memory allocated for the in-memory list is greater
  66793. ** than (page-size * cache-size), or
  66794. **
  66795. ** * The total memory allocated for the in-memory list is greater
  66796. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  66797. */
  66798. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  66799. (pSorter->nInMemory>pSorter->mxPmaSize)
  66800. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  66801. )){
  66802. #ifdef SQLITE_DEBUG
  66803. i64 nExpect = pSorter->iWriteOff
  66804. + sqlite3VarintLen(pSorter->nInMemory)
  66805. + pSorter->nInMemory;
  66806. #endif
  66807. rc = vdbeSorterListToPMA(db, pCsr);
  66808. pSorter->nInMemory = 0;
  66809. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  66810. }
  66811. return rc;
  66812. }
  66813. /*
  66814. ** Helper function for sqlite3VdbeSorterRewind().
  66815. */
  66816. static int vdbeSorterInitMerge(
  66817. sqlite3 *db, /* Database handle */
  66818. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  66819. i64 *pnByte /* Sum of bytes in all opened PMAs */
  66820. ){
  66821. VdbeSorter *pSorter = pCsr->pSorter;
  66822. int rc = SQLITE_OK; /* Return code */
  66823. int i; /* Used to iterator through aIter[] */
  66824. i64 nByte = 0; /* Total bytes in all opened PMAs */
  66825. /* Initialize the iterators. */
  66826. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  66827. VdbeSorterIter *pIter = &pSorter->aIter[i];
  66828. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  66829. pSorter->iReadOff = pIter->iEof;
  66830. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  66831. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  66832. }
  66833. /* Initialize the aTree[] array. */
  66834. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  66835. rc = vdbeSorterDoCompare(pCsr, i);
  66836. }
  66837. *pnByte = nByte;
  66838. return rc;
  66839. }
  66840. /*
  66841. ** Once the sorter has been populated, this function is called to prepare
  66842. ** for iterating through its contents in sorted order.
  66843. */
  66844. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  66845. VdbeSorter *pSorter = pCsr->pSorter;
  66846. int rc; /* Return code */
  66847. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  66848. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  66849. int nIter; /* Number of iterators used */
  66850. int nByte; /* Bytes of space required for aIter/aTree */
  66851. int N = 2; /* Power of 2 >= nIter */
  66852. assert( pSorter );
  66853. /* If no data has been written to disk, then do not do so now. Instead,
  66854. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  66855. ** from the in-memory list. */
  66856. if( pSorter->nPMA==0 ){
  66857. *pbEof = !pSorter->pRecord;
  66858. assert( pSorter->aTree==0 );
  66859. return vdbeSorterSort(pCsr);
  66860. }
  66861. /* Write the current in-memory list to a PMA. */
  66862. rc = vdbeSorterListToPMA(db, pCsr);
  66863. if( rc!=SQLITE_OK ) return rc;
  66864. /* Allocate space for aIter[] and aTree[]. */
  66865. nIter = pSorter->nPMA;
  66866. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  66867. assert( nIter>0 );
  66868. while( N<nIter ) N += N;
  66869. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  66870. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  66871. if( !pSorter->aIter ) return SQLITE_NOMEM;
  66872. pSorter->aTree = (int *)&pSorter->aIter[N];
  66873. pSorter->nTree = N;
  66874. do {
  66875. int iNew; /* Index of new, merged, PMA */
  66876. for(iNew=0;
  66877. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  66878. iNew++
  66879. ){
  66880. int rc2; /* Return code from fileWriterFinish() */
  66881. FileWriter writer; /* Object used to write to disk */
  66882. i64 nWrite; /* Number of bytes in new PMA */
  66883. memset(&writer, 0, sizeof(FileWriter));
  66884. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  66885. ** initialize an iterator for each of them and break out of the loop.
  66886. ** These iterators will be incrementally merged as the VDBE layer calls
  66887. ** sqlite3VdbeSorterNext().
  66888. **
  66889. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  66890. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  66891. ** are merged into a single PMA that is written to file pTemp2.
  66892. */
  66893. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  66894. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  66895. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  66896. break;
  66897. }
  66898. /* Open the second temp file, if it is not already open. */
  66899. if( pTemp2==0 ){
  66900. assert( iWrite2==0 );
  66901. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  66902. }
  66903. if( rc==SQLITE_OK ){
  66904. int bEof = 0;
  66905. fileWriterInit(db, pTemp2, &writer, iWrite2);
  66906. fileWriterWriteVarint(&writer, nWrite);
  66907. while( rc==SQLITE_OK && bEof==0 ){
  66908. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  66909. assert( pIter->pFile );
  66910. fileWriterWriteVarint(&writer, pIter->nKey);
  66911. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  66912. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  66913. }
  66914. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  66915. if( rc==SQLITE_OK ) rc = rc2;
  66916. }
  66917. }
  66918. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  66919. break;
  66920. }else{
  66921. sqlite3_file *pTmp = pSorter->pTemp1;
  66922. pSorter->nPMA = iNew;
  66923. pSorter->pTemp1 = pTemp2;
  66924. pTemp2 = pTmp;
  66925. pSorter->iWriteOff = iWrite2;
  66926. pSorter->iReadOff = 0;
  66927. iWrite2 = 0;
  66928. }
  66929. }while( rc==SQLITE_OK );
  66930. if( pTemp2 ){
  66931. sqlite3OsCloseFree(pTemp2);
  66932. }
  66933. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  66934. return rc;
  66935. }
  66936. /*
  66937. ** Advance to the next element in the sorter.
  66938. */
  66939. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  66940. VdbeSorter *pSorter = pCsr->pSorter;
  66941. int rc; /* Return code */
  66942. if( pSorter->aTree ){
  66943. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  66944. int i; /* Index of aTree[] to recalculate */
  66945. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  66946. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  66947. rc = vdbeSorterDoCompare(pCsr, i);
  66948. }
  66949. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  66950. }else{
  66951. SorterRecord *pFree = pSorter->pRecord;
  66952. pSorter->pRecord = pFree->pNext;
  66953. pFree->pNext = 0;
  66954. vdbeSorterRecordFree(db, pFree);
  66955. *pbEof = !pSorter->pRecord;
  66956. rc = SQLITE_OK;
  66957. }
  66958. return rc;
  66959. }
  66960. /*
  66961. ** Return a pointer to a buffer owned by the sorter that contains the
  66962. ** current key.
  66963. */
  66964. static void *vdbeSorterRowkey(
  66965. const VdbeSorter *pSorter, /* Sorter object */
  66966. int *pnKey /* OUT: Size of current key in bytes */
  66967. ){
  66968. void *pKey;
  66969. if( pSorter->aTree ){
  66970. VdbeSorterIter *pIter;
  66971. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  66972. *pnKey = pIter->nKey;
  66973. pKey = pIter->aKey;
  66974. }else{
  66975. *pnKey = pSorter->pRecord->nVal;
  66976. pKey = pSorter->pRecord->pVal;
  66977. }
  66978. return pKey;
  66979. }
  66980. /*
  66981. ** Copy the current sorter key into the memory cell pOut.
  66982. */
  66983. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  66984. VdbeSorter *pSorter = pCsr->pSorter;
  66985. void *pKey; int nKey; /* Sorter key to copy into pOut */
  66986. pKey = vdbeSorterRowkey(pSorter, &nKey);
  66987. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  66988. return SQLITE_NOMEM;
  66989. }
  66990. pOut->n = nKey;
  66991. MemSetTypeFlag(pOut, MEM_Blob);
  66992. memcpy(pOut->z, pKey, nKey);
  66993. return SQLITE_OK;
  66994. }
  66995. /*
  66996. ** Compare the key in memory cell pVal with the key that the sorter cursor
  66997. ** passed as the first argument currently points to. For the purposes of
  66998. ** the comparison, ignore the rowid field at the end of each record.
  66999. **
  67000. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  67001. ** Otherwise, set *pRes to a negative, zero or positive value if the
  67002. ** key in pVal is smaller than, equal to or larger than the current sorter
  67003. ** key.
  67004. */
  67005. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  67006. const VdbeCursor *pCsr, /* Sorter cursor */
  67007. Mem *pVal, /* Value to compare to current sorter key */
  67008. int *pRes /* OUT: Result of comparison */
  67009. ){
  67010. VdbeSorter *pSorter = pCsr->pSorter;
  67011. void *pKey; int nKey; /* Sorter key to compare pVal with */
  67012. pKey = vdbeSorterRowkey(pSorter, &nKey);
  67013. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  67014. return SQLITE_OK;
  67015. }
  67016. #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
  67017. /************** End of vdbesort.c ********************************************/
  67018. /************** Begin file journal.c *****************************************/
  67019. /*
  67020. ** 2007 August 22
  67021. **
  67022. ** The author disclaims copyright to this source code. In place of
  67023. ** a legal notice, here is a blessing:
  67024. **
  67025. ** May you do good and not evil.
  67026. ** May you find forgiveness for yourself and forgive others.
  67027. ** May you share freely, never taking more than you give.
  67028. **
  67029. *************************************************************************
  67030. **
  67031. ** This file implements a special kind of sqlite3_file object used
  67032. ** by SQLite to create journal files if the atomic-write optimization
  67033. ** is enabled.
  67034. **
  67035. ** The distinctive characteristic of this sqlite3_file is that the
  67036. ** actual on disk file is created lazily. When the file is created,
  67037. ** the caller specifies a buffer size for an in-memory buffer to
  67038. ** be used to service read() and write() requests. The actual file
  67039. ** on disk is not created or populated until either:
  67040. **
  67041. ** 1) The in-memory representation grows too large for the allocated
  67042. ** buffer, or
  67043. ** 2) The sqlite3JournalCreate() function is called.
  67044. */
  67045. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  67046. /*
  67047. ** A JournalFile object is a subclass of sqlite3_file used by
  67048. ** as an open file handle for journal files.
  67049. */
  67050. struct JournalFile {
  67051. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  67052. int nBuf; /* Size of zBuf[] in bytes */
  67053. char *zBuf; /* Space to buffer journal writes */
  67054. int iSize; /* Amount of zBuf[] currently used */
  67055. int flags; /* xOpen flags */
  67056. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  67057. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  67058. const char *zJournal; /* Name of the journal file */
  67059. };
  67060. typedef struct JournalFile JournalFile;
  67061. /*
  67062. ** If it does not already exists, create and populate the on-disk file
  67063. ** for JournalFile p.
  67064. */
  67065. static int createFile(JournalFile *p){
  67066. int rc = SQLITE_OK;
  67067. if( !p->pReal ){
  67068. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  67069. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  67070. if( rc==SQLITE_OK ){
  67071. p->pReal = pReal;
  67072. if( p->iSize>0 ){
  67073. assert(p->iSize<=p->nBuf);
  67074. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  67075. }
  67076. }
  67077. }
  67078. return rc;
  67079. }
  67080. /*
  67081. ** Close the file.
  67082. */
  67083. static int jrnlClose(sqlite3_file *pJfd){
  67084. JournalFile *p = (JournalFile *)pJfd;
  67085. if( p->pReal ){
  67086. sqlite3OsClose(p->pReal);
  67087. }
  67088. sqlite3_free(p->zBuf);
  67089. return SQLITE_OK;
  67090. }
  67091. /*
  67092. ** Read data from the file.
  67093. */
  67094. static int jrnlRead(
  67095. sqlite3_file *pJfd, /* The journal file from which to read */
  67096. void *zBuf, /* Put the results here */
  67097. int iAmt, /* Number of bytes to read */
  67098. sqlite_int64 iOfst /* Begin reading at this offset */
  67099. ){
  67100. int rc = SQLITE_OK;
  67101. JournalFile *p = (JournalFile *)pJfd;
  67102. if( p->pReal ){
  67103. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  67104. }else if( (iAmt+iOfst)>p->iSize ){
  67105. rc = SQLITE_IOERR_SHORT_READ;
  67106. }else{
  67107. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  67108. }
  67109. return rc;
  67110. }
  67111. /*
  67112. ** Write data to the file.
  67113. */
  67114. static int jrnlWrite(
  67115. sqlite3_file *pJfd, /* The journal file into which to write */
  67116. const void *zBuf, /* Take data to be written from here */
  67117. int iAmt, /* Number of bytes to write */
  67118. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  67119. ){
  67120. int rc = SQLITE_OK;
  67121. JournalFile *p = (JournalFile *)pJfd;
  67122. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  67123. rc = createFile(p);
  67124. }
  67125. if( rc==SQLITE_OK ){
  67126. if( p->pReal ){
  67127. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  67128. }else{
  67129. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  67130. if( p->iSize<(iOfst+iAmt) ){
  67131. p->iSize = (iOfst+iAmt);
  67132. }
  67133. }
  67134. }
  67135. return rc;
  67136. }
  67137. /*
  67138. ** Truncate the file.
  67139. */
  67140. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  67141. int rc = SQLITE_OK;
  67142. JournalFile *p = (JournalFile *)pJfd;
  67143. if( p->pReal ){
  67144. rc = sqlite3OsTruncate(p->pReal, size);
  67145. }else if( size<p->iSize ){
  67146. p->iSize = size;
  67147. }
  67148. return rc;
  67149. }
  67150. /*
  67151. ** Sync the file.
  67152. */
  67153. static int jrnlSync(sqlite3_file *pJfd, int flags){
  67154. int rc;
  67155. JournalFile *p = (JournalFile *)pJfd;
  67156. if( p->pReal ){
  67157. rc = sqlite3OsSync(p->pReal, flags);
  67158. }else{
  67159. rc = SQLITE_OK;
  67160. }
  67161. return rc;
  67162. }
  67163. /*
  67164. ** Query the size of the file in bytes.
  67165. */
  67166. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  67167. int rc = SQLITE_OK;
  67168. JournalFile *p = (JournalFile *)pJfd;
  67169. if( p->pReal ){
  67170. rc = sqlite3OsFileSize(p->pReal, pSize);
  67171. }else{
  67172. *pSize = (sqlite_int64) p->iSize;
  67173. }
  67174. return rc;
  67175. }
  67176. /*
  67177. ** Table of methods for JournalFile sqlite3_file object.
  67178. */
  67179. static struct sqlite3_io_methods JournalFileMethods = {
  67180. 1, /* iVersion */
  67181. jrnlClose, /* xClose */
  67182. jrnlRead, /* xRead */
  67183. jrnlWrite, /* xWrite */
  67184. jrnlTruncate, /* xTruncate */
  67185. jrnlSync, /* xSync */
  67186. jrnlFileSize, /* xFileSize */
  67187. 0, /* xLock */
  67188. 0, /* xUnlock */
  67189. 0, /* xCheckReservedLock */
  67190. 0, /* xFileControl */
  67191. 0, /* xSectorSize */
  67192. 0, /* xDeviceCharacteristics */
  67193. 0, /* xShmMap */
  67194. 0, /* xShmLock */
  67195. 0, /* xShmBarrier */
  67196. 0 /* xShmUnmap */
  67197. };
  67198. /*
  67199. ** Open a journal file.
  67200. */
  67201. SQLITE_PRIVATE int sqlite3JournalOpen(
  67202. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  67203. const char *zName, /* Name of the journal file */
  67204. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  67205. int flags, /* Opening flags */
  67206. int nBuf /* Bytes buffered before opening the file */
  67207. ){
  67208. JournalFile *p = (JournalFile *)pJfd;
  67209. memset(p, 0, sqlite3JournalSize(pVfs));
  67210. if( nBuf>0 ){
  67211. p->zBuf = sqlite3MallocZero(nBuf);
  67212. if( !p->zBuf ){
  67213. return SQLITE_NOMEM;
  67214. }
  67215. }else{
  67216. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  67217. }
  67218. p->pMethod = &JournalFileMethods;
  67219. p->nBuf = nBuf;
  67220. p->flags = flags;
  67221. p->zJournal = zName;
  67222. p->pVfs = pVfs;
  67223. return SQLITE_OK;
  67224. }
  67225. /*
  67226. ** If the argument p points to a JournalFile structure, and the underlying
  67227. ** file has not yet been created, create it now.
  67228. */
  67229. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  67230. if( p->pMethods!=&JournalFileMethods ){
  67231. return SQLITE_OK;
  67232. }
  67233. return createFile((JournalFile *)p);
  67234. }
  67235. /*
  67236. ** The file-handle passed as the only argument is guaranteed to be an open
  67237. ** file. It may or may not be of class JournalFile. If the file is a
  67238. ** JournalFile, and the underlying file on disk has not yet been opened,
  67239. ** return 0. Otherwise, return 1.
  67240. */
  67241. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  67242. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  67243. }
  67244. /*
  67245. ** Return the number of bytes required to store a JournalFile that uses vfs
  67246. ** pVfs to create the underlying on-disk files.
  67247. */
  67248. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  67249. return (pVfs->szOsFile+sizeof(JournalFile));
  67250. }
  67251. #endif
  67252. /************** End of journal.c *********************************************/
  67253. /************** Begin file memjournal.c **************************************/
  67254. /*
  67255. ** 2008 October 7
  67256. **
  67257. ** The author disclaims copyright to this source code. In place of
  67258. ** a legal notice, here is a blessing:
  67259. **
  67260. ** May you do good and not evil.
  67261. ** May you find forgiveness for yourself and forgive others.
  67262. ** May you share freely, never taking more than you give.
  67263. **
  67264. *************************************************************************
  67265. **
  67266. ** This file contains code use to implement an in-memory rollback journal.
  67267. ** The in-memory rollback journal is used to journal transactions for
  67268. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  67269. */
  67270. /* Forward references to internal structures */
  67271. typedef struct MemJournal MemJournal;
  67272. typedef struct FilePoint FilePoint;
  67273. typedef struct FileChunk FileChunk;
  67274. /* Space to hold the rollback journal is allocated in increments of
  67275. ** this many bytes.
  67276. **
  67277. ** The size chosen is a little less than a power of two. That way,
  67278. ** the FileChunk object will have a size that almost exactly fills
  67279. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  67280. ** memory allocators.
  67281. */
  67282. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  67283. /* Macro to find the minimum of two numeric values.
  67284. */
  67285. #ifndef MIN
  67286. # define MIN(x,y) ((x)<(y)?(x):(y))
  67287. #endif
  67288. /*
  67289. ** The rollback journal is composed of a linked list of these structures.
  67290. */
  67291. struct FileChunk {
  67292. FileChunk *pNext; /* Next chunk in the journal */
  67293. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  67294. };
  67295. /*
  67296. ** An instance of this object serves as a cursor into the rollback journal.
  67297. ** The cursor can be either for reading or writing.
  67298. */
  67299. struct FilePoint {
  67300. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  67301. FileChunk *pChunk; /* Specific chunk into which cursor points */
  67302. };
  67303. /*
  67304. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  67305. ** is an instance of this class.
  67306. */
  67307. struct MemJournal {
  67308. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  67309. FileChunk *pFirst; /* Head of in-memory chunk-list */
  67310. FilePoint endpoint; /* Pointer to the end of the file */
  67311. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  67312. };
  67313. /*
  67314. ** Read data from the in-memory journal file. This is the implementation
  67315. ** of the sqlite3_vfs.xRead method.
  67316. */
  67317. static int memjrnlRead(
  67318. sqlite3_file *pJfd, /* The journal file from which to read */
  67319. void *zBuf, /* Put the results here */
  67320. int iAmt, /* Number of bytes to read */
  67321. sqlite_int64 iOfst /* Begin reading at this offset */
  67322. ){
  67323. MemJournal *p = (MemJournal *)pJfd;
  67324. u8 *zOut = zBuf;
  67325. int nRead = iAmt;
  67326. int iChunkOffset;
  67327. FileChunk *pChunk;
  67328. /* SQLite never tries to read past the end of a rollback journal file */
  67329. assert( iOfst+iAmt<=p->endpoint.iOffset );
  67330. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  67331. sqlite3_int64 iOff = 0;
  67332. for(pChunk=p->pFirst;
  67333. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  67334. pChunk=pChunk->pNext
  67335. ){
  67336. iOff += JOURNAL_CHUNKSIZE;
  67337. }
  67338. }else{
  67339. pChunk = p->readpoint.pChunk;
  67340. }
  67341. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  67342. do {
  67343. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  67344. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  67345. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  67346. zOut += nCopy;
  67347. nRead -= iSpace;
  67348. iChunkOffset = 0;
  67349. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  67350. p->readpoint.iOffset = iOfst+iAmt;
  67351. p->readpoint.pChunk = pChunk;
  67352. return SQLITE_OK;
  67353. }
  67354. /*
  67355. ** Write data to the file.
  67356. */
  67357. static int memjrnlWrite(
  67358. sqlite3_file *pJfd, /* The journal file into which to write */
  67359. const void *zBuf, /* Take data to be written from here */
  67360. int iAmt, /* Number of bytes to write */
  67361. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  67362. ){
  67363. MemJournal *p = (MemJournal *)pJfd;
  67364. int nWrite = iAmt;
  67365. u8 *zWrite = (u8 *)zBuf;
  67366. /* An in-memory journal file should only ever be appended to. Random
  67367. ** access writes are not required by sqlite.
  67368. */
  67369. assert( iOfst==p->endpoint.iOffset );
  67370. UNUSED_PARAMETER(iOfst);
  67371. while( nWrite>0 ){
  67372. FileChunk *pChunk = p->endpoint.pChunk;
  67373. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  67374. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  67375. if( iChunkOffset==0 ){
  67376. /* New chunk is required to extend the file. */
  67377. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  67378. if( !pNew ){
  67379. return SQLITE_IOERR_NOMEM;
  67380. }
  67381. pNew->pNext = 0;
  67382. if( pChunk ){
  67383. assert( p->pFirst );
  67384. pChunk->pNext = pNew;
  67385. }else{
  67386. assert( !p->pFirst );
  67387. p->pFirst = pNew;
  67388. }
  67389. p->endpoint.pChunk = pNew;
  67390. }
  67391. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  67392. zWrite += iSpace;
  67393. nWrite -= iSpace;
  67394. p->endpoint.iOffset += iSpace;
  67395. }
  67396. return SQLITE_OK;
  67397. }
  67398. /*
  67399. ** Truncate the file.
  67400. */
  67401. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  67402. MemJournal *p = (MemJournal *)pJfd;
  67403. FileChunk *pChunk;
  67404. assert(size==0);
  67405. UNUSED_PARAMETER(size);
  67406. pChunk = p->pFirst;
  67407. while( pChunk ){
  67408. FileChunk *pTmp = pChunk;
  67409. pChunk = pChunk->pNext;
  67410. sqlite3_free(pTmp);
  67411. }
  67412. sqlite3MemJournalOpen(pJfd);
  67413. return SQLITE_OK;
  67414. }
  67415. /*
  67416. ** Close the file.
  67417. */
  67418. static int memjrnlClose(sqlite3_file *pJfd){
  67419. memjrnlTruncate(pJfd, 0);
  67420. return SQLITE_OK;
  67421. }
  67422. /*
  67423. ** Sync the file.
  67424. **
  67425. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  67426. ** is never called in a working implementation. This implementation
  67427. ** exists purely as a contingency, in case some malfunction in some other
  67428. ** part of SQLite causes Sync to be called by mistake.
  67429. */
  67430. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  67431. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  67432. return SQLITE_OK;
  67433. }
  67434. /*
  67435. ** Query the size of the file in bytes.
  67436. */
  67437. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  67438. MemJournal *p = (MemJournal *)pJfd;
  67439. *pSize = (sqlite_int64) p->endpoint.iOffset;
  67440. return SQLITE_OK;
  67441. }
  67442. /*
  67443. ** Table of methods for MemJournal sqlite3_file object.
  67444. */
  67445. static const struct sqlite3_io_methods MemJournalMethods = {
  67446. 1, /* iVersion */
  67447. memjrnlClose, /* xClose */
  67448. memjrnlRead, /* xRead */
  67449. memjrnlWrite, /* xWrite */
  67450. memjrnlTruncate, /* xTruncate */
  67451. memjrnlSync, /* xSync */
  67452. memjrnlFileSize, /* xFileSize */
  67453. 0, /* xLock */
  67454. 0, /* xUnlock */
  67455. 0, /* xCheckReservedLock */
  67456. 0, /* xFileControl */
  67457. 0, /* xSectorSize */
  67458. 0, /* xDeviceCharacteristics */
  67459. 0, /* xShmMap */
  67460. 0, /* xShmLock */
  67461. 0, /* xShmBarrier */
  67462. 0 /* xShmUnlock */
  67463. };
  67464. /*
  67465. ** Open a journal file.
  67466. */
  67467. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  67468. MemJournal *p = (MemJournal *)pJfd;
  67469. assert( EIGHT_BYTE_ALIGNMENT(p) );
  67470. memset(p, 0, sqlite3MemJournalSize());
  67471. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  67472. }
  67473. /*
  67474. ** Return true if the file-handle passed as an argument is
  67475. ** an in-memory journal
  67476. */
  67477. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  67478. return pJfd->pMethods==&MemJournalMethods;
  67479. }
  67480. /*
  67481. ** Return the number of bytes required to store a MemJournal file descriptor.
  67482. */
  67483. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  67484. return sizeof(MemJournal);
  67485. }
  67486. /************** End of memjournal.c ******************************************/
  67487. /************** Begin file walker.c ******************************************/
  67488. /*
  67489. ** 2008 August 16
  67490. **
  67491. ** The author disclaims copyright to this source code. In place of
  67492. ** a legal notice, here is a blessing:
  67493. **
  67494. ** May you do good and not evil.
  67495. ** May you find forgiveness for yourself and forgive others.
  67496. ** May you share freely, never taking more than you give.
  67497. **
  67498. *************************************************************************
  67499. ** This file contains routines used for walking the parser tree for
  67500. ** an SQL statement.
  67501. */
  67502. /* #include <stdlib.h> */
  67503. /* #include <string.h> */
  67504. /*
  67505. ** Walk an expression tree. Invoke the callback once for each node
  67506. ** of the expression, while decending. (In other words, the callback
  67507. ** is invoked before visiting children.)
  67508. **
  67509. ** The return value from the callback should be one of the WRC_*
  67510. ** constants to specify how to proceed with the walk.
  67511. **
  67512. ** WRC_Continue Continue descending down the tree.
  67513. **
  67514. ** WRC_Prune Do not descend into child nodes. But allow
  67515. ** the walk to continue with sibling nodes.
  67516. **
  67517. ** WRC_Abort Do no more callbacks. Unwind the stack and
  67518. ** return the top-level walk call.
  67519. **
  67520. ** The return value from this routine is WRC_Abort to abandon the tree walk
  67521. ** and WRC_Continue to continue.
  67522. */
  67523. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  67524. int rc;
  67525. if( pExpr==0 ) return WRC_Continue;
  67526. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  67527. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  67528. rc = pWalker->xExprCallback(pWalker, pExpr);
  67529. if( rc==WRC_Continue
  67530. && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
  67531. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  67532. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  67533. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  67534. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  67535. }else{
  67536. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  67537. }
  67538. }
  67539. return rc & WRC_Abort;
  67540. }
  67541. /*
  67542. ** Call sqlite3WalkExpr() for every expression in list p or until
  67543. ** an abort request is seen.
  67544. */
  67545. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  67546. int i;
  67547. struct ExprList_item *pItem;
  67548. if( p ){
  67549. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  67550. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  67551. }
  67552. }
  67553. return WRC_Continue;
  67554. }
  67555. /*
  67556. ** Walk all expressions associated with SELECT statement p. Do
  67557. ** not invoke the SELECT callback on p, but do (of course) invoke
  67558. ** any expr callbacks and SELECT callbacks that come from subqueries.
  67559. ** Return WRC_Abort or WRC_Continue.
  67560. */
  67561. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  67562. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  67563. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  67564. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  67565. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  67566. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  67567. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  67568. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  67569. return WRC_Continue;
  67570. }
  67571. /*
  67572. ** Walk the parse trees associated with all subqueries in the
  67573. ** FROM clause of SELECT statement p. Do not invoke the select
  67574. ** callback on p, but do invoke it on each FROM clause subquery
  67575. ** and on any subqueries further down in the tree. Return
  67576. ** WRC_Abort or WRC_Continue;
  67577. */
  67578. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  67579. SrcList *pSrc;
  67580. int i;
  67581. struct SrcList_item *pItem;
  67582. pSrc = p->pSrc;
  67583. if( ALWAYS(pSrc) ){
  67584. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  67585. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  67586. return WRC_Abort;
  67587. }
  67588. }
  67589. }
  67590. return WRC_Continue;
  67591. }
  67592. /*
  67593. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  67594. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  67595. ** on the compound select chain, p->pPrior.
  67596. **
  67597. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  67598. ** there is an abort request.
  67599. **
  67600. ** If the Walker does not have an xSelectCallback() then this routine
  67601. ** is a no-op returning WRC_Continue.
  67602. */
  67603. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  67604. int rc;
  67605. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  67606. rc = WRC_Continue;
  67607. pWalker->walkerDepth++;
  67608. while( p ){
  67609. rc = pWalker->xSelectCallback(pWalker, p);
  67610. if( rc ) break;
  67611. if( sqlite3WalkSelectExpr(pWalker, p)
  67612. || sqlite3WalkSelectFrom(pWalker, p)
  67613. ){
  67614. pWalker->walkerDepth--;
  67615. return WRC_Abort;
  67616. }
  67617. p = p->pPrior;
  67618. }
  67619. pWalker->walkerDepth--;
  67620. return rc & WRC_Abort;
  67621. }
  67622. /************** End of walker.c **********************************************/
  67623. /************** Begin file resolve.c *****************************************/
  67624. /*
  67625. ** 2008 August 18
  67626. **
  67627. ** The author disclaims copyright to this source code. In place of
  67628. ** a legal notice, here is a blessing:
  67629. **
  67630. ** May you do good and not evil.
  67631. ** May you find forgiveness for yourself and forgive others.
  67632. ** May you share freely, never taking more than you give.
  67633. **
  67634. *************************************************************************
  67635. **
  67636. ** This file contains routines used for walking the parser tree and
  67637. ** resolve all identifiers by associating them with a particular
  67638. ** table and column.
  67639. */
  67640. /* #include <stdlib.h> */
  67641. /* #include <string.h> */
  67642. /*
  67643. ** Walk the expression tree pExpr and increase the aggregate function
  67644. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  67645. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  67646. ** outer query into an inner subquery.
  67647. **
  67648. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  67649. ** is a helper function - a callback for the tree walker.
  67650. */
  67651. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  67652. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  67653. return WRC_Continue;
  67654. }
  67655. static void incrAggFunctionDepth(Expr *pExpr, int N){
  67656. if( N>0 ){
  67657. Walker w;
  67658. memset(&w, 0, sizeof(w));
  67659. w.xExprCallback = incrAggDepth;
  67660. w.u.i = N;
  67661. sqlite3WalkExpr(&w, pExpr);
  67662. }
  67663. }
  67664. /*
  67665. ** Turn the pExpr expression into an alias for the iCol-th column of the
  67666. ** result set in pEList.
  67667. **
  67668. ** If the result set column is a simple column reference, then this routine
  67669. ** makes an exact copy. But for any other kind of expression, this
  67670. ** routine make a copy of the result set column as the argument to the
  67671. ** TK_AS operator. The TK_AS operator causes the expression to be
  67672. ** evaluated just once and then reused for each alias.
  67673. **
  67674. ** The reason for suppressing the TK_AS term when the expression is a simple
  67675. ** column reference is so that the column reference will be recognized as
  67676. ** usable by indices within the WHERE clause processing logic.
  67677. **
  67678. ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
  67679. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  67680. **
  67681. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  67682. **
  67683. ** Is equivalent to:
  67684. **
  67685. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  67686. **
  67687. ** The result of random()%5 in the GROUP BY clause is probably different
  67688. ** from the result in the result-set. We might fix this someday. Or
  67689. ** then again, we might not...
  67690. **
  67691. ** If the reference is followed by a COLLATE operator, then make sure
  67692. ** the COLLATE operator is preserved. For example:
  67693. **
  67694. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  67695. **
  67696. ** Should be transformed into:
  67697. **
  67698. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  67699. **
  67700. ** The nSubquery parameter specifies how many levels of subquery the
  67701. ** alias is removed from the original expression. The usually value is
  67702. ** zero but it might be more if the alias is contained within a subquery
  67703. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  67704. ** structures must be increased by the nSubquery amount.
  67705. */
  67706. static void resolveAlias(
  67707. Parse *pParse, /* Parsing context */
  67708. ExprList *pEList, /* A result set */
  67709. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  67710. Expr *pExpr, /* Transform this into an alias to the result set */
  67711. const char *zType, /* "GROUP" or "ORDER" or "" */
  67712. int nSubquery /* Number of subqueries that the label is moving */
  67713. ){
  67714. Expr *pOrig; /* The iCol-th column of the result set */
  67715. Expr *pDup; /* Copy of pOrig */
  67716. sqlite3 *db; /* The database connection */
  67717. assert( iCol>=0 && iCol<pEList->nExpr );
  67718. pOrig = pEList->a[iCol].pExpr;
  67719. assert( pOrig!=0 );
  67720. assert( pOrig->flags & EP_Resolved );
  67721. db = pParse->db;
  67722. pDup = sqlite3ExprDup(db, pOrig, 0);
  67723. if( pDup==0 ) return;
  67724. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  67725. incrAggFunctionDepth(pDup, nSubquery);
  67726. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  67727. if( pDup==0 ) return;
  67728. if( pEList->a[iCol].iAlias==0 ){
  67729. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  67730. }
  67731. pDup->iTable = pEList->a[iCol].iAlias;
  67732. }
  67733. if( pExpr->op==TK_COLLATE ){
  67734. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  67735. }
  67736. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  67737. ** prevents ExprDelete() from deleting the Expr structure itself,
  67738. ** allowing it to be repopulated by the memcpy() on the following line.
  67739. ** The pExpr->u.zToken might point into memory that will be freed by the
  67740. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  67741. ** make a copy of the token before doing the sqlite3DbFree().
  67742. */
  67743. ExprSetProperty(pExpr, EP_Static);
  67744. sqlite3ExprDelete(db, pExpr);
  67745. memcpy(pExpr, pDup, sizeof(*pExpr));
  67746. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  67747. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  67748. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  67749. pExpr->flags2 |= EP2_MallocedToken;
  67750. }
  67751. sqlite3DbFree(db, pDup);
  67752. }
  67753. /*
  67754. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  67755. **
  67756. ** Return FALSE if the USING clause is NULL or if it does not contain
  67757. ** zCol.
  67758. */
  67759. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  67760. if( pUsing ){
  67761. int k;
  67762. for(k=0; k<pUsing->nId; k++){
  67763. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  67764. }
  67765. }
  67766. return 0;
  67767. }
  67768. /*
  67769. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  67770. ** that name in the set of source tables in pSrcList and make the pExpr
  67771. ** expression node refer back to that source column. The following changes
  67772. ** are made to pExpr:
  67773. **
  67774. ** pExpr->iDb Set the index in db->aDb[] of the database X
  67775. ** (even if X is implied).
  67776. ** pExpr->iTable Set to the cursor number for the table obtained
  67777. ** from pSrcList.
  67778. ** pExpr->pTab Points to the Table structure of X.Y (even if
  67779. ** X and/or Y are implied.)
  67780. ** pExpr->iColumn Set to the column number within the table.
  67781. ** pExpr->op Set to TK_COLUMN.
  67782. ** pExpr->pLeft Any expression this points to is deleted
  67783. ** pExpr->pRight Any expression this points to is deleted.
  67784. **
  67785. ** The zDb variable is the name of the database (the "X"). This value may be
  67786. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  67787. ** can be used. The zTable variable is the name of the table (the "Y"). This
  67788. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  67789. ** means that the form of the name is Z and that columns from any table
  67790. ** can be used.
  67791. **
  67792. ** If the name cannot be resolved unambiguously, leave an error message
  67793. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  67794. */
  67795. static int lookupName(
  67796. Parse *pParse, /* The parsing context */
  67797. const char *zDb, /* Name of the database containing table, or NULL */
  67798. const char *zTab, /* Name of table containing column, or NULL */
  67799. const char *zCol, /* Name of the column. */
  67800. NameContext *pNC, /* The name context used to resolve the name */
  67801. Expr *pExpr /* Make this EXPR node point to the selected column */
  67802. ){
  67803. int i, j; /* Loop counters */
  67804. int cnt = 0; /* Number of matching column names */
  67805. int cntTab = 0; /* Number of matching table names */
  67806. int nSubquery = 0; /* How many levels of subquery */
  67807. sqlite3 *db = pParse->db; /* The database connection */
  67808. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  67809. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  67810. NameContext *pTopNC = pNC; /* First namecontext in the list */
  67811. Schema *pSchema = 0; /* Schema of the expression */
  67812. int isTrigger = 0;
  67813. assert( pNC ); /* the name context cannot be NULL. */
  67814. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  67815. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  67816. /* Initialize the node to no-match */
  67817. pExpr->iTable = -1;
  67818. pExpr->pTab = 0;
  67819. ExprSetIrreducible(pExpr);
  67820. /* Start at the inner-most context and move outward until a match is found */
  67821. while( pNC && cnt==0 ){
  67822. ExprList *pEList;
  67823. SrcList *pSrcList = pNC->pSrcList;
  67824. if( pSrcList ){
  67825. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  67826. Table *pTab;
  67827. int iDb;
  67828. Column *pCol;
  67829. pTab = pItem->pTab;
  67830. assert( pTab!=0 && pTab->zName!=0 );
  67831. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67832. assert( pTab->nCol>0 );
  67833. if( zTab ){
  67834. if( pItem->zAlias ){
  67835. char *zTabName = pItem->zAlias;
  67836. if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  67837. }else{
  67838. char *zTabName = pTab->zName;
  67839. if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
  67840. continue;
  67841. }
  67842. if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
  67843. continue;
  67844. }
  67845. }
  67846. }
  67847. if( 0==(cntTab++) ){
  67848. pExpr->iTable = pItem->iCursor;
  67849. pExpr->pTab = pTab;
  67850. pSchema = pTab->pSchema;
  67851. pMatch = pItem;
  67852. }
  67853. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  67854. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  67855. /* If there has been exactly one prior match and this match
  67856. ** is for the right-hand table of a NATURAL JOIN or is in a
  67857. ** USING clause, then skip this match.
  67858. */
  67859. if( cnt==1 ){
  67860. if( pItem->jointype & JT_NATURAL ) continue;
  67861. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  67862. }
  67863. cnt++;
  67864. pExpr->iTable = pItem->iCursor;
  67865. pExpr->pTab = pTab;
  67866. pMatch = pItem;
  67867. pSchema = pTab->pSchema;
  67868. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  67869. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  67870. break;
  67871. }
  67872. }
  67873. }
  67874. }
  67875. #ifndef SQLITE_OMIT_TRIGGER
  67876. /* If we have not already resolved the name, then maybe
  67877. ** it is a new.* or old.* trigger argument reference
  67878. */
  67879. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  67880. int op = pParse->eTriggerOp;
  67881. Table *pTab = 0;
  67882. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  67883. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  67884. pExpr->iTable = 1;
  67885. pTab = pParse->pTriggerTab;
  67886. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  67887. pExpr->iTable = 0;
  67888. pTab = pParse->pTriggerTab;
  67889. }
  67890. if( pTab ){
  67891. int iCol;
  67892. pSchema = pTab->pSchema;
  67893. cntTab++;
  67894. for(iCol=0; iCol<pTab->nCol; iCol++){
  67895. Column *pCol = &pTab->aCol[iCol];
  67896. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  67897. if( iCol==pTab->iPKey ){
  67898. iCol = -1;
  67899. }
  67900. break;
  67901. }
  67902. }
  67903. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  67904. iCol = -1; /* IMP: R-44911-55124 */
  67905. }
  67906. if( iCol<pTab->nCol ){
  67907. cnt++;
  67908. if( iCol<0 ){
  67909. pExpr->affinity = SQLITE_AFF_INTEGER;
  67910. }else if( pExpr->iTable==0 ){
  67911. testcase( iCol==31 );
  67912. testcase( iCol==32 );
  67913. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  67914. }else{
  67915. testcase( iCol==31 );
  67916. testcase( iCol==32 );
  67917. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  67918. }
  67919. pExpr->iColumn = (i16)iCol;
  67920. pExpr->pTab = pTab;
  67921. isTrigger = 1;
  67922. }
  67923. }
  67924. }
  67925. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  67926. /*
  67927. ** Perhaps the name is a reference to the ROWID
  67928. */
  67929. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  67930. cnt = 1;
  67931. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  67932. pExpr->affinity = SQLITE_AFF_INTEGER;
  67933. }
  67934. /*
  67935. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  67936. ** might refer to an result-set alias. This happens, for example, when
  67937. ** we are resolving names in the WHERE clause of the following command:
  67938. **
  67939. ** SELECT a+b AS x FROM table WHERE x<10;
  67940. **
  67941. ** In cases like this, replace pExpr with a copy of the expression that
  67942. ** forms the result set entry ("a+b" in the example) and return immediately.
  67943. ** Note that the expression in the result set should have already been
  67944. ** resolved by the time the WHERE clause is resolved.
  67945. */
  67946. if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
  67947. for(j=0; j<pEList->nExpr; j++){
  67948. char *zAs = pEList->a[j].zName;
  67949. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  67950. Expr *pOrig;
  67951. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  67952. assert( pExpr->x.pList==0 );
  67953. assert( pExpr->x.pSelect==0 );
  67954. pOrig = pEList->a[j].pExpr;
  67955. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  67956. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  67957. return WRC_Abort;
  67958. }
  67959. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  67960. cnt = 1;
  67961. pMatch = 0;
  67962. assert( zTab==0 && zDb==0 );
  67963. goto lookupname_end;
  67964. }
  67965. }
  67966. }
  67967. /* Advance to the next name context. The loop will exit when either
  67968. ** we have a match (cnt>0) or when we run out of name contexts.
  67969. */
  67970. if( cnt==0 ){
  67971. pNC = pNC->pNext;
  67972. nSubquery++;
  67973. }
  67974. }
  67975. /*
  67976. ** If X and Y are NULL (in other words if only the column name Z is
  67977. ** supplied) and the value of Z is enclosed in double-quotes, then
  67978. ** Z is a string literal if it doesn't match any column names. In that
  67979. ** case, we need to return right away and not make any changes to
  67980. ** pExpr.
  67981. **
  67982. ** Because no reference was made to outer contexts, the pNC->nRef
  67983. ** fields are not changed in any context.
  67984. */
  67985. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  67986. pExpr->op = TK_STRING;
  67987. pExpr->pTab = 0;
  67988. return WRC_Prune;
  67989. }
  67990. /*
  67991. ** cnt==0 means there was not match. cnt>1 means there were two or
  67992. ** more matches. Either way, we have an error.
  67993. */
  67994. if( cnt!=1 ){
  67995. const char *zErr;
  67996. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  67997. if( zDb ){
  67998. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  67999. }else if( zTab ){
  68000. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  68001. }else{
  68002. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  68003. }
  68004. pParse->checkSchema = 1;
  68005. pTopNC->nErr++;
  68006. }
  68007. /* If a column from a table in pSrcList is referenced, then record
  68008. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  68009. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  68010. ** column number is greater than the number of bits in the bitmask
  68011. ** then set the high-order bit of the bitmask.
  68012. */
  68013. if( pExpr->iColumn>=0 && pMatch!=0 ){
  68014. int n = pExpr->iColumn;
  68015. testcase( n==BMS-1 );
  68016. if( n>=BMS ){
  68017. n = BMS-1;
  68018. }
  68019. assert( pMatch->iCursor==pExpr->iTable );
  68020. pMatch->colUsed |= ((Bitmask)1)<<n;
  68021. }
  68022. /* Clean up and return
  68023. */
  68024. sqlite3ExprDelete(db, pExpr->pLeft);
  68025. pExpr->pLeft = 0;
  68026. sqlite3ExprDelete(db, pExpr->pRight);
  68027. pExpr->pRight = 0;
  68028. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  68029. lookupname_end:
  68030. if( cnt==1 ){
  68031. assert( pNC!=0 );
  68032. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  68033. /* Increment the nRef value on all name contexts from TopNC up to
  68034. ** the point where the name matched. */
  68035. for(;;){
  68036. assert( pTopNC!=0 );
  68037. pTopNC->nRef++;
  68038. if( pTopNC==pNC ) break;
  68039. pTopNC = pTopNC->pNext;
  68040. }
  68041. return WRC_Prune;
  68042. } else {
  68043. return WRC_Abort;
  68044. }
  68045. }
  68046. /*
  68047. ** Allocate and return a pointer to an expression to load the column iCol
  68048. ** from datasource iSrc in SrcList pSrc.
  68049. */
  68050. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  68051. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  68052. if( p ){
  68053. struct SrcList_item *pItem = &pSrc->a[iSrc];
  68054. p->pTab = pItem->pTab;
  68055. p->iTable = pItem->iCursor;
  68056. if( p->pTab->iPKey==iCol ){
  68057. p->iColumn = -1;
  68058. }else{
  68059. p->iColumn = (ynVar)iCol;
  68060. testcase( iCol==BMS );
  68061. testcase( iCol==BMS-1 );
  68062. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  68063. }
  68064. ExprSetProperty(p, EP_Resolved);
  68065. }
  68066. return p;
  68067. }
  68068. /*
  68069. ** This routine is callback for sqlite3WalkExpr().
  68070. **
  68071. ** Resolve symbolic names into TK_COLUMN operators for the current
  68072. ** node in the expression tree. Return 0 to continue the search down
  68073. ** the tree or 2 to abort the tree walk.
  68074. **
  68075. ** This routine also does error checking and name resolution for
  68076. ** function names. The operator for aggregate functions is changed
  68077. ** to TK_AGG_FUNCTION.
  68078. */
  68079. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  68080. NameContext *pNC;
  68081. Parse *pParse;
  68082. pNC = pWalker->u.pNC;
  68083. assert( pNC!=0 );
  68084. pParse = pNC->pParse;
  68085. assert( pParse==pWalker->pParse );
  68086. if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  68087. ExprSetProperty(pExpr, EP_Resolved);
  68088. #ifndef NDEBUG
  68089. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  68090. SrcList *pSrcList = pNC->pSrcList;
  68091. int i;
  68092. for(i=0; i<pNC->pSrcList->nSrc; i++){
  68093. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  68094. }
  68095. }
  68096. #endif
  68097. switch( pExpr->op ){
  68098. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  68099. /* The special operator TK_ROW means use the rowid for the first
  68100. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  68101. ** clause processing on UPDATE and DELETE statements.
  68102. */
  68103. case TK_ROW: {
  68104. SrcList *pSrcList = pNC->pSrcList;
  68105. struct SrcList_item *pItem;
  68106. assert( pSrcList && pSrcList->nSrc==1 );
  68107. pItem = pSrcList->a;
  68108. pExpr->op = TK_COLUMN;
  68109. pExpr->pTab = pItem->pTab;
  68110. pExpr->iTable = pItem->iCursor;
  68111. pExpr->iColumn = -1;
  68112. pExpr->affinity = SQLITE_AFF_INTEGER;
  68113. break;
  68114. }
  68115. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  68116. /* A lone identifier is the name of a column.
  68117. */
  68118. case TK_ID: {
  68119. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  68120. }
  68121. /* A table name and column name: ID.ID
  68122. ** Or a database, table and column: ID.ID.ID
  68123. */
  68124. case TK_DOT: {
  68125. const char *zColumn;
  68126. const char *zTable;
  68127. const char *zDb;
  68128. Expr *pRight;
  68129. /* if( pSrcList==0 ) break; */
  68130. pRight = pExpr->pRight;
  68131. if( pRight->op==TK_ID ){
  68132. zDb = 0;
  68133. zTable = pExpr->pLeft->u.zToken;
  68134. zColumn = pRight->u.zToken;
  68135. }else{
  68136. assert( pRight->op==TK_DOT );
  68137. zDb = pExpr->pLeft->u.zToken;
  68138. zTable = pRight->pLeft->u.zToken;
  68139. zColumn = pRight->pRight->u.zToken;
  68140. }
  68141. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  68142. }
  68143. /* Resolve function names
  68144. */
  68145. case TK_CONST_FUNC:
  68146. case TK_FUNCTION: {
  68147. ExprList *pList = pExpr->x.pList; /* The argument list */
  68148. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  68149. int no_such_func = 0; /* True if no such function exists */
  68150. int wrong_num_args = 0; /* True if wrong number of arguments */
  68151. int is_agg = 0; /* True if is an aggregate function */
  68152. int auth; /* Authorization to use the function */
  68153. int nId; /* Number of characters in function name */
  68154. const char *zId; /* The function name. */
  68155. FuncDef *pDef; /* Information about the function */
  68156. u8 enc = ENC(pParse->db); /* The database encoding */
  68157. testcase( pExpr->op==TK_CONST_FUNC );
  68158. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  68159. zId = pExpr->u.zToken;
  68160. nId = sqlite3Strlen30(zId);
  68161. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  68162. if( pDef==0 ){
  68163. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  68164. if( pDef==0 ){
  68165. no_such_func = 1;
  68166. }else{
  68167. wrong_num_args = 1;
  68168. }
  68169. }else{
  68170. is_agg = pDef->xFunc==0;
  68171. }
  68172. #ifndef SQLITE_OMIT_AUTHORIZATION
  68173. if( pDef ){
  68174. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  68175. if( auth!=SQLITE_OK ){
  68176. if( auth==SQLITE_DENY ){
  68177. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  68178. pDef->zName);
  68179. pNC->nErr++;
  68180. }
  68181. pExpr->op = TK_NULL;
  68182. return WRC_Prune;
  68183. }
  68184. }
  68185. #endif
  68186. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  68187. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  68188. pNC->nErr++;
  68189. is_agg = 0;
  68190. }else if( no_such_func ){
  68191. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  68192. pNC->nErr++;
  68193. }else if( wrong_num_args ){
  68194. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  68195. nId, zId);
  68196. pNC->nErr++;
  68197. }
  68198. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  68199. sqlite3WalkExprList(pWalker, pList);
  68200. if( is_agg ){
  68201. NameContext *pNC2 = pNC;
  68202. pExpr->op = TK_AGG_FUNCTION;
  68203. pExpr->op2 = 0;
  68204. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  68205. pExpr->op2++;
  68206. pNC2 = pNC2->pNext;
  68207. }
  68208. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  68209. pNC->ncFlags |= NC_AllowAgg;
  68210. }
  68211. /* FIX ME: Compute pExpr->affinity based on the expected return
  68212. ** type of the function
  68213. */
  68214. return WRC_Prune;
  68215. }
  68216. #ifndef SQLITE_OMIT_SUBQUERY
  68217. case TK_SELECT:
  68218. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  68219. #endif
  68220. case TK_IN: {
  68221. testcase( pExpr->op==TK_IN );
  68222. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  68223. int nRef = pNC->nRef;
  68224. #ifndef SQLITE_OMIT_CHECK
  68225. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  68226. sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
  68227. }
  68228. #endif
  68229. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  68230. assert( pNC->nRef>=nRef );
  68231. if( nRef!=pNC->nRef ){
  68232. ExprSetProperty(pExpr, EP_VarSelect);
  68233. }
  68234. }
  68235. break;
  68236. }
  68237. #ifndef SQLITE_OMIT_CHECK
  68238. case TK_VARIABLE: {
  68239. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  68240. sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
  68241. }
  68242. break;
  68243. }
  68244. #endif
  68245. }
  68246. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  68247. }
  68248. /*
  68249. ** pEList is a list of expressions which are really the result set of the
  68250. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  68251. ** This routine checks to see if pE is a simple identifier which corresponds
  68252. ** to the AS-name of one of the terms of the expression list. If it is,
  68253. ** this routine return an integer between 1 and N where N is the number of
  68254. ** elements in pEList, corresponding to the matching entry. If there is
  68255. ** no match, or if pE is not a simple identifier, then this routine
  68256. ** return 0.
  68257. **
  68258. ** pEList has been resolved. pE has not.
  68259. */
  68260. static int resolveAsName(
  68261. Parse *pParse, /* Parsing context for error messages */
  68262. ExprList *pEList, /* List of expressions to scan */
  68263. Expr *pE /* Expression we are trying to match */
  68264. ){
  68265. int i; /* Loop counter */
  68266. UNUSED_PARAMETER(pParse);
  68267. if( pE->op==TK_ID ){
  68268. char *zCol = pE->u.zToken;
  68269. for(i=0; i<pEList->nExpr; i++){
  68270. char *zAs = pEList->a[i].zName;
  68271. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  68272. return i+1;
  68273. }
  68274. }
  68275. }
  68276. return 0;
  68277. }
  68278. /*
  68279. ** pE is a pointer to an expression which is a single term in the
  68280. ** ORDER BY of a compound SELECT. The expression has not been
  68281. ** name resolved.
  68282. **
  68283. ** At the point this routine is called, we already know that the
  68284. ** ORDER BY term is not an integer index into the result set. That
  68285. ** case is handled by the calling routine.
  68286. **
  68287. ** Attempt to match pE against result set columns in the left-most
  68288. ** SELECT statement. Return the index i of the matching column,
  68289. ** as an indication to the caller that it should sort by the i-th column.
  68290. ** The left-most column is 1. In other words, the value returned is the
  68291. ** same integer value that would be used in the SQL statement to indicate
  68292. ** the column.
  68293. **
  68294. ** If there is no match, return 0. Return -1 if an error occurs.
  68295. */
  68296. static int resolveOrderByTermToExprList(
  68297. Parse *pParse, /* Parsing context for error messages */
  68298. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  68299. Expr *pE /* The specific ORDER BY term */
  68300. ){
  68301. int i; /* Loop counter */
  68302. ExprList *pEList; /* The columns of the result set */
  68303. NameContext nc; /* Name context for resolving pE */
  68304. sqlite3 *db; /* Database connection */
  68305. int rc; /* Return code from subprocedures */
  68306. u8 savedSuppErr; /* Saved value of db->suppressErr */
  68307. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  68308. pEList = pSelect->pEList;
  68309. /* Resolve all names in the ORDER BY term expression
  68310. */
  68311. memset(&nc, 0, sizeof(nc));
  68312. nc.pParse = pParse;
  68313. nc.pSrcList = pSelect->pSrc;
  68314. nc.pEList = pEList;
  68315. nc.ncFlags = NC_AllowAgg;
  68316. nc.nErr = 0;
  68317. db = pParse->db;
  68318. savedSuppErr = db->suppressErr;
  68319. db->suppressErr = 1;
  68320. rc = sqlite3ResolveExprNames(&nc, pE);
  68321. db->suppressErr = savedSuppErr;
  68322. if( rc ) return 0;
  68323. /* Try to match the ORDER BY expression against an expression
  68324. ** in the result set. Return an 1-based index of the matching
  68325. ** result-set entry.
  68326. */
  68327. for(i=0; i<pEList->nExpr; i++){
  68328. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
  68329. return i+1;
  68330. }
  68331. }
  68332. /* If no match, return 0. */
  68333. return 0;
  68334. }
  68335. /*
  68336. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  68337. */
  68338. static void resolveOutOfRangeError(
  68339. Parse *pParse, /* The error context into which to write the error */
  68340. const char *zType, /* "ORDER" or "GROUP" */
  68341. int i, /* The index (1-based) of the term out of range */
  68342. int mx /* Largest permissible value of i */
  68343. ){
  68344. sqlite3ErrorMsg(pParse,
  68345. "%r %s BY term out of range - should be "
  68346. "between 1 and %d", i, zType, mx);
  68347. }
  68348. /*
  68349. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  68350. ** each term of the ORDER BY clause is a constant integer between 1
  68351. ** and N where N is the number of columns in the compound SELECT.
  68352. **
  68353. ** ORDER BY terms that are already an integer between 1 and N are
  68354. ** unmodified. ORDER BY terms that are integers outside the range of
  68355. ** 1 through N generate an error. ORDER BY terms that are expressions
  68356. ** are matched against result set expressions of compound SELECT
  68357. ** beginning with the left-most SELECT and working toward the right.
  68358. ** At the first match, the ORDER BY expression is transformed into
  68359. ** the integer column number.
  68360. **
  68361. ** Return the number of errors seen.
  68362. */
  68363. static int resolveCompoundOrderBy(
  68364. Parse *pParse, /* Parsing context. Leave error messages here */
  68365. Select *pSelect /* The SELECT statement containing the ORDER BY */
  68366. ){
  68367. int i;
  68368. ExprList *pOrderBy;
  68369. ExprList *pEList;
  68370. sqlite3 *db;
  68371. int moreToDo = 1;
  68372. pOrderBy = pSelect->pOrderBy;
  68373. if( pOrderBy==0 ) return 0;
  68374. db = pParse->db;
  68375. #if SQLITE_MAX_COLUMN
  68376. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  68377. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  68378. return 1;
  68379. }
  68380. #endif
  68381. for(i=0; i<pOrderBy->nExpr; i++){
  68382. pOrderBy->a[i].done = 0;
  68383. }
  68384. pSelect->pNext = 0;
  68385. while( pSelect->pPrior ){
  68386. pSelect->pPrior->pNext = pSelect;
  68387. pSelect = pSelect->pPrior;
  68388. }
  68389. while( pSelect && moreToDo ){
  68390. struct ExprList_item *pItem;
  68391. moreToDo = 0;
  68392. pEList = pSelect->pEList;
  68393. assert( pEList!=0 );
  68394. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  68395. int iCol = -1;
  68396. Expr *pE, *pDup;
  68397. if( pItem->done ) continue;
  68398. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  68399. if( sqlite3ExprIsInteger(pE, &iCol) ){
  68400. if( iCol<=0 || iCol>pEList->nExpr ){
  68401. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  68402. return 1;
  68403. }
  68404. }else{
  68405. iCol = resolveAsName(pParse, pEList, pE);
  68406. if( iCol==0 ){
  68407. pDup = sqlite3ExprDup(db, pE, 0);
  68408. if( !db->mallocFailed ){
  68409. assert(pDup);
  68410. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  68411. }
  68412. sqlite3ExprDelete(db, pDup);
  68413. }
  68414. }
  68415. if( iCol>0 ){
  68416. /* Convert the ORDER BY term into an integer column number iCol,
  68417. ** taking care to preserve the COLLATE clause if it exists */
  68418. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  68419. if( pNew==0 ) return 1;
  68420. pNew->flags |= EP_IntValue;
  68421. pNew->u.iValue = iCol;
  68422. if( pItem->pExpr==pE ){
  68423. pItem->pExpr = pNew;
  68424. }else{
  68425. assert( pItem->pExpr->op==TK_COLLATE );
  68426. assert( pItem->pExpr->pLeft==pE );
  68427. pItem->pExpr->pLeft = pNew;
  68428. }
  68429. sqlite3ExprDelete(db, pE);
  68430. pItem->iOrderByCol = (u16)iCol;
  68431. pItem->done = 1;
  68432. }else{
  68433. moreToDo = 1;
  68434. }
  68435. }
  68436. pSelect = pSelect->pNext;
  68437. }
  68438. for(i=0; i<pOrderBy->nExpr; i++){
  68439. if( pOrderBy->a[i].done==0 ){
  68440. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  68441. "column in the result set", i+1);
  68442. return 1;
  68443. }
  68444. }
  68445. return 0;
  68446. }
  68447. /*
  68448. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  68449. ** the SELECT statement pSelect. If any term is reference to a
  68450. ** result set expression (as determined by the ExprList.a.iCol field)
  68451. ** then convert that term into a copy of the corresponding result set
  68452. ** column.
  68453. **
  68454. ** If any errors are detected, add an error message to pParse and
  68455. ** return non-zero. Return zero if no errors are seen.
  68456. */
  68457. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  68458. Parse *pParse, /* Parsing context. Leave error messages here */
  68459. Select *pSelect, /* The SELECT statement containing the clause */
  68460. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  68461. const char *zType /* "ORDER" or "GROUP" */
  68462. ){
  68463. int i;
  68464. sqlite3 *db = pParse->db;
  68465. ExprList *pEList;
  68466. struct ExprList_item *pItem;
  68467. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  68468. #if SQLITE_MAX_COLUMN
  68469. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  68470. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  68471. return 1;
  68472. }
  68473. #endif
  68474. pEList = pSelect->pEList;
  68475. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  68476. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  68477. if( pItem->iOrderByCol ){
  68478. if( pItem->iOrderByCol>pEList->nExpr ){
  68479. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  68480. return 1;
  68481. }
  68482. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  68483. }
  68484. }
  68485. return 0;
  68486. }
  68487. /*
  68488. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  68489. ** The Name context of the SELECT statement is pNC. zType is either
  68490. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  68491. **
  68492. ** This routine resolves each term of the clause into an expression.
  68493. ** If the order-by term is an integer I between 1 and N (where N is the
  68494. ** number of columns in the result set of the SELECT) then the expression
  68495. ** in the resolution is a copy of the I-th result-set expression. If
  68496. ** the order-by term is an identify that corresponds to the AS-name of
  68497. ** a result-set expression, then the term resolves to a copy of the
  68498. ** result-set expression. Otherwise, the expression is resolved in
  68499. ** the usual way - using sqlite3ResolveExprNames().
  68500. **
  68501. ** This routine returns the number of errors. If errors occur, then
  68502. ** an appropriate error message might be left in pParse. (OOM errors
  68503. ** excepted.)
  68504. */
  68505. static int resolveOrderGroupBy(
  68506. NameContext *pNC, /* The name context of the SELECT statement */
  68507. Select *pSelect, /* The SELECT statement holding pOrderBy */
  68508. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  68509. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  68510. ){
  68511. int i, j; /* Loop counters */
  68512. int iCol; /* Column number */
  68513. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  68514. Parse *pParse; /* Parsing context */
  68515. int nResult; /* Number of terms in the result set */
  68516. if( pOrderBy==0 ) return 0;
  68517. nResult = pSelect->pEList->nExpr;
  68518. pParse = pNC->pParse;
  68519. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  68520. Expr *pE = pItem->pExpr;
  68521. iCol = resolveAsName(pParse, pSelect->pEList, pE);
  68522. if( iCol>0 ){
  68523. /* If an AS-name match is found, mark this ORDER BY column as being
  68524. ** a copy of the iCol-th result-set column. The subsequent call to
  68525. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  68526. ** copy of the iCol-th result-set expression. */
  68527. pItem->iOrderByCol = (u16)iCol;
  68528. continue;
  68529. }
  68530. if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
  68531. /* The ORDER BY term is an integer constant. Again, set the column
  68532. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  68533. ** order-by term to a copy of the result-set expression */
  68534. if( iCol<1 || iCol>0xffff ){
  68535. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  68536. return 1;
  68537. }
  68538. pItem->iOrderByCol = (u16)iCol;
  68539. continue;
  68540. }
  68541. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  68542. pItem->iOrderByCol = 0;
  68543. if( sqlite3ResolveExprNames(pNC, pE) ){
  68544. return 1;
  68545. }
  68546. for(j=0; j<pSelect->pEList->nExpr; j++){
  68547. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
  68548. pItem->iOrderByCol = j+1;
  68549. }
  68550. }
  68551. }
  68552. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  68553. }
  68554. /*
  68555. ** Resolve names in the SELECT statement p and all of its descendents.
  68556. */
  68557. static int resolveSelectStep(Walker *pWalker, Select *p){
  68558. NameContext *pOuterNC; /* Context that contains this SELECT */
  68559. NameContext sNC; /* Name context of this SELECT */
  68560. int isCompound; /* True if p is a compound select */
  68561. int nCompound; /* Number of compound terms processed so far */
  68562. Parse *pParse; /* Parsing context */
  68563. ExprList *pEList; /* Result set expression list */
  68564. int i; /* Loop counter */
  68565. ExprList *pGroupBy; /* The GROUP BY clause */
  68566. Select *pLeftmost; /* Left-most of SELECT of a compound */
  68567. sqlite3 *db; /* Database connection */
  68568. assert( p!=0 );
  68569. if( p->selFlags & SF_Resolved ){
  68570. return WRC_Prune;
  68571. }
  68572. pOuterNC = pWalker->u.pNC;
  68573. pParse = pWalker->pParse;
  68574. db = pParse->db;
  68575. /* Normally sqlite3SelectExpand() will be called first and will have
  68576. ** already expanded this SELECT. However, if this is a subquery within
  68577. ** an expression, sqlite3ResolveExprNames() will be called without a
  68578. ** prior call to sqlite3SelectExpand(). When that happens, let
  68579. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  68580. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  68581. ** this routine in the correct order.
  68582. */
  68583. if( (p->selFlags & SF_Expanded)==0 ){
  68584. sqlite3SelectPrep(pParse, p, pOuterNC);
  68585. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  68586. }
  68587. isCompound = p->pPrior!=0;
  68588. nCompound = 0;
  68589. pLeftmost = p;
  68590. while( p ){
  68591. assert( (p->selFlags & SF_Expanded)!=0 );
  68592. assert( (p->selFlags & SF_Resolved)==0 );
  68593. p->selFlags |= SF_Resolved;
  68594. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  68595. ** are not allowed to refer to any names, so pass an empty NameContext.
  68596. */
  68597. memset(&sNC, 0, sizeof(sNC));
  68598. sNC.pParse = pParse;
  68599. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  68600. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  68601. return WRC_Abort;
  68602. }
  68603. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  68604. ** resolve the result-set expression list.
  68605. */
  68606. sNC.ncFlags = NC_AllowAgg;
  68607. sNC.pSrcList = p->pSrc;
  68608. sNC.pNext = pOuterNC;
  68609. /* Resolve names in the result set. */
  68610. pEList = p->pEList;
  68611. assert( pEList!=0 );
  68612. for(i=0; i<pEList->nExpr; i++){
  68613. Expr *pX = pEList->a[i].pExpr;
  68614. if( sqlite3ResolveExprNames(&sNC, pX) ){
  68615. return WRC_Abort;
  68616. }
  68617. }
  68618. /* Recursively resolve names in all subqueries
  68619. */
  68620. for(i=0; i<p->pSrc->nSrc; i++){
  68621. struct SrcList_item *pItem = &p->pSrc->a[i];
  68622. if( pItem->pSelect ){
  68623. NameContext *pNC; /* Used to iterate name contexts */
  68624. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  68625. const char *zSavedContext = pParse->zAuthContext;
  68626. /* Count the total number of references to pOuterNC and all of its
  68627. ** parent contexts. After resolving references to expressions in
  68628. ** pItem->pSelect, check if this value has changed. If so, then
  68629. ** SELECT statement pItem->pSelect must be correlated. Set the
  68630. ** pItem->isCorrelated flag if this is the case. */
  68631. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  68632. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  68633. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  68634. pParse->zAuthContext = zSavedContext;
  68635. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  68636. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  68637. assert( pItem->isCorrelated==0 && nRef<=0 );
  68638. pItem->isCorrelated = (nRef!=0);
  68639. }
  68640. }
  68641. /* If there are no aggregate functions in the result-set, and no GROUP BY
  68642. ** expression, do not allow aggregates in any of the other expressions.
  68643. */
  68644. assert( (p->selFlags & SF_Aggregate)==0 );
  68645. pGroupBy = p->pGroupBy;
  68646. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  68647. p->selFlags |= SF_Aggregate;
  68648. }else{
  68649. sNC.ncFlags &= ~NC_AllowAgg;
  68650. }
  68651. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  68652. */
  68653. if( p->pHaving && !pGroupBy ){
  68654. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  68655. return WRC_Abort;
  68656. }
  68657. /* Add the expression list to the name-context before parsing the
  68658. ** other expressions in the SELECT statement. This is so that
  68659. ** expressions in the WHERE clause (etc.) can refer to expressions by
  68660. ** aliases in the result set.
  68661. **
  68662. ** Minor point: If this is the case, then the expression will be
  68663. ** re-evaluated for each reference to it.
  68664. */
  68665. sNC.pEList = p->pEList;
  68666. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
  68667. sqlite3ResolveExprNames(&sNC, p->pHaving)
  68668. ){
  68669. return WRC_Abort;
  68670. }
  68671. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  68672. ** outer queries
  68673. */
  68674. sNC.pNext = 0;
  68675. sNC.ncFlags |= NC_AllowAgg;
  68676. /* Process the ORDER BY clause for singleton SELECT statements.
  68677. ** The ORDER BY clause for compounds SELECT statements is handled
  68678. ** below, after all of the result-sets for all of the elements of
  68679. ** the compound have been resolved.
  68680. */
  68681. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  68682. return WRC_Abort;
  68683. }
  68684. if( db->mallocFailed ){
  68685. return WRC_Abort;
  68686. }
  68687. /* Resolve the GROUP BY clause. At the same time, make sure
  68688. ** the GROUP BY clause does not contain aggregate functions.
  68689. */
  68690. if( pGroupBy ){
  68691. struct ExprList_item *pItem;
  68692. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  68693. return WRC_Abort;
  68694. }
  68695. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  68696. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  68697. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  68698. "the GROUP BY clause");
  68699. return WRC_Abort;
  68700. }
  68701. }
  68702. }
  68703. /* Advance to the next term of the compound
  68704. */
  68705. p = p->pPrior;
  68706. nCompound++;
  68707. }
  68708. /* Resolve the ORDER BY on a compound SELECT after all terms of
  68709. ** the compound have been resolved.
  68710. */
  68711. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  68712. return WRC_Abort;
  68713. }
  68714. return WRC_Prune;
  68715. }
  68716. /*
  68717. ** This routine walks an expression tree and resolves references to
  68718. ** table columns and result-set columns. At the same time, do error
  68719. ** checking on function usage and set a flag if any aggregate functions
  68720. ** are seen.
  68721. **
  68722. ** To resolve table columns references we look for nodes (or subtrees) of the
  68723. ** form X.Y.Z or Y.Z or just Z where
  68724. **
  68725. ** X: The name of a database. Ex: "main" or "temp" or
  68726. ** the symbolic name assigned to an ATTACH-ed database.
  68727. **
  68728. ** Y: The name of a table in a FROM clause. Or in a trigger
  68729. ** one of the special names "old" or "new".
  68730. **
  68731. ** Z: The name of a column in table Y.
  68732. **
  68733. ** The node at the root of the subtree is modified as follows:
  68734. **
  68735. ** Expr.op Changed to TK_COLUMN
  68736. ** Expr.pTab Points to the Table object for X.Y
  68737. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  68738. ** Expr.iTable The VDBE cursor number for X.Y
  68739. **
  68740. **
  68741. ** To resolve result-set references, look for expression nodes of the
  68742. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  68743. ** size of an AS clause in the result-set of a SELECT. The Z expression
  68744. ** is replaced by a copy of the left-hand side of the result-set expression.
  68745. ** Table-name and function resolution occurs on the substituted expression
  68746. ** tree. For example, in:
  68747. **
  68748. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  68749. **
  68750. ** The "x" term of the order by is replaced by "a+b" to render:
  68751. **
  68752. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  68753. **
  68754. ** Function calls are checked to make sure that the function is
  68755. ** defined and that the correct number of arguments are specified.
  68756. ** If the function is an aggregate function, then the NC_HasAgg flag is
  68757. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  68758. ** If an expression contains aggregate functions then the EP_Agg
  68759. ** property on the expression is set.
  68760. **
  68761. ** An error message is left in pParse if anything is amiss. The number
  68762. ** if errors is returned.
  68763. */
  68764. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  68765. NameContext *pNC, /* Namespace to resolve expressions in. */
  68766. Expr *pExpr /* The expression to be analyzed. */
  68767. ){
  68768. u8 savedHasAgg;
  68769. Walker w;
  68770. if( pExpr==0 ) return 0;
  68771. #if SQLITE_MAX_EXPR_DEPTH>0
  68772. {
  68773. Parse *pParse = pNC->pParse;
  68774. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  68775. return 1;
  68776. }
  68777. pParse->nHeight += pExpr->nHeight;
  68778. }
  68779. #endif
  68780. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  68781. pNC->ncFlags &= ~NC_HasAgg;
  68782. w.xExprCallback = resolveExprStep;
  68783. w.xSelectCallback = resolveSelectStep;
  68784. w.pParse = pNC->pParse;
  68785. w.u.pNC = pNC;
  68786. sqlite3WalkExpr(&w, pExpr);
  68787. #if SQLITE_MAX_EXPR_DEPTH>0
  68788. pNC->pParse->nHeight -= pExpr->nHeight;
  68789. #endif
  68790. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  68791. ExprSetProperty(pExpr, EP_Error);
  68792. }
  68793. if( pNC->ncFlags & NC_HasAgg ){
  68794. ExprSetProperty(pExpr, EP_Agg);
  68795. }else if( savedHasAgg ){
  68796. pNC->ncFlags |= NC_HasAgg;
  68797. }
  68798. return ExprHasProperty(pExpr, EP_Error);
  68799. }
  68800. /*
  68801. ** Resolve all names in all expressions of a SELECT and in all
  68802. ** decendents of the SELECT, including compounds off of p->pPrior,
  68803. ** subqueries in expressions, and subqueries used as FROM clause
  68804. ** terms.
  68805. **
  68806. ** See sqlite3ResolveExprNames() for a description of the kinds of
  68807. ** transformations that occur.
  68808. **
  68809. ** All SELECT statements should have been expanded using
  68810. ** sqlite3SelectExpand() prior to invoking this routine.
  68811. */
  68812. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  68813. Parse *pParse, /* The parser context */
  68814. Select *p, /* The SELECT statement being coded. */
  68815. NameContext *pOuterNC /* Name context for parent SELECT statement */
  68816. ){
  68817. Walker w;
  68818. assert( p!=0 );
  68819. w.xExprCallback = resolveExprStep;
  68820. w.xSelectCallback = resolveSelectStep;
  68821. w.pParse = pParse;
  68822. w.u.pNC = pOuterNC;
  68823. sqlite3WalkSelect(&w, p);
  68824. }
  68825. /************** End of resolve.c *********************************************/
  68826. /************** Begin file expr.c ********************************************/
  68827. /*
  68828. ** 2001 September 15
  68829. **
  68830. ** The author disclaims copyright to this source code. In place of
  68831. ** a legal notice, here is a blessing:
  68832. **
  68833. ** May you do good and not evil.
  68834. ** May you find forgiveness for yourself and forgive others.
  68835. ** May you share freely, never taking more than you give.
  68836. **
  68837. *************************************************************************
  68838. ** This file contains routines used for analyzing expressions and
  68839. ** for generating VDBE code that evaluates expressions in SQLite.
  68840. */
  68841. /*
  68842. ** Return the 'affinity' of the expression pExpr if any.
  68843. **
  68844. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  68845. ** or a sub-select with a column as the return value, then the
  68846. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  68847. ** indicating no affinity for the expression.
  68848. **
  68849. ** i.e. the WHERE clause expresssions in the following statements all
  68850. ** have an affinity:
  68851. **
  68852. ** CREATE TABLE t1(a);
  68853. ** SELECT * FROM t1 WHERE a;
  68854. ** SELECT a AS b FROM t1 WHERE b;
  68855. ** SELECT * FROM t1 WHERE (select a from t1);
  68856. */
  68857. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  68858. int op;
  68859. pExpr = sqlite3ExprSkipCollate(pExpr);
  68860. op = pExpr->op;
  68861. if( op==TK_SELECT ){
  68862. assert( pExpr->flags&EP_xIsSelect );
  68863. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  68864. }
  68865. #ifndef SQLITE_OMIT_CAST
  68866. if( op==TK_CAST ){
  68867. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68868. return sqlite3AffinityType(pExpr->u.zToken);
  68869. }
  68870. #endif
  68871. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  68872. && pExpr->pTab!=0
  68873. ){
  68874. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  68875. ** a TK_COLUMN but was previously evaluated and cached in a register */
  68876. int j = pExpr->iColumn;
  68877. if( j<0 ) return SQLITE_AFF_INTEGER;
  68878. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  68879. return pExpr->pTab->aCol[j].affinity;
  68880. }
  68881. return pExpr->affinity;
  68882. }
  68883. /*
  68884. ** Set the collating sequence for expression pExpr to be the collating
  68885. ** sequence named by pToken. Return a pointer to a new Expr node that
  68886. ** implements the COLLATE operator.
  68887. **
  68888. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  68889. ** and the pExpr parameter is returned unchanged.
  68890. */
  68891. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  68892. if( pCollName->n>0 ){
  68893. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  68894. if( pNew ){
  68895. pNew->pLeft = pExpr;
  68896. pNew->flags |= EP_Collate;
  68897. pExpr = pNew;
  68898. }
  68899. }
  68900. return pExpr;
  68901. }
  68902. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  68903. Token s;
  68904. assert( zC!=0 );
  68905. s.z = zC;
  68906. s.n = sqlite3Strlen30(s.z);
  68907. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  68908. }
  68909. /*
  68910. ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
  68911. ** an expression.
  68912. */
  68913. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  68914. while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
  68915. pExpr = pExpr->pLeft;
  68916. }
  68917. return pExpr;
  68918. }
  68919. /*
  68920. ** Return the collation sequence for the expression pExpr. If
  68921. ** there is no defined collating sequence, return NULL.
  68922. **
  68923. ** The collating sequence might be determined by a COLLATE operator
  68924. ** or by the presence of a column with a defined collating sequence.
  68925. ** COLLATE operators take first precedence. Left operands take
  68926. ** precedence over right operands.
  68927. */
  68928. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  68929. sqlite3 *db = pParse->db;
  68930. CollSeq *pColl = 0;
  68931. Expr *p = pExpr;
  68932. while( p ){
  68933. int op = p->op;
  68934. if( op==TK_CAST || op==TK_UPLUS ){
  68935. p = p->pLeft;
  68936. continue;
  68937. }
  68938. assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
  68939. if( op==TK_COLLATE ){
  68940. if( db->init.busy ){
  68941. /* Do not report errors when parsing while the schema */
  68942. pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
  68943. }else{
  68944. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  68945. }
  68946. break;
  68947. }
  68948. if( p->pTab!=0
  68949. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  68950. || op==TK_REGISTER || op==TK_TRIGGER)
  68951. ){
  68952. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  68953. ** a TK_COLUMN but was previously evaluated and cached in a register */
  68954. int j = p->iColumn;
  68955. if( j>=0 ){
  68956. const char *zColl = p->pTab->aCol[j].zColl;
  68957. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  68958. }
  68959. break;
  68960. }
  68961. if( p->flags & EP_Collate ){
  68962. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  68963. p = p->pLeft;
  68964. }else{
  68965. p = p->pRight;
  68966. }
  68967. }else{
  68968. break;
  68969. }
  68970. }
  68971. if( sqlite3CheckCollSeq(pParse, pColl) ){
  68972. pColl = 0;
  68973. }
  68974. return pColl;
  68975. }
  68976. /*
  68977. ** pExpr is an operand of a comparison operator. aff2 is the
  68978. ** type affinity of the other operand. This routine returns the
  68979. ** type affinity that should be used for the comparison operator.
  68980. */
  68981. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  68982. char aff1 = sqlite3ExprAffinity(pExpr);
  68983. if( aff1 && aff2 ){
  68984. /* Both sides of the comparison are columns. If one has numeric
  68985. ** affinity, use that. Otherwise use no affinity.
  68986. */
  68987. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  68988. return SQLITE_AFF_NUMERIC;
  68989. }else{
  68990. return SQLITE_AFF_NONE;
  68991. }
  68992. }else if( !aff1 && !aff2 ){
  68993. /* Neither side of the comparison is a column. Compare the
  68994. ** results directly.
  68995. */
  68996. return SQLITE_AFF_NONE;
  68997. }else{
  68998. /* One side is a column, the other is not. Use the columns affinity. */
  68999. assert( aff1==0 || aff2==0 );
  69000. return (aff1 + aff2);
  69001. }
  69002. }
  69003. /*
  69004. ** pExpr is a comparison operator. Return the type affinity that should
  69005. ** be applied to both operands prior to doing the comparison.
  69006. */
  69007. static char comparisonAffinity(Expr *pExpr){
  69008. char aff;
  69009. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  69010. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  69011. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  69012. assert( pExpr->pLeft );
  69013. aff = sqlite3ExprAffinity(pExpr->pLeft);
  69014. if( pExpr->pRight ){
  69015. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  69016. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  69017. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  69018. }else if( !aff ){
  69019. aff = SQLITE_AFF_NONE;
  69020. }
  69021. return aff;
  69022. }
  69023. /*
  69024. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  69025. ** idx_affinity is the affinity of an indexed column. Return true
  69026. ** if the index with affinity idx_affinity may be used to implement
  69027. ** the comparison in pExpr.
  69028. */
  69029. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  69030. char aff = comparisonAffinity(pExpr);
  69031. switch( aff ){
  69032. case SQLITE_AFF_NONE:
  69033. return 1;
  69034. case SQLITE_AFF_TEXT:
  69035. return idx_affinity==SQLITE_AFF_TEXT;
  69036. default:
  69037. return sqlite3IsNumericAffinity(idx_affinity);
  69038. }
  69039. }
  69040. /*
  69041. ** Return the P5 value that should be used for a binary comparison
  69042. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  69043. */
  69044. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  69045. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  69046. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  69047. return aff;
  69048. }
  69049. /*
  69050. ** Return a pointer to the collation sequence that should be used by
  69051. ** a binary comparison operator comparing pLeft and pRight.
  69052. **
  69053. ** If the left hand expression has a collating sequence type, then it is
  69054. ** used. Otherwise the collation sequence for the right hand expression
  69055. ** is used, or the default (BINARY) if neither expression has a collating
  69056. ** type.
  69057. **
  69058. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  69059. ** it is not considered.
  69060. */
  69061. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  69062. Parse *pParse,
  69063. Expr *pLeft,
  69064. Expr *pRight
  69065. ){
  69066. CollSeq *pColl;
  69067. assert( pLeft );
  69068. if( pLeft->flags & EP_Collate ){
  69069. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  69070. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  69071. pColl = sqlite3ExprCollSeq(pParse, pRight);
  69072. }else{
  69073. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  69074. if( !pColl ){
  69075. pColl = sqlite3ExprCollSeq(pParse, pRight);
  69076. }
  69077. }
  69078. return pColl;
  69079. }
  69080. /*
  69081. ** Generate code for a comparison operator.
  69082. */
  69083. static int codeCompare(
  69084. Parse *pParse, /* The parsing (and code generating) context */
  69085. Expr *pLeft, /* The left operand */
  69086. Expr *pRight, /* The right operand */
  69087. int opcode, /* The comparison opcode */
  69088. int in1, int in2, /* Register holding operands */
  69089. int dest, /* Jump here if true. */
  69090. int jumpIfNull /* If true, jump if either operand is NULL */
  69091. ){
  69092. int p5;
  69093. int addr;
  69094. CollSeq *p4;
  69095. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  69096. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  69097. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  69098. (void*)p4, P4_COLLSEQ);
  69099. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  69100. return addr;
  69101. }
  69102. #if SQLITE_MAX_EXPR_DEPTH>0
  69103. /*
  69104. ** Check that argument nHeight is less than or equal to the maximum
  69105. ** expression depth allowed. If it is not, leave an error message in
  69106. ** pParse.
  69107. */
  69108. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  69109. int rc = SQLITE_OK;
  69110. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  69111. if( nHeight>mxHeight ){
  69112. sqlite3ErrorMsg(pParse,
  69113. "Expression tree is too large (maximum depth %d)", mxHeight
  69114. );
  69115. rc = SQLITE_ERROR;
  69116. }
  69117. return rc;
  69118. }
  69119. /* The following three functions, heightOfExpr(), heightOfExprList()
  69120. ** and heightOfSelect(), are used to determine the maximum height
  69121. ** of any expression tree referenced by the structure passed as the
  69122. ** first argument.
  69123. **
  69124. ** If this maximum height is greater than the current value pointed
  69125. ** to by pnHeight, the second parameter, then set *pnHeight to that
  69126. ** value.
  69127. */
  69128. static void heightOfExpr(Expr *p, int *pnHeight){
  69129. if( p ){
  69130. if( p->nHeight>*pnHeight ){
  69131. *pnHeight = p->nHeight;
  69132. }
  69133. }
  69134. }
  69135. static void heightOfExprList(ExprList *p, int *pnHeight){
  69136. if( p ){
  69137. int i;
  69138. for(i=0; i<p->nExpr; i++){
  69139. heightOfExpr(p->a[i].pExpr, pnHeight);
  69140. }
  69141. }
  69142. }
  69143. static void heightOfSelect(Select *p, int *pnHeight){
  69144. if( p ){
  69145. heightOfExpr(p->pWhere, pnHeight);
  69146. heightOfExpr(p->pHaving, pnHeight);
  69147. heightOfExpr(p->pLimit, pnHeight);
  69148. heightOfExpr(p->pOffset, pnHeight);
  69149. heightOfExprList(p->pEList, pnHeight);
  69150. heightOfExprList(p->pGroupBy, pnHeight);
  69151. heightOfExprList(p->pOrderBy, pnHeight);
  69152. heightOfSelect(p->pPrior, pnHeight);
  69153. }
  69154. }
  69155. /*
  69156. ** Set the Expr.nHeight variable in the structure passed as an
  69157. ** argument. An expression with no children, Expr.pList or
  69158. ** Expr.pSelect member has a height of 1. Any other expression
  69159. ** has a height equal to the maximum height of any other
  69160. ** referenced Expr plus one.
  69161. */
  69162. static void exprSetHeight(Expr *p){
  69163. int nHeight = 0;
  69164. heightOfExpr(p->pLeft, &nHeight);
  69165. heightOfExpr(p->pRight, &nHeight);
  69166. if( ExprHasProperty(p, EP_xIsSelect) ){
  69167. heightOfSelect(p->x.pSelect, &nHeight);
  69168. }else{
  69169. heightOfExprList(p->x.pList, &nHeight);
  69170. }
  69171. p->nHeight = nHeight + 1;
  69172. }
  69173. /*
  69174. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  69175. ** the height is greater than the maximum allowed expression depth,
  69176. ** leave an error in pParse.
  69177. */
  69178. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  69179. exprSetHeight(p);
  69180. sqlite3ExprCheckHeight(pParse, p->nHeight);
  69181. }
  69182. /*
  69183. ** Return the maximum height of any expression tree referenced
  69184. ** by the select statement passed as an argument.
  69185. */
  69186. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  69187. int nHeight = 0;
  69188. heightOfSelect(p, &nHeight);
  69189. return nHeight;
  69190. }
  69191. #else
  69192. #define exprSetHeight(y)
  69193. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  69194. /*
  69195. ** This routine is the core allocator for Expr nodes.
  69196. **
  69197. ** Construct a new expression node and return a pointer to it. Memory
  69198. ** for this node and for the pToken argument is a single allocation
  69199. ** obtained from sqlite3DbMalloc(). The calling function
  69200. ** is responsible for making sure the node eventually gets freed.
  69201. **
  69202. ** If dequote is true, then the token (if it exists) is dequoted.
  69203. ** If dequote is false, no dequoting is performance. The deQuote
  69204. ** parameter is ignored if pToken is NULL or if the token does not
  69205. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  69206. ** then the EP_DblQuoted flag is set on the expression node.
  69207. **
  69208. ** Special case: If op==TK_INTEGER and pToken points to a string that
  69209. ** can be translated into a 32-bit integer, then the token is not
  69210. ** stored in u.zToken. Instead, the integer values is written
  69211. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  69212. ** is allocated to hold the integer text and the dequote flag is ignored.
  69213. */
  69214. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  69215. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  69216. int op, /* Expression opcode */
  69217. const Token *pToken, /* Token argument. Might be NULL */
  69218. int dequote /* True to dequote */
  69219. ){
  69220. Expr *pNew;
  69221. int nExtra = 0;
  69222. int iValue = 0;
  69223. if( pToken ){
  69224. if( op!=TK_INTEGER || pToken->z==0
  69225. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  69226. nExtra = pToken->n+1;
  69227. assert( iValue>=0 );
  69228. }
  69229. }
  69230. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  69231. if( pNew ){
  69232. pNew->op = (u8)op;
  69233. pNew->iAgg = -1;
  69234. if( pToken ){
  69235. if( nExtra==0 ){
  69236. pNew->flags |= EP_IntValue;
  69237. pNew->u.iValue = iValue;
  69238. }else{
  69239. int c;
  69240. pNew->u.zToken = (char*)&pNew[1];
  69241. assert( pToken->z!=0 || pToken->n==0 );
  69242. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  69243. pNew->u.zToken[pToken->n] = 0;
  69244. if( dequote && nExtra>=3
  69245. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  69246. sqlite3Dequote(pNew->u.zToken);
  69247. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  69248. }
  69249. }
  69250. }
  69251. #if SQLITE_MAX_EXPR_DEPTH>0
  69252. pNew->nHeight = 1;
  69253. #endif
  69254. }
  69255. return pNew;
  69256. }
  69257. /*
  69258. ** Allocate a new expression node from a zero-terminated token that has
  69259. ** already been dequoted.
  69260. */
  69261. SQLITE_PRIVATE Expr *sqlite3Expr(
  69262. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  69263. int op, /* Expression opcode */
  69264. const char *zToken /* Token argument. Might be NULL */
  69265. ){
  69266. Token x;
  69267. x.z = zToken;
  69268. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  69269. return sqlite3ExprAlloc(db, op, &x, 0);
  69270. }
  69271. /*
  69272. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  69273. **
  69274. ** If pRoot==NULL that means that a memory allocation error has occurred.
  69275. ** In that case, delete the subtrees pLeft and pRight.
  69276. */
  69277. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  69278. sqlite3 *db,
  69279. Expr *pRoot,
  69280. Expr *pLeft,
  69281. Expr *pRight
  69282. ){
  69283. if( pRoot==0 ){
  69284. assert( db->mallocFailed );
  69285. sqlite3ExprDelete(db, pLeft);
  69286. sqlite3ExprDelete(db, pRight);
  69287. }else{
  69288. if( pRight ){
  69289. pRoot->pRight = pRight;
  69290. pRoot->flags |= EP_Collate & pRight->flags;
  69291. }
  69292. if( pLeft ){
  69293. pRoot->pLeft = pLeft;
  69294. pRoot->flags |= EP_Collate & pLeft->flags;
  69295. }
  69296. exprSetHeight(pRoot);
  69297. }
  69298. }
  69299. /*
  69300. ** Allocate a Expr node which joins as many as two subtrees.
  69301. **
  69302. ** One or both of the subtrees can be NULL. Return a pointer to the new
  69303. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  69304. ** free the subtrees and return NULL.
  69305. */
  69306. SQLITE_PRIVATE Expr *sqlite3PExpr(
  69307. Parse *pParse, /* Parsing context */
  69308. int op, /* Expression opcode */
  69309. Expr *pLeft, /* Left operand */
  69310. Expr *pRight, /* Right operand */
  69311. const Token *pToken /* Argument token */
  69312. ){
  69313. Expr *p;
  69314. if( op==TK_AND && pLeft && pRight ){
  69315. /* Take advantage of short-circuit false optimization for AND */
  69316. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  69317. }else{
  69318. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  69319. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  69320. }
  69321. if( p ) {
  69322. sqlite3ExprCheckHeight(pParse, p->nHeight);
  69323. }
  69324. return p;
  69325. }
  69326. /*
  69327. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  69328. ** expression might be true. This is an optimization. If is OK to
  69329. ** return 0 here even if the expression really is always false (a
  69330. ** false negative). But it is a bug to return 1 if the expression
  69331. ** might be true in some rare circumstances (a false positive.)
  69332. **
  69333. ** Note that if the expression is part of conditional for a
  69334. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  69335. ** is it true or false, so always return 0.
  69336. */
  69337. static int exprAlwaysFalse(Expr *p){
  69338. int v = 0;
  69339. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  69340. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  69341. return v==0;
  69342. }
  69343. /*
  69344. ** Join two expressions using an AND operator. If either expression is
  69345. ** NULL, then just return the other expression.
  69346. **
  69347. ** If one side or the other of the AND is known to be false, then instead
  69348. ** of returning an AND expression, just return a constant expression with
  69349. ** a value of false.
  69350. */
  69351. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  69352. if( pLeft==0 ){
  69353. return pRight;
  69354. }else if( pRight==0 ){
  69355. return pLeft;
  69356. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  69357. sqlite3ExprDelete(db, pLeft);
  69358. sqlite3ExprDelete(db, pRight);
  69359. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  69360. }else{
  69361. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  69362. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  69363. return pNew;
  69364. }
  69365. }
  69366. /*
  69367. ** Construct a new expression node for a function with multiple
  69368. ** arguments.
  69369. */
  69370. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  69371. Expr *pNew;
  69372. sqlite3 *db = pParse->db;
  69373. assert( pToken );
  69374. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  69375. if( pNew==0 ){
  69376. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  69377. return 0;
  69378. }
  69379. pNew->x.pList = pList;
  69380. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  69381. sqlite3ExprSetHeight(pParse, pNew);
  69382. return pNew;
  69383. }
  69384. /*
  69385. ** Assign a variable number to an expression that encodes a wildcard
  69386. ** in the original SQL statement.
  69387. **
  69388. ** Wildcards consisting of a single "?" are assigned the next sequential
  69389. ** variable number.
  69390. **
  69391. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  69392. ** sure "nnn" is not too be to avoid a denial of service attack when
  69393. ** the SQL statement comes from an external source.
  69394. **
  69395. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  69396. ** as the previous instance of the same wildcard. Or if this is the first
  69397. ** instance of the wildcard, the next sequenial variable number is
  69398. ** assigned.
  69399. */
  69400. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  69401. sqlite3 *db = pParse->db;
  69402. const char *z;
  69403. if( pExpr==0 ) return;
  69404. assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  69405. z = pExpr->u.zToken;
  69406. assert( z!=0 );
  69407. assert( z[0]!=0 );
  69408. if( z[1]==0 ){
  69409. /* Wildcard of the form "?". Assign the next variable number */
  69410. assert( z[0]=='?' );
  69411. pExpr->iColumn = (ynVar)(++pParse->nVar);
  69412. }else{
  69413. ynVar x = 0;
  69414. u32 n = sqlite3Strlen30(z);
  69415. if( z[0]=='?' ){
  69416. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  69417. ** use it as the variable number */
  69418. i64 i;
  69419. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  69420. pExpr->iColumn = x = (ynVar)i;
  69421. testcase( i==0 );
  69422. testcase( i==1 );
  69423. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  69424. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  69425. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  69426. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  69427. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  69428. x = 0;
  69429. }
  69430. if( i>pParse->nVar ){
  69431. pParse->nVar = (int)i;
  69432. }
  69433. }else{
  69434. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  69435. ** number as the prior appearance of the same name, or if the name
  69436. ** has never appeared before, reuse the same variable number
  69437. */
  69438. ynVar i;
  69439. for(i=0; i<pParse->nzVar; i++){
  69440. if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
  69441. pExpr->iColumn = x = (ynVar)i+1;
  69442. break;
  69443. }
  69444. }
  69445. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  69446. }
  69447. if( x>0 ){
  69448. if( x>pParse->nzVar ){
  69449. char **a;
  69450. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  69451. if( a==0 ) return; /* Error reported through db->mallocFailed */
  69452. pParse->azVar = a;
  69453. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  69454. pParse->nzVar = x;
  69455. }
  69456. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  69457. sqlite3DbFree(db, pParse->azVar[x-1]);
  69458. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  69459. }
  69460. }
  69461. }
  69462. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  69463. sqlite3ErrorMsg(pParse, "too many SQL variables");
  69464. }
  69465. }
  69466. /*
  69467. ** Recursively delete an expression tree.
  69468. */
  69469. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  69470. if( p==0 ) return;
  69471. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  69472. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  69473. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  69474. sqlite3ExprDelete(db, p->pLeft);
  69475. sqlite3ExprDelete(db, p->pRight);
  69476. if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
  69477. sqlite3DbFree(db, p->u.zToken);
  69478. }
  69479. if( ExprHasProperty(p, EP_xIsSelect) ){
  69480. sqlite3SelectDelete(db, p->x.pSelect);
  69481. }else{
  69482. sqlite3ExprListDelete(db, p->x.pList);
  69483. }
  69484. }
  69485. if( !ExprHasProperty(p, EP_Static) ){
  69486. sqlite3DbFree(db, p);
  69487. }
  69488. }
  69489. /*
  69490. ** Return the number of bytes allocated for the expression structure
  69491. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  69492. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  69493. */
  69494. static int exprStructSize(Expr *p){
  69495. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  69496. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  69497. return EXPR_FULLSIZE;
  69498. }
  69499. /*
  69500. ** The dupedExpr*Size() routines each return the number of bytes required
  69501. ** to store a copy of an expression or expression tree. They differ in
  69502. ** how much of the tree is measured.
  69503. **
  69504. ** dupedExprStructSize() Size of only the Expr structure
  69505. ** dupedExprNodeSize() Size of Expr + space for token
  69506. ** dupedExprSize() Expr + token + subtree components
  69507. **
  69508. ***************************************************************************
  69509. **
  69510. ** The dupedExprStructSize() function returns two values OR-ed together:
  69511. ** (1) the space required for a copy of the Expr structure only and
  69512. ** (2) the EP_xxx flags that indicate what the structure size should be.
  69513. ** The return values is always one of:
  69514. **
  69515. ** EXPR_FULLSIZE
  69516. ** EXPR_REDUCEDSIZE | EP_Reduced
  69517. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  69518. **
  69519. ** The size of the structure can be found by masking the return value
  69520. ** of this routine with 0xfff. The flags can be found by masking the
  69521. ** return value with EP_Reduced|EP_TokenOnly.
  69522. **
  69523. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  69524. ** (unreduced) Expr objects as they or originally constructed by the parser.
  69525. ** During expression analysis, extra information is computed and moved into
  69526. ** later parts of teh Expr object and that extra information might get chopped
  69527. ** off if the expression is reduced. Note also that it does not work to
  69528. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  69529. ** to reduce a pristine expression tree from the parser. The implementation
  69530. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  69531. ** to enforce this constraint.
  69532. */
  69533. static int dupedExprStructSize(Expr *p, int flags){
  69534. int nSize;
  69535. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  69536. if( 0==(flags&EXPRDUP_REDUCE) ){
  69537. nSize = EXPR_FULLSIZE;
  69538. }else{
  69539. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  69540. assert( !ExprHasProperty(p, EP_FromJoin) );
  69541. assert( (p->flags2 & EP2_MallocedToken)==0 );
  69542. assert( (p->flags2 & EP2_Irreducible)==0 );
  69543. if( p->pLeft || p->pRight || p->x.pList ){
  69544. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  69545. }else{
  69546. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  69547. }
  69548. }
  69549. return nSize;
  69550. }
  69551. /*
  69552. ** This function returns the space in bytes required to store the copy
  69553. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  69554. ** string is defined.)
  69555. */
  69556. static int dupedExprNodeSize(Expr *p, int flags){
  69557. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  69558. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  69559. nByte += sqlite3Strlen30(p->u.zToken)+1;
  69560. }
  69561. return ROUND8(nByte);
  69562. }
  69563. /*
  69564. ** Return the number of bytes required to create a duplicate of the
  69565. ** expression passed as the first argument. The second argument is a
  69566. ** mask containing EXPRDUP_XXX flags.
  69567. **
  69568. ** The value returned includes space to create a copy of the Expr struct
  69569. ** itself and the buffer referred to by Expr.u.zToken, if any.
  69570. **
  69571. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  69572. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  69573. ** and Expr.pRight variables (but not for any structures pointed to or
  69574. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  69575. */
  69576. static int dupedExprSize(Expr *p, int flags){
  69577. int nByte = 0;
  69578. if( p ){
  69579. nByte = dupedExprNodeSize(p, flags);
  69580. if( flags&EXPRDUP_REDUCE ){
  69581. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  69582. }
  69583. }
  69584. return nByte;
  69585. }
  69586. /*
  69587. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  69588. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  69589. ** to store the copy of expression p, the copies of p->u.zToken
  69590. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  69591. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  69592. ** portion of the buffer copied into by this function.
  69593. */
  69594. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  69595. Expr *pNew = 0; /* Value to return */
  69596. if( p ){
  69597. const int isReduced = (flags&EXPRDUP_REDUCE);
  69598. u8 *zAlloc;
  69599. u32 staticFlag = 0;
  69600. assert( pzBuffer==0 || isReduced );
  69601. /* Figure out where to write the new Expr structure. */
  69602. if( pzBuffer ){
  69603. zAlloc = *pzBuffer;
  69604. staticFlag = EP_Static;
  69605. }else{
  69606. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  69607. }
  69608. pNew = (Expr *)zAlloc;
  69609. if( pNew ){
  69610. /* Set nNewSize to the size allocated for the structure pointed to
  69611. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  69612. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  69613. ** by the copy of the p->u.zToken string (if any).
  69614. */
  69615. const unsigned nStructSize = dupedExprStructSize(p, flags);
  69616. const int nNewSize = nStructSize & 0xfff;
  69617. int nToken;
  69618. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  69619. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  69620. }else{
  69621. nToken = 0;
  69622. }
  69623. if( isReduced ){
  69624. assert( ExprHasProperty(p, EP_Reduced)==0 );
  69625. memcpy(zAlloc, p, nNewSize);
  69626. }else{
  69627. int nSize = exprStructSize(p);
  69628. memcpy(zAlloc, p, nSize);
  69629. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  69630. }
  69631. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  69632. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
  69633. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  69634. pNew->flags |= staticFlag;
  69635. /* Copy the p->u.zToken string, if any. */
  69636. if( nToken ){
  69637. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  69638. memcpy(zToken, p->u.zToken, nToken);
  69639. }
  69640. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  69641. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  69642. if( ExprHasProperty(p, EP_xIsSelect) ){
  69643. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  69644. }else{
  69645. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  69646. }
  69647. }
  69648. /* Fill in pNew->pLeft and pNew->pRight. */
  69649. if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  69650. zAlloc += dupedExprNodeSize(p, flags);
  69651. if( ExprHasProperty(pNew, EP_Reduced) ){
  69652. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  69653. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  69654. }
  69655. if( pzBuffer ){
  69656. *pzBuffer = zAlloc;
  69657. }
  69658. }else{
  69659. pNew->flags2 = 0;
  69660. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  69661. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  69662. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  69663. }
  69664. }
  69665. }
  69666. }
  69667. return pNew;
  69668. }
  69669. /*
  69670. ** The following group of routines make deep copies of expressions,
  69671. ** expression lists, ID lists, and select statements. The copies can
  69672. ** be deleted (by being passed to their respective ...Delete() routines)
  69673. ** without effecting the originals.
  69674. **
  69675. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  69676. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  69677. ** by subsequent calls to sqlite*ListAppend() routines.
  69678. **
  69679. ** Any tables that the SrcList might point to are not duplicated.
  69680. **
  69681. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  69682. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  69683. ** truncated version of the usual Expr structure that will be stored as
  69684. ** part of the in-memory representation of the database schema.
  69685. */
  69686. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  69687. return exprDup(db, p, flags, 0);
  69688. }
  69689. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  69690. ExprList *pNew;
  69691. struct ExprList_item *pItem, *pOldItem;
  69692. int i;
  69693. if( p==0 ) return 0;
  69694. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  69695. if( pNew==0 ) return 0;
  69696. pNew->iECursor = 0;
  69697. pNew->nExpr = i = p->nExpr;
  69698. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  69699. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  69700. if( pItem==0 ){
  69701. sqlite3DbFree(db, pNew);
  69702. return 0;
  69703. }
  69704. pOldItem = p->a;
  69705. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  69706. Expr *pOldExpr = pOldItem->pExpr;
  69707. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  69708. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  69709. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  69710. pItem->sortOrder = pOldItem->sortOrder;
  69711. pItem->done = 0;
  69712. pItem->iOrderByCol = pOldItem->iOrderByCol;
  69713. pItem->iAlias = pOldItem->iAlias;
  69714. }
  69715. return pNew;
  69716. }
  69717. /*
  69718. ** If cursors, triggers, views and subqueries are all omitted from
  69719. ** the build, then none of the following routines, except for
  69720. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  69721. ** called with a NULL argument.
  69722. */
  69723. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  69724. || !defined(SQLITE_OMIT_SUBQUERY)
  69725. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  69726. SrcList *pNew;
  69727. int i;
  69728. int nByte;
  69729. if( p==0 ) return 0;
  69730. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  69731. pNew = sqlite3DbMallocRaw(db, nByte );
  69732. if( pNew==0 ) return 0;
  69733. pNew->nSrc = pNew->nAlloc = p->nSrc;
  69734. for(i=0; i<p->nSrc; i++){
  69735. struct SrcList_item *pNewItem = &pNew->a[i];
  69736. struct SrcList_item *pOldItem = &p->a[i];
  69737. Table *pTab;
  69738. pNewItem->pSchema = pOldItem->pSchema;
  69739. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  69740. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  69741. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  69742. pNewItem->jointype = pOldItem->jointype;
  69743. pNewItem->iCursor = pOldItem->iCursor;
  69744. pNewItem->addrFillSub = pOldItem->addrFillSub;
  69745. pNewItem->regReturn = pOldItem->regReturn;
  69746. pNewItem->isCorrelated = pOldItem->isCorrelated;
  69747. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  69748. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  69749. pNewItem->notIndexed = pOldItem->notIndexed;
  69750. pNewItem->pIndex = pOldItem->pIndex;
  69751. pTab = pNewItem->pTab = pOldItem->pTab;
  69752. if( pTab ){
  69753. pTab->nRef++;
  69754. }
  69755. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  69756. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  69757. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  69758. pNewItem->colUsed = pOldItem->colUsed;
  69759. }
  69760. return pNew;
  69761. }
  69762. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  69763. IdList *pNew;
  69764. int i;
  69765. if( p==0 ) return 0;
  69766. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  69767. if( pNew==0 ) return 0;
  69768. pNew->nId = p->nId;
  69769. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  69770. if( pNew->a==0 ){
  69771. sqlite3DbFree(db, pNew);
  69772. return 0;
  69773. }
  69774. /* Note that because the size of the allocation for p->a[] is not
  69775. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  69776. ** on the duplicate created by this function. */
  69777. for(i=0; i<p->nId; i++){
  69778. struct IdList_item *pNewItem = &pNew->a[i];
  69779. struct IdList_item *pOldItem = &p->a[i];
  69780. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  69781. pNewItem->idx = pOldItem->idx;
  69782. }
  69783. return pNew;
  69784. }
  69785. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  69786. Select *pNew, *pPrior;
  69787. if( p==0 ) return 0;
  69788. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  69789. if( pNew==0 ) return 0;
  69790. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  69791. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  69792. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  69793. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  69794. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  69795. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  69796. pNew->op = p->op;
  69797. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  69798. if( pPrior ) pPrior->pNext = pNew;
  69799. pNew->pNext = 0;
  69800. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  69801. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  69802. pNew->iLimit = 0;
  69803. pNew->iOffset = 0;
  69804. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  69805. pNew->pRightmost = 0;
  69806. pNew->addrOpenEphm[0] = -1;
  69807. pNew->addrOpenEphm[1] = -1;
  69808. pNew->addrOpenEphm[2] = -1;
  69809. return pNew;
  69810. }
  69811. #else
  69812. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  69813. assert( p==0 );
  69814. return 0;
  69815. }
  69816. #endif
  69817. /*
  69818. ** Add a new element to the end of an expression list. If pList is
  69819. ** initially NULL, then create a new expression list.
  69820. **
  69821. ** If a memory allocation error occurs, the entire list is freed and
  69822. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  69823. ** that the new entry was successfully appended.
  69824. */
  69825. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  69826. Parse *pParse, /* Parsing context */
  69827. ExprList *pList, /* List to which to append. Might be NULL */
  69828. Expr *pExpr /* Expression to be appended. Might be NULL */
  69829. ){
  69830. sqlite3 *db = pParse->db;
  69831. if( pList==0 ){
  69832. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  69833. if( pList==0 ){
  69834. goto no_mem;
  69835. }
  69836. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  69837. if( pList->a==0 ) goto no_mem;
  69838. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  69839. struct ExprList_item *a;
  69840. assert( pList->nExpr>0 );
  69841. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  69842. if( a==0 ){
  69843. goto no_mem;
  69844. }
  69845. pList->a = a;
  69846. }
  69847. assert( pList->a!=0 );
  69848. if( 1 ){
  69849. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  69850. memset(pItem, 0, sizeof(*pItem));
  69851. pItem->pExpr = pExpr;
  69852. }
  69853. return pList;
  69854. no_mem:
  69855. /* Avoid leaking memory if malloc has failed. */
  69856. sqlite3ExprDelete(db, pExpr);
  69857. sqlite3ExprListDelete(db, pList);
  69858. return 0;
  69859. }
  69860. /*
  69861. ** Set the ExprList.a[].zName element of the most recently added item
  69862. ** on the expression list.
  69863. **
  69864. ** pList might be NULL following an OOM error. But pName should never be
  69865. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  69866. ** is set.
  69867. */
  69868. SQLITE_PRIVATE void sqlite3ExprListSetName(
  69869. Parse *pParse, /* Parsing context */
  69870. ExprList *pList, /* List to which to add the span. */
  69871. Token *pName, /* Name to be added */
  69872. int dequote /* True to cause the name to be dequoted */
  69873. ){
  69874. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  69875. if( pList ){
  69876. struct ExprList_item *pItem;
  69877. assert( pList->nExpr>0 );
  69878. pItem = &pList->a[pList->nExpr-1];
  69879. assert( pItem->zName==0 );
  69880. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  69881. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  69882. }
  69883. }
  69884. /*
  69885. ** Set the ExprList.a[].zSpan element of the most recently added item
  69886. ** on the expression list.
  69887. **
  69888. ** pList might be NULL following an OOM error. But pSpan should never be
  69889. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  69890. ** is set.
  69891. */
  69892. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  69893. Parse *pParse, /* Parsing context */
  69894. ExprList *pList, /* List to which to add the span. */
  69895. ExprSpan *pSpan /* The span to be added */
  69896. ){
  69897. sqlite3 *db = pParse->db;
  69898. assert( pList!=0 || db->mallocFailed!=0 );
  69899. if( pList ){
  69900. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  69901. assert( pList->nExpr>0 );
  69902. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  69903. sqlite3DbFree(db, pItem->zSpan);
  69904. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  69905. (int)(pSpan->zEnd - pSpan->zStart));
  69906. }
  69907. }
  69908. /*
  69909. ** If the expression list pEList contains more than iLimit elements,
  69910. ** leave an error message in pParse.
  69911. */
  69912. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  69913. Parse *pParse,
  69914. ExprList *pEList,
  69915. const char *zObject
  69916. ){
  69917. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  69918. testcase( pEList && pEList->nExpr==mx );
  69919. testcase( pEList && pEList->nExpr==mx+1 );
  69920. if( pEList && pEList->nExpr>mx ){
  69921. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  69922. }
  69923. }
  69924. /*
  69925. ** Delete an entire expression list.
  69926. */
  69927. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  69928. int i;
  69929. struct ExprList_item *pItem;
  69930. if( pList==0 ) return;
  69931. assert( pList->a!=0 || pList->nExpr==0 );
  69932. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  69933. sqlite3ExprDelete(db, pItem->pExpr);
  69934. sqlite3DbFree(db, pItem->zName);
  69935. sqlite3DbFree(db, pItem->zSpan);
  69936. }
  69937. sqlite3DbFree(db, pList->a);
  69938. sqlite3DbFree(db, pList);
  69939. }
  69940. /*
  69941. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  69942. ** to an integer. These routines are checking an expression to see
  69943. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  69944. ** not constant.
  69945. **
  69946. ** These callback routines are used to implement the following:
  69947. **
  69948. ** sqlite3ExprIsConstant()
  69949. ** sqlite3ExprIsConstantNotJoin()
  69950. ** sqlite3ExprIsConstantOrFunction()
  69951. **
  69952. */
  69953. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  69954. /* If pWalker->u.i is 3 then any term of the expression that comes from
  69955. ** the ON or USING clauses of a join disqualifies the expression
  69956. ** from being considered constant. */
  69957. if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
  69958. pWalker->u.i = 0;
  69959. return WRC_Abort;
  69960. }
  69961. switch( pExpr->op ){
  69962. /* Consider functions to be constant if all their arguments are constant
  69963. ** and pWalker->u.i==2 */
  69964. case TK_FUNCTION:
  69965. if( pWalker->u.i==2 ) return 0;
  69966. /* Fall through */
  69967. case TK_ID:
  69968. case TK_COLUMN:
  69969. case TK_AGG_FUNCTION:
  69970. case TK_AGG_COLUMN:
  69971. testcase( pExpr->op==TK_ID );
  69972. testcase( pExpr->op==TK_COLUMN );
  69973. testcase( pExpr->op==TK_AGG_FUNCTION );
  69974. testcase( pExpr->op==TK_AGG_COLUMN );
  69975. pWalker->u.i = 0;
  69976. return WRC_Abort;
  69977. default:
  69978. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  69979. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  69980. return WRC_Continue;
  69981. }
  69982. }
  69983. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  69984. UNUSED_PARAMETER(NotUsed);
  69985. pWalker->u.i = 0;
  69986. return WRC_Abort;
  69987. }
  69988. static int exprIsConst(Expr *p, int initFlag){
  69989. Walker w;
  69990. w.u.i = initFlag;
  69991. w.xExprCallback = exprNodeIsConstant;
  69992. w.xSelectCallback = selectNodeIsConstant;
  69993. sqlite3WalkExpr(&w, p);
  69994. return w.u.i;
  69995. }
  69996. /*
  69997. ** Walk an expression tree. Return 1 if the expression is constant
  69998. ** and 0 if it involves variables or function calls.
  69999. **
  70000. ** For the purposes of this function, a double-quoted string (ex: "abc")
  70001. ** is considered a variable but a single-quoted string (ex: 'abc') is
  70002. ** a constant.
  70003. */
  70004. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  70005. return exprIsConst(p, 1);
  70006. }
  70007. /*
  70008. ** Walk an expression tree. Return 1 if the expression is constant
  70009. ** that does no originate from the ON or USING clauses of a join.
  70010. ** Return 0 if it involves variables or function calls or terms from
  70011. ** an ON or USING clause.
  70012. */
  70013. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  70014. return exprIsConst(p, 3);
  70015. }
  70016. /*
  70017. ** Walk an expression tree. Return 1 if the expression is constant
  70018. ** or a function call with constant arguments. Return and 0 if there
  70019. ** are any variables.
  70020. **
  70021. ** For the purposes of this function, a double-quoted string (ex: "abc")
  70022. ** is considered a variable but a single-quoted string (ex: 'abc') is
  70023. ** a constant.
  70024. */
  70025. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  70026. return exprIsConst(p, 2);
  70027. }
  70028. /*
  70029. ** If the expression p codes a constant integer that is small enough
  70030. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  70031. ** in *pValue. If the expression is not an integer or if it is too big
  70032. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  70033. */
  70034. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  70035. int rc = 0;
  70036. /* If an expression is an integer literal that fits in a signed 32-bit
  70037. ** integer, then the EP_IntValue flag will have already been set */
  70038. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  70039. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  70040. if( p->flags & EP_IntValue ){
  70041. *pValue = p->u.iValue;
  70042. return 1;
  70043. }
  70044. switch( p->op ){
  70045. case TK_UPLUS: {
  70046. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  70047. break;
  70048. }
  70049. case TK_UMINUS: {
  70050. int v;
  70051. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  70052. *pValue = -v;
  70053. rc = 1;
  70054. }
  70055. break;
  70056. }
  70057. default: break;
  70058. }
  70059. return rc;
  70060. }
  70061. /*
  70062. ** Return FALSE if there is no chance that the expression can be NULL.
  70063. **
  70064. ** If the expression might be NULL or if the expression is too complex
  70065. ** to tell return TRUE.
  70066. **
  70067. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  70068. ** when we know that a value cannot be NULL. Hence, a false positive
  70069. ** (returning TRUE when in fact the expression can never be NULL) might
  70070. ** be a small performance hit but is otherwise harmless. On the other
  70071. ** hand, a false negative (returning FALSE when the result could be NULL)
  70072. ** will likely result in an incorrect answer. So when in doubt, return
  70073. ** TRUE.
  70074. */
  70075. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  70076. u8 op;
  70077. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  70078. op = p->op;
  70079. if( op==TK_REGISTER ) op = p->op2;
  70080. switch( op ){
  70081. case TK_INTEGER:
  70082. case TK_STRING:
  70083. case TK_FLOAT:
  70084. case TK_BLOB:
  70085. return 0;
  70086. default:
  70087. return 1;
  70088. }
  70089. }
  70090. /*
  70091. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  70092. ** to location iDest if the value in iReg is NULL. The value in iReg
  70093. ** was computed by pExpr. If we can look at pExpr at compile-time and
  70094. ** determine that it can never generate a NULL, then the OP_IsNull operation
  70095. ** can be omitted.
  70096. */
  70097. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  70098. Vdbe *v, /* The VDBE under construction */
  70099. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  70100. int iReg, /* Test the value in this register for NULL */
  70101. int iDest /* Jump here if the value is null */
  70102. ){
  70103. if( sqlite3ExprCanBeNull(pExpr) ){
  70104. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  70105. }
  70106. }
  70107. /*
  70108. ** Return TRUE if the given expression is a constant which would be
  70109. ** unchanged by OP_Affinity with the affinity given in the second
  70110. ** argument.
  70111. **
  70112. ** This routine is used to determine if the OP_Affinity operation
  70113. ** can be omitted. When in doubt return FALSE. A false negative
  70114. ** is harmless. A false positive, however, can result in the wrong
  70115. ** answer.
  70116. */
  70117. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  70118. u8 op;
  70119. if( aff==SQLITE_AFF_NONE ) return 1;
  70120. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  70121. op = p->op;
  70122. if( op==TK_REGISTER ) op = p->op2;
  70123. switch( op ){
  70124. case TK_INTEGER: {
  70125. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  70126. }
  70127. case TK_FLOAT: {
  70128. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  70129. }
  70130. case TK_STRING: {
  70131. return aff==SQLITE_AFF_TEXT;
  70132. }
  70133. case TK_BLOB: {
  70134. return 1;
  70135. }
  70136. case TK_COLUMN: {
  70137. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  70138. return p->iColumn<0
  70139. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  70140. }
  70141. default: {
  70142. return 0;
  70143. }
  70144. }
  70145. }
  70146. /*
  70147. ** Return TRUE if the given string is a row-id column name.
  70148. */
  70149. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  70150. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  70151. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  70152. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  70153. return 0;
  70154. }
  70155. /*
  70156. ** Return true if we are able to the IN operator optimization on a
  70157. ** query of the form
  70158. **
  70159. ** x IN (SELECT ...)
  70160. **
  70161. ** Where the SELECT... clause is as specified by the parameter to this
  70162. ** routine.
  70163. **
  70164. ** The Select object passed in has already been preprocessed and no
  70165. ** errors have been found.
  70166. */
  70167. #ifndef SQLITE_OMIT_SUBQUERY
  70168. static int isCandidateForInOpt(Select *p){
  70169. SrcList *pSrc;
  70170. ExprList *pEList;
  70171. Table *pTab;
  70172. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  70173. if( p->pPrior ) return 0; /* Not a compound SELECT */
  70174. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  70175. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  70176. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  70177. return 0; /* No DISTINCT keyword and no aggregate functions */
  70178. }
  70179. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  70180. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  70181. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  70182. if( p->pWhere ) return 0; /* Has no WHERE clause */
  70183. pSrc = p->pSrc;
  70184. assert( pSrc!=0 );
  70185. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  70186. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  70187. pTab = pSrc->a[0].pTab;
  70188. if( NEVER(pTab==0) ) return 0;
  70189. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  70190. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  70191. pEList = p->pEList;
  70192. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  70193. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  70194. return 1;
  70195. }
  70196. #endif /* SQLITE_OMIT_SUBQUERY */
  70197. /*
  70198. ** Code an OP_Once instruction and allocate space for its flag. Return the
  70199. ** address of the new instruction.
  70200. */
  70201. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  70202. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  70203. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  70204. }
  70205. /*
  70206. ** This function is used by the implementation of the IN (...) operator.
  70207. ** The pX parameter is the expression on the RHS of the IN operator, which
  70208. ** might be either a list of expressions or a subquery.
  70209. **
  70210. ** The job of this routine is to find or create a b-tree object that can
  70211. ** be used either to test for membership in the RHS set or to iterate through
  70212. ** all members of the RHS set, skipping duplicates.
  70213. **
  70214. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  70215. ** and pX->iTable is set to the index of that cursor.
  70216. **
  70217. ** The returned value of this function indicates the b-tree type, as follows:
  70218. **
  70219. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  70220. ** IN_INDEX_INDEX - The cursor was opened on a database index.
  70221. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  70222. ** populated epheremal table.
  70223. **
  70224. ** An existing b-tree might be used if the RHS expression pX is a simple
  70225. ** subquery such as:
  70226. **
  70227. ** SELECT <column> FROM <table>
  70228. **
  70229. ** If the RHS of the IN operator is a list or a more complex subquery, then
  70230. ** an ephemeral table might need to be generated from the RHS and then
  70231. ** pX->iTable made to point to the ephermeral table instead of an
  70232. ** existing table.
  70233. **
  70234. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  70235. ** through the set members, skipping any duplicates. In this case an
  70236. ** epheremal table must be used unless the selected <column> is guaranteed
  70237. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  70238. ** has a UNIQUE constraint or UNIQUE index.
  70239. **
  70240. ** If the prNotFound parameter is not 0, then the b-tree will be used
  70241. ** for fast set membership tests. In this case an epheremal table must
  70242. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  70243. ** be found with <column> as its left-most column.
  70244. **
  70245. ** When the b-tree is being used for membership tests, the calling function
  70246. ** needs to know whether or not the structure contains an SQL NULL
  70247. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  70248. ** If there is any chance that the (...) might contain a NULL value at
  70249. ** runtime, then a register is allocated and the register number written
  70250. ** to *prNotFound. If there is no chance that the (...) contains a
  70251. ** NULL value, then *prNotFound is left unchanged.
  70252. **
  70253. ** If a register is allocated and its location stored in *prNotFound, then
  70254. ** its initial value is NULL. If the (...) does not remain constant
  70255. ** for the duration of the query (i.e. the SELECT within the (...)
  70256. ** is a correlated subquery) then the value of the allocated register is
  70257. ** reset to NULL each time the subquery is rerun. This allows the
  70258. ** caller to use vdbe code equivalent to the following:
  70259. **
  70260. ** if( register==NULL ){
  70261. ** has_null = <test if data structure contains null>
  70262. ** register = 1
  70263. ** }
  70264. **
  70265. ** in order to avoid running the <test if data structure contains null>
  70266. ** test more often than is necessary.
  70267. */
  70268. #ifndef SQLITE_OMIT_SUBQUERY
  70269. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  70270. Select *p; /* SELECT to the right of IN operator */
  70271. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  70272. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  70273. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  70274. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  70275. assert( pX->op==TK_IN );
  70276. /* Check to see if an existing table or index can be used to
  70277. ** satisfy the query. This is preferable to generating a new
  70278. ** ephemeral table.
  70279. */
  70280. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  70281. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  70282. sqlite3 *db = pParse->db; /* Database connection */
  70283. Table *pTab; /* Table <table>. */
  70284. Expr *pExpr; /* Expression <column> */
  70285. int iCol; /* Index of column <column> */
  70286. int iDb; /* Database idx for pTab */
  70287. assert( p ); /* Because of isCandidateForInOpt(p) */
  70288. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  70289. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  70290. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  70291. pTab = p->pSrc->a[0].pTab;
  70292. pExpr = p->pEList->a[0].pExpr;
  70293. iCol = pExpr->iColumn;
  70294. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  70295. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70296. sqlite3CodeVerifySchema(pParse, iDb);
  70297. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  70298. /* This function is only called from two places. In both cases the vdbe
  70299. ** has already been allocated. So assume sqlite3GetVdbe() is always
  70300. ** successful here.
  70301. */
  70302. assert(v);
  70303. if( iCol<0 ){
  70304. int iAddr;
  70305. iAddr = sqlite3CodeOnce(pParse);
  70306. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  70307. eType = IN_INDEX_ROWID;
  70308. sqlite3VdbeJumpHere(v, iAddr);
  70309. }else{
  70310. Index *pIdx; /* Iterator variable */
  70311. /* The collation sequence used by the comparison. If an index is to
  70312. ** be used in place of a temp-table, it must be ordered according
  70313. ** to this collation sequence. */
  70314. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  70315. /* Check that the affinity that will be used to perform the
  70316. ** comparison is the same as the affinity of the column. If
  70317. ** it is not, it is not possible to use any index.
  70318. */
  70319. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  70320. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  70321. if( (pIdx->aiColumn[0]==iCol)
  70322. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  70323. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  70324. ){
  70325. int iAddr;
  70326. char *pKey;
  70327. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  70328. iAddr = sqlite3CodeOnce(pParse);
  70329. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  70330. pKey,P4_KEYINFO_HANDOFF);
  70331. VdbeComment((v, "%s", pIdx->zName));
  70332. eType = IN_INDEX_INDEX;
  70333. sqlite3VdbeJumpHere(v, iAddr);
  70334. if( prNotFound && !pTab->aCol[iCol].notNull ){
  70335. *prNotFound = ++pParse->nMem;
  70336. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  70337. }
  70338. }
  70339. }
  70340. }
  70341. }
  70342. if( eType==0 ){
  70343. /* Could not found an existing table or index to use as the RHS b-tree.
  70344. ** We will have to generate an ephemeral table to do the job.
  70345. */
  70346. double savedNQueryLoop = pParse->nQueryLoop;
  70347. int rMayHaveNull = 0;
  70348. eType = IN_INDEX_EPH;
  70349. if( prNotFound ){
  70350. *prNotFound = rMayHaveNull = ++pParse->nMem;
  70351. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  70352. }else{
  70353. testcase( pParse->nQueryLoop>(double)1 );
  70354. pParse->nQueryLoop = (double)1;
  70355. if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
  70356. eType = IN_INDEX_ROWID;
  70357. }
  70358. }
  70359. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  70360. pParse->nQueryLoop = savedNQueryLoop;
  70361. }else{
  70362. pX->iTable = iTab;
  70363. }
  70364. return eType;
  70365. }
  70366. #endif
  70367. /*
  70368. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  70369. ** or IN operators. Examples:
  70370. **
  70371. ** (SELECT a FROM b) -- subquery
  70372. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  70373. ** x IN (4,5,11) -- IN operator with list on right-hand side
  70374. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  70375. **
  70376. ** The pExpr parameter describes the expression that contains the IN
  70377. ** operator or subquery.
  70378. **
  70379. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  70380. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  70381. ** to some integer key column of a table B-Tree. In this case, use an
  70382. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  70383. ** (slower) variable length keys B-Tree.
  70384. **
  70385. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  70386. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  70387. ** Furthermore, the IN is in a WHERE clause and that we really want
  70388. ** to iterate over the RHS of the IN operator in order to quickly locate
  70389. ** all corresponding LHS elements. All this routine does is initialize
  70390. ** the register given by rMayHaveNull to NULL. Calling routines will take
  70391. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  70392. **
  70393. ** If rMayHaveNull is zero, that means that the subquery is being used
  70394. ** for membership testing only. There is no need to initialize any
  70395. ** registers to indicate the presense or absence of NULLs on the RHS.
  70396. **
  70397. ** For a SELECT or EXISTS operator, return the register that holds the
  70398. ** result. For IN operators or if an error occurs, the return value is 0.
  70399. */
  70400. #ifndef SQLITE_OMIT_SUBQUERY
  70401. SQLITE_PRIVATE int sqlite3CodeSubselect(
  70402. Parse *pParse, /* Parsing context */
  70403. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  70404. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  70405. int isRowid /* If true, LHS of IN operator is a rowid */
  70406. ){
  70407. int testAddr = -1; /* One-time test address */
  70408. int rReg = 0; /* Register storing resulting */
  70409. Vdbe *v = sqlite3GetVdbe(pParse);
  70410. if( NEVER(v==0) ) return 0;
  70411. sqlite3ExprCachePush(pParse);
  70412. /* This code must be run in its entirety every time it is encountered
  70413. ** if any of the following is true:
  70414. **
  70415. ** * The right-hand side is a correlated subquery
  70416. ** * The right-hand side is an expression list containing variables
  70417. ** * We are inside a trigger
  70418. **
  70419. ** If all of the above are false, then we can run this code just once
  70420. ** save the results, and reuse the same result on subsequent invocations.
  70421. */
  70422. if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
  70423. testAddr = sqlite3CodeOnce(pParse);
  70424. }
  70425. #ifndef SQLITE_OMIT_EXPLAIN
  70426. if( pParse->explain==2 ){
  70427. char *zMsg = sqlite3MPrintf(
  70428. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  70429. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  70430. );
  70431. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  70432. }
  70433. #endif
  70434. switch( pExpr->op ){
  70435. case TK_IN: {
  70436. char affinity; /* Affinity of the LHS of the IN */
  70437. KeyInfo keyInfo; /* Keyinfo for the generated table */
  70438. static u8 sortOrder = 0; /* Fake aSortOrder for keyInfo */
  70439. int addr; /* Address of OP_OpenEphemeral instruction */
  70440. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  70441. if( rMayHaveNull ){
  70442. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  70443. }
  70444. affinity = sqlite3ExprAffinity(pLeft);
  70445. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  70446. ** expression it is handled the same way. An ephemeral table is
  70447. ** filled with single-field index keys representing the results
  70448. ** from the SELECT or the <exprlist>.
  70449. **
  70450. ** If the 'x' expression is a column value, or the SELECT...
  70451. ** statement returns a column value, then the affinity of that
  70452. ** column is used to build the index keys. If both 'x' and the
  70453. ** SELECT... statement are columns, then numeric affinity is used
  70454. ** if either column has NUMERIC or INTEGER affinity. If neither
  70455. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  70456. ** is used.
  70457. */
  70458. pExpr->iTable = pParse->nTab++;
  70459. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  70460. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  70461. memset(&keyInfo, 0, sizeof(keyInfo));
  70462. keyInfo.nField = 1;
  70463. keyInfo.aSortOrder = &sortOrder;
  70464. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  70465. /* Case 1: expr IN (SELECT ...)
  70466. **
  70467. ** Generate code to write the results of the select into the temporary
  70468. ** table allocated and opened above.
  70469. */
  70470. SelectDest dest;
  70471. ExprList *pEList;
  70472. assert( !isRowid );
  70473. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  70474. dest.affSdst = (u8)affinity;
  70475. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  70476. pExpr->x.pSelect->iLimit = 0;
  70477. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  70478. return 0;
  70479. }
  70480. pEList = pExpr->x.pSelect->pEList;
  70481. if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
  70482. keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  70483. pEList->a[0].pExpr);
  70484. }
  70485. }else if( ALWAYS(pExpr->x.pList!=0) ){
  70486. /* Case 2: expr IN (exprlist)
  70487. **
  70488. ** For each expression, build an index key from the evaluation and
  70489. ** store it in the temporary table. If <expr> is a column, then use
  70490. ** that columns affinity when building index keys. If <expr> is not
  70491. ** a column, use numeric affinity.
  70492. */
  70493. int i;
  70494. ExprList *pList = pExpr->x.pList;
  70495. struct ExprList_item *pItem;
  70496. int r1, r2, r3;
  70497. if( !affinity ){
  70498. affinity = SQLITE_AFF_NONE;
  70499. }
  70500. keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  70501. keyInfo.aSortOrder = &sortOrder;
  70502. /* Loop through each expression in <exprlist>. */
  70503. r1 = sqlite3GetTempReg(pParse);
  70504. r2 = sqlite3GetTempReg(pParse);
  70505. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  70506. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  70507. Expr *pE2 = pItem->pExpr;
  70508. int iValToIns;
  70509. /* If the expression is not constant then we will need to
  70510. ** disable the test that was generated above that makes sure
  70511. ** this code only executes once. Because for a non-constant
  70512. ** expression we need to rerun this code each time.
  70513. */
  70514. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  70515. sqlite3VdbeChangeToNoop(v, testAddr);
  70516. testAddr = -1;
  70517. }
  70518. /* Evaluate the expression and insert it into the temp table */
  70519. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  70520. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  70521. }else{
  70522. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  70523. if( isRowid ){
  70524. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  70525. sqlite3VdbeCurrentAddr(v)+2);
  70526. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  70527. }else{
  70528. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  70529. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  70530. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  70531. }
  70532. }
  70533. }
  70534. sqlite3ReleaseTempReg(pParse, r1);
  70535. sqlite3ReleaseTempReg(pParse, r2);
  70536. }
  70537. if( !isRowid ){
  70538. sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
  70539. }
  70540. break;
  70541. }
  70542. case TK_EXISTS:
  70543. case TK_SELECT:
  70544. default: {
  70545. /* If this has to be a scalar SELECT. Generate code to put the
  70546. ** value of this select in a memory cell and record the number
  70547. ** of the memory cell in iColumn. If this is an EXISTS, write
  70548. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  70549. ** and record that memory cell in iColumn.
  70550. */
  70551. Select *pSel; /* SELECT statement to encode */
  70552. SelectDest dest; /* How to deal with SELECt result */
  70553. testcase( pExpr->op==TK_EXISTS );
  70554. testcase( pExpr->op==TK_SELECT );
  70555. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  70556. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  70557. pSel = pExpr->x.pSelect;
  70558. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  70559. if( pExpr->op==TK_SELECT ){
  70560. dest.eDest = SRT_Mem;
  70561. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  70562. VdbeComment((v, "Init subquery result"));
  70563. }else{
  70564. dest.eDest = SRT_Exists;
  70565. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  70566. VdbeComment((v, "Init EXISTS result"));
  70567. }
  70568. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  70569. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  70570. &sqlite3IntTokens[1]);
  70571. pSel->iLimit = 0;
  70572. if( sqlite3Select(pParse, pSel, &dest) ){
  70573. return 0;
  70574. }
  70575. rReg = dest.iSDParm;
  70576. ExprSetIrreducible(pExpr);
  70577. break;
  70578. }
  70579. }
  70580. if( testAddr>=0 ){
  70581. sqlite3VdbeJumpHere(v, testAddr);
  70582. }
  70583. sqlite3ExprCachePop(pParse, 1);
  70584. return rReg;
  70585. }
  70586. #endif /* SQLITE_OMIT_SUBQUERY */
  70587. #ifndef SQLITE_OMIT_SUBQUERY
  70588. /*
  70589. ** Generate code for an IN expression.
  70590. **
  70591. ** x IN (SELECT ...)
  70592. ** x IN (value, value, ...)
  70593. **
  70594. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  70595. ** is an array of zero or more values. The expression is true if the LHS is
  70596. ** contained within the RHS. The value of the expression is unknown (NULL)
  70597. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  70598. ** RHS contains one or more NULL values.
  70599. **
  70600. ** This routine generates code will jump to destIfFalse if the LHS is not
  70601. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  70602. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  70603. ** within the RHS then fall through.
  70604. */
  70605. static void sqlite3ExprCodeIN(
  70606. Parse *pParse, /* Parsing and code generating context */
  70607. Expr *pExpr, /* The IN expression */
  70608. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  70609. int destIfNull /* Jump here if the results are unknown due to NULLs */
  70610. ){
  70611. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  70612. char affinity; /* Comparison affinity to use */
  70613. int eType; /* Type of the RHS */
  70614. int r1; /* Temporary use register */
  70615. Vdbe *v; /* Statement under construction */
  70616. /* Compute the RHS. After this step, the table with cursor
  70617. ** pExpr->iTable will contains the values that make up the RHS.
  70618. */
  70619. v = pParse->pVdbe;
  70620. assert( v!=0 ); /* OOM detected prior to this routine */
  70621. VdbeNoopComment((v, "begin IN expr"));
  70622. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  70623. /* Figure out the affinity to use to create a key from the results
  70624. ** of the expression. affinityStr stores a static string suitable for
  70625. ** P4 of OP_MakeRecord.
  70626. */
  70627. affinity = comparisonAffinity(pExpr);
  70628. /* Code the LHS, the <expr> from "<expr> IN (...)".
  70629. */
  70630. sqlite3ExprCachePush(pParse);
  70631. r1 = sqlite3GetTempReg(pParse);
  70632. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  70633. /* If the LHS is NULL, then the result is either false or NULL depending
  70634. ** on whether the RHS is empty or not, respectively.
  70635. */
  70636. if( destIfNull==destIfFalse ){
  70637. /* Shortcut for the common case where the false and NULL outcomes are
  70638. ** the same. */
  70639. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  70640. }else{
  70641. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  70642. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  70643. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  70644. sqlite3VdbeJumpHere(v, addr1);
  70645. }
  70646. if( eType==IN_INDEX_ROWID ){
  70647. /* In this case, the RHS is the ROWID of table b-tree
  70648. */
  70649. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  70650. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  70651. }else{
  70652. /* In this case, the RHS is an index b-tree.
  70653. */
  70654. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  70655. /* If the set membership test fails, then the result of the
  70656. ** "x IN (...)" expression must be either 0 or NULL. If the set
  70657. ** contains no NULL values, then the result is 0. If the set
  70658. ** contains one or more NULL values, then the result of the
  70659. ** expression is also NULL.
  70660. */
  70661. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  70662. /* This branch runs if it is known at compile time that the RHS
  70663. ** cannot contain NULL values. This happens as the result
  70664. ** of a "NOT NULL" constraint in the database schema.
  70665. **
  70666. ** Also run this branch if NULL is equivalent to FALSE
  70667. ** for this particular IN operator.
  70668. */
  70669. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  70670. }else{
  70671. /* In this branch, the RHS of the IN might contain a NULL and
  70672. ** the presence of a NULL on the RHS makes a difference in the
  70673. ** outcome.
  70674. */
  70675. int j1, j2, j3;
  70676. /* First check to see if the LHS is contained in the RHS. If so,
  70677. ** then the presence of NULLs in the RHS does not matter, so jump
  70678. ** over all of the code that follows.
  70679. */
  70680. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  70681. /* Here we begin generating code that runs if the LHS is not
  70682. ** contained within the RHS. Generate additional code that
  70683. ** tests the RHS for NULLs. If the RHS contains a NULL then
  70684. ** jump to destIfNull. If there are no NULLs in the RHS then
  70685. ** jump to destIfFalse.
  70686. */
  70687. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  70688. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  70689. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  70690. sqlite3VdbeJumpHere(v, j3);
  70691. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  70692. sqlite3VdbeJumpHere(v, j2);
  70693. /* Jump to the appropriate target depending on whether or not
  70694. ** the RHS contains a NULL
  70695. */
  70696. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  70697. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  70698. /* The OP_Found at the top of this branch jumps here when true,
  70699. ** causing the overall IN expression evaluation to fall through.
  70700. */
  70701. sqlite3VdbeJumpHere(v, j1);
  70702. }
  70703. }
  70704. sqlite3ReleaseTempReg(pParse, r1);
  70705. sqlite3ExprCachePop(pParse, 1);
  70706. VdbeComment((v, "end IN expr"));
  70707. }
  70708. #endif /* SQLITE_OMIT_SUBQUERY */
  70709. /*
  70710. ** Duplicate an 8-byte value
  70711. */
  70712. static char *dup8bytes(Vdbe *v, const char *in){
  70713. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  70714. if( out ){
  70715. memcpy(out, in, 8);
  70716. }
  70717. return out;
  70718. }
  70719. #ifndef SQLITE_OMIT_FLOATING_POINT
  70720. /*
  70721. ** Generate an instruction that will put the floating point
  70722. ** value described by z[0..n-1] into register iMem.
  70723. **
  70724. ** The z[] string will probably not be zero-terminated. But the
  70725. ** z[n] character is guaranteed to be something that does not look
  70726. ** like the continuation of the number.
  70727. */
  70728. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  70729. if( ALWAYS(z!=0) ){
  70730. double value;
  70731. char *zV;
  70732. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  70733. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  70734. if( negateFlag ) value = -value;
  70735. zV = dup8bytes(v, (char*)&value);
  70736. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  70737. }
  70738. }
  70739. #endif
  70740. /*
  70741. ** Generate an instruction that will put the integer describe by
  70742. ** text z[0..n-1] into register iMem.
  70743. **
  70744. ** Expr.u.zToken is always UTF8 and zero-terminated.
  70745. */
  70746. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  70747. Vdbe *v = pParse->pVdbe;
  70748. if( pExpr->flags & EP_IntValue ){
  70749. int i = pExpr->u.iValue;
  70750. assert( i>=0 );
  70751. if( negFlag ) i = -i;
  70752. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  70753. }else{
  70754. int c;
  70755. i64 value;
  70756. const char *z = pExpr->u.zToken;
  70757. assert( z!=0 );
  70758. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  70759. if( c==0 || (c==2 && negFlag) ){
  70760. char *zV;
  70761. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  70762. zV = dup8bytes(v, (char*)&value);
  70763. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  70764. }else{
  70765. #ifdef SQLITE_OMIT_FLOATING_POINT
  70766. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  70767. #else
  70768. codeReal(v, z, negFlag, iMem);
  70769. #endif
  70770. }
  70771. }
  70772. }
  70773. /*
  70774. ** Clear a cache entry.
  70775. */
  70776. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  70777. if( p->tempReg ){
  70778. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  70779. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  70780. }
  70781. p->tempReg = 0;
  70782. }
  70783. }
  70784. /*
  70785. ** Record in the column cache that a particular column from a
  70786. ** particular table is stored in a particular register.
  70787. */
  70788. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  70789. int i;
  70790. int minLru;
  70791. int idxLru;
  70792. struct yColCache *p;
  70793. assert( iReg>0 ); /* Register numbers are always positive */
  70794. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  70795. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  70796. ** for testing only - to verify that SQLite always gets the same answer
  70797. ** with and without the column cache.
  70798. */
  70799. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  70800. /* First replace any existing entry.
  70801. **
  70802. ** Actually, the way the column cache is currently used, we are guaranteed
  70803. ** that the object will never already be in cache. Verify this guarantee.
  70804. */
  70805. #ifndef NDEBUG
  70806. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70807. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  70808. }
  70809. #endif
  70810. /* Find an empty slot and replace it */
  70811. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70812. if( p->iReg==0 ){
  70813. p->iLevel = pParse->iCacheLevel;
  70814. p->iTable = iTab;
  70815. p->iColumn = iCol;
  70816. p->iReg = iReg;
  70817. p->tempReg = 0;
  70818. p->lru = pParse->iCacheCnt++;
  70819. return;
  70820. }
  70821. }
  70822. /* Replace the last recently used */
  70823. minLru = 0x7fffffff;
  70824. idxLru = -1;
  70825. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70826. if( p->lru<minLru ){
  70827. idxLru = i;
  70828. minLru = p->lru;
  70829. }
  70830. }
  70831. if( ALWAYS(idxLru>=0) ){
  70832. p = &pParse->aColCache[idxLru];
  70833. p->iLevel = pParse->iCacheLevel;
  70834. p->iTable = iTab;
  70835. p->iColumn = iCol;
  70836. p->iReg = iReg;
  70837. p->tempReg = 0;
  70838. p->lru = pParse->iCacheCnt++;
  70839. return;
  70840. }
  70841. }
  70842. /*
  70843. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  70844. ** Purge the range of registers from the column cache.
  70845. */
  70846. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  70847. int i;
  70848. int iLast = iReg + nReg - 1;
  70849. struct yColCache *p;
  70850. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70851. int r = p->iReg;
  70852. if( r>=iReg && r<=iLast ){
  70853. cacheEntryClear(pParse, p);
  70854. p->iReg = 0;
  70855. }
  70856. }
  70857. }
  70858. /*
  70859. ** Remember the current column cache context. Any new entries added
  70860. ** added to the column cache after this call are removed when the
  70861. ** corresponding pop occurs.
  70862. */
  70863. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  70864. pParse->iCacheLevel++;
  70865. }
  70866. /*
  70867. ** Remove from the column cache any entries that were added since the
  70868. ** the previous N Push operations. In other words, restore the cache
  70869. ** to the state it was in N Pushes ago.
  70870. */
  70871. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  70872. int i;
  70873. struct yColCache *p;
  70874. assert( N>0 );
  70875. assert( pParse->iCacheLevel>=N );
  70876. pParse->iCacheLevel -= N;
  70877. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70878. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  70879. cacheEntryClear(pParse, p);
  70880. p->iReg = 0;
  70881. }
  70882. }
  70883. }
  70884. /*
  70885. ** When a cached column is reused, make sure that its register is
  70886. ** no longer available as a temp register. ticket #3879: that same
  70887. ** register might be in the cache in multiple places, so be sure to
  70888. ** get them all.
  70889. */
  70890. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  70891. int i;
  70892. struct yColCache *p;
  70893. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70894. if( p->iReg==iReg ){
  70895. p->tempReg = 0;
  70896. }
  70897. }
  70898. }
  70899. /*
  70900. ** Generate code to extract the value of the iCol-th column of a table.
  70901. */
  70902. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  70903. Vdbe *v, /* The VDBE under construction */
  70904. Table *pTab, /* The table containing the value */
  70905. int iTabCur, /* The cursor for this table */
  70906. int iCol, /* Index of the column to extract */
  70907. int regOut /* Extract the valud into this register */
  70908. ){
  70909. if( iCol<0 || iCol==pTab->iPKey ){
  70910. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  70911. }else{
  70912. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  70913. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  70914. }
  70915. if( iCol>=0 ){
  70916. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  70917. }
  70918. }
  70919. /*
  70920. ** Generate code that will extract the iColumn-th column from
  70921. ** table pTab and store the column value in a register. An effort
  70922. ** is made to store the column value in register iReg, but this is
  70923. ** not guaranteed. The location of the column value is returned.
  70924. **
  70925. ** There must be an open cursor to pTab in iTable when this routine
  70926. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  70927. */
  70928. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  70929. Parse *pParse, /* Parsing and code generating context */
  70930. Table *pTab, /* Description of the table we are reading from */
  70931. int iColumn, /* Index of the table column */
  70932. int iTable, /* The cursor pointing to the table */
  70933. int iReg, /* Store results here */
  70934. u8 p5 /* P5 value for OP_Column */
  70935. ){
  70936. Vdbe *v = pParse->pVdbe;
  70937. int i;
  70938. struct yColCache *p;
  70939. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70940. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  70941. p->lru = pParse->iCacheCnt++;
  70942. sqlite3ExprCachePinRegister(pParse, p->iReg);
  70943. return p->iReg;
  70944. }
  70945. }
  70946. assert( v!=0 );
  70947. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  70948. if( p5 ){
  70949. sqlite3VdbeChangeP5(v, p5);
  70950. }else{
  70951. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  70952. }
  70953. return iReg;
  70954. }
  70955. /*
  70956. ** Clear all column cache entries.
  70957. */
  70958. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  70959. int i;
  70960. struct yColCache *p;
  70961. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70962. if( p->iReg ){
  70963. cacheEntryClear(pParse, p);
  70964. p->iReg = 0;
  70965. }
  70966. }
  70967. }
  70968. /*
  70969. ** Record the fact that an affinity change has occurred on iCount
  70970. ** registers starting with iStart.
  70971. */
  70972. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  70973. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  70974. }
  70975. /*
  70976. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  70977. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  70978. */
  70979. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  70980. int i;
  70981. struct yColCache *p;
  70982. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  70983. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  70984. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  70985. int x = p->iReg;
  70986. if( x>=iFrom && x<iFrom+nReg ){
  70987. p->iReg += iTo-iFrom;
  70988. }
  70989. }
  70990. }
  70991. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  70992. /*
  70993. ** Return true if any register in the range iFrom..iTo (inclusive)
  70994. ** is used as part of the column cache.
  70995. **
  70996. ** This routine is used within assert() and testcase() macros only
  70997. ** and does not appear in a normal build.
  70998. */
  70999. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  71000. int i;
  71001. struct yColCache *p;
  71002. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  71003. int r = p->iReg;
  71004. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  71005. }
  71006. return 0;
  71007. }
  71008. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  71009. /*
  71010. ** Generate code into the current Vdbe to evaluate the given
  71011. ** expression. Attempt to store the results in register "target".
  71012. ** Return the register where results are stored.
  71013. **
  71014. ** With this routine, there is no guarantee that results will
  71015. ** be stored in target. The result might be stored in some other
  71016. ** register if it is convenient to do so. The calling function
  71017. ** must check the return code and move the results to the desired
  71018. ** register.
  71019. */
  71020. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  71021. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  71022. int op; /* The opcode being coded */
  71023. int inReg = target; /* Results stored in register inReg */
  71024. int regFree1 = 0; /* If non-zero free this temporary register */
  71025. int regFree2 = 0; /* If non-zero free this temporary register */
  71026. int r1, r2, r3, r4; /* Various register numbers */
  71027. sqlite3 *db = pParse->db; /* The database connection */
  71028. assert( target>0 && target<=pParse->nMem );
  71029. if( v==0 ){
  71030. assert( pParse->db->mallocFailed );
  71031. return 0;
  71032. }
  71033. if( pExpr==0 ){
  71034. op = TK_NULL;
  71035. }else{
  71036. op = pExpr->op;
  71037. }
  71038. switch( op ){
  71039. case TK_AGG_COLUMN: {
  71040. AggInfo *pAggInfo = pExpr->pAggInfo;
  71041. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  71042. if( !pAggInfo->directMode ){
  71043. assert( pCol->iMem>0 );
  71044. inReg = pCol->iMem;
  71045. break;
  71046. }else if( pAggInfo->useSortingIdx ){
  71047. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  71048. pCol->iSorterColumn, target);
  71049. break;
  71050. }
  71051. /* Otherwise, fall thru into the TK_COLUMN case */
  71052. }
  71053. case TK_COLUMN: {
  71054. if( pExpr->iTable<0 ){
  71055. /* This only happens when coding check constraints */
  71056. assert( pParse->ckBase>0 );
  71057. inReg = pExpr->iColumn + pParse->ckBase;
  71058. }else{
  71059. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  71060. pExpr->iColumn, pExpr->iTable, target,
  71061. pExpr->op2);
  71062. }
  71063. break;
  71064. }
  71065. case TK_INTEGER: {
  71066. codeInteger(pParse, pExpr, 0, target);
  71067. break;
  71068. }
  71069. #ifndef SQLITE_OMIT_FLOATING_POINT
  71070. case TK_FLOAT: {
  71071. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71072. codeReal(v, pExpr->u.zToken, 0, target);
  71073. break;
  71074. }
  71075. #endif
  71076. case TK_STRING: {
  71077. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71078. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  71079. break;
  71080. }
  71081. case TK_NULL: {
  71082. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  71083. break;
  71084. }
  71085. #ifndef SQLITE_OMIT_BLOB_LITERAL
  71086. case TK_BLOB: {
  71087. int n;
  71088. const char *z;
  71089. char *zBlob;
  71090. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71091. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  71092. assert( pExpr->u.zToken[1]=='\'' );
  71093. z = &pExpr->u.zToken[2];
  71094. n = sqlite3Strlen30(z) - 1;
  71095. assert( z[n]=='\'' );
  71096. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  71097. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  71098. break;
  71099. }
  71100. #endif
  71101. case TK_VARIABLE: {
  71102. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71103. assert( pExpr->u.zToken!=0 );
  71104. assert( pExpr->u.zToken[0]!=0 );
  71105. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  71106. if( pExpr->u.zToken[1]!=0 ){
  71107. assert( pExpr->u.zToken[0]=='?'
  71108. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  71109. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  71110. }
  71111. break;
  71112. }
  71113. case TK_REGISTER: {
  71114. inReg = pExpr->iTable;
  71115. break;
  71116. }
  71117. case TK_AS: {
  71118. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  71119. break;
  71120. }
  71121. #ifndef SQLITE_OMIT_CAST
  71122. case TK_CAST: {
  71123. /* Expressions of the form: CAST(pLeft AS token) */
  71124. int aff, to_op;
  71125. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  71126. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71127. aff = sqlite3AffinityType(pExpr->u.zToken);
  71128. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  71129. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  71130. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  71131. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  71132. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  71133. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  71134. testcase( to_op==OP_ToText );
  71135. testcase( to_op==OP_ToBlob );
  71136. testcase( to_op==OP_ToNumeric );
  71137. testcase( to_op==OP_ToInt );
  71138. testcase( to_op==OP_ToReal );
  71139. if( inReg!=target ){
  71140. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  71141. inReg = target;
  71142. }
  71143. sqlite3VdbeAddOp1(v, to_op, inReg);
  71144. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  71145. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  71146. break;
  71147. }
  71148. #endif /* SQLITE_OMIT_CAST */
  71149. case TK_LT:
  71150. case TK_LE:
  71151. case TK_GT:
  71152. case TK_GE:
  71153. case TK_NE:
  71154. case TK_EQ: {
  71155. assert( TK_LT==OP_Lt );
  71156. assert( TK_LE==OP_Le );
  71157. assert( TK_GT==OP_Gt );
  71158. assert( TK_GE==OP_Ge );
  71159. assert( TK_EQ==OP_Eq );
  71160. assert( TK_NE==OP_Ne );
  71161. testcase( op==TK_LT );
  71162. testcase( op==TK_LE );
  71163. testcase( op==TK_GT );
  71164. testcase( op==TK_GE );
  71165. testcase( op==TK_EQ );
  71166. testcase( op==TK_NE );
  71167. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  71168. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  71169. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  71170. r1, r2, inReg, SQLITE_STOREP2);
  71171. testcase( regFree1==0 );
  71172. testcase( regFree2==0 );
  71173. break;
  71174. }
  71175. case TK_IS:
  71176. case TK_ISNOT: {
  71177. testcase( op==TK_IS );
  71178. testcase( op==TK_ISNOT );
  71179. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  71180. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  71181. op = (op==TK_IS) ? TK_EQ : TK_NE;
  71182. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  71183. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  71184. testcase( regFree1==0 );
  71185. testcase( regFree2==0 );
  71186. break;
  71187. }
  71188. case TK_AND:
  71189. case TK_OR:
  71190. case TK_PLUS:
  71191. case TK_STAR:
  71192. case TK_MINUS:
  71193. case TK_REM:
  71194. case TK_BITAND:
  71195. case TK_BITOR:
  71196. case TK_SLASH:
  71197. case TK_LSHIFT:
  71198. case TK_RSHIFT:
  71199. case TK_CONCAT: {
  71200. assert( TK_AND==OP_And );
  71201. assert( TK_OR==OP_Or );
  71202. assert( TK_PLUS==OP_Add );
  71203. assert( TK_MINUS==OP_Subtract );
  71204. assert( TK_REM==OP_Remainder );
  71205. assert( TK_BITAND==OP_BitAnd );
  71206. assert( TK_BITOR==OP_BitOr );
  71207. assert( TK_SLASH==OP_Divide );
  71208. assert( TK_LSHIFT==OP_ShiftLeft );
  71209. assert( TK_RSHIFT==OP_ShiftRight );
  71210. assert( TK_CONCAT==OP_Concat );
  71211. testcase( op==TK_AND );
  71212. testcase( op==TK_OR );
  71213. testcase( op==TK_PLUS );
  71214. testcase( op==TK_MINUS );
  71215. testcase( op==TK_REM );
  71216. testcase( op==TK_BITAND );
  71217. testcase( op==TK_BITOR );
  71218. testcase( op==TK_SLASH );
  71219. testcase( op==TK_LSHIFT );
  71220. testcase( op==TK_RSHIFT );
  71221. testcase( op==TK_CONCAT );
  71222. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  71223. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  71224. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  71225. testcase( regFree1==0 );
  71226. testcase( regFree2==0 );
  71227. break;
  71228. }
  71229. case TK_UMINUS: {
  71230. Expr *pLeft = pExpr->pLeft;
  71231. assert( pLeft );
  71232. if( pLeft->op==TK_INTEGER ){
  71233. codeInteger(pParse, pLeft, 1, target);
  71234. #ifndef SQLITE_OMIT_FLOATING_POINT
  71235. }else if( pLeft->op==TK_FLOAT ){
  71236. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71237. codeReal(v, pLeft->u.zToken, 1, target);
  71238. #endif
  71239. }else{
  71240. regFree1 = r1 = sqlite3GetTempReg(pParse);
  71241. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  71242. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  71243. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  71244. testcase( regFree2==0 );
  71245. }
  71246. inReg = target;
  71247. break;
  71248. }
  71249. case TK_BITNOT:
  71250. case TK_NOT: {
  71251. assert( TK_BITNOT==OP_BitNot );
  71252. assert( TK_NOT==OP_Not );
  71253. testcase( op==TK_BITNOT );
  71254. testcase( op==TK_NOT );
  71255. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  71256. testcase( regFree1==0 );
  71257. inReg = target;
  71258. sqlite3VdbeAddOp2(v, op, r1, inReg);
  71259. break;
  71260. }
  71261. case TK_ISNULL:
  71262. case TK_NOTNULL: {
  71263. int addr;
  71264. assert( TK_ISNULL==OP_IsNull );
  71265. assert( TK_NOTNULL==OP_NotNull );
  71266. testcase( op==TK_ISNULL );
  71267. testcase( op==TK_NOTNULL );
  71268. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  71269. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  71270. testcase( regFree1==0 );
  71271. addr = sqlite3VdbeAddOp1(v, op, r1);
  71272. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  71273. sqlite3VdbeJumpHere(v, addr);
  71274. break;
  71275. }
  71276. case TK_AGG_FUNCTION: {
  71277. AggInfo *pInfo = pExpr->pAggInfo;
  71278. if( pInfo==0 ){
  71279. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71280. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  71281. }else{
  71282. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  71283. }
  71284. break;
  71285. }
  71286. case TK_CONST_FUNC:
  71287. case TK_FUNCTION: {
  71288. ExprList *pFarg; /* List of function arguments */
  71289. int nFarg; /* Number of function arguments */
  71290. FuncDef *pDef; /* The function definition object */
  71291. int nId; /* Length of the function name in bytes */
  71292. const char *zId; /* The function name */
  71293. int constMask = 0; /* Mask of function arguments that are constant */
  71294. int i; /* Loop counter */
  71295. u8 enc = ENC(db); /* The text encoding used by this database */
  71296. CollSeq *pColl = 0; /* A collating sequence */
  71297. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  71298. testcase( op==TK_CONST_FUNC );
  71299. testcase( op==TK_FUNCTION );
  71300. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
  71301. pFarg = 0;
  71302. }else{
  71303. pFarg = pExpr->x.pList;
  71304. }
  71305. nFarg = pFarg ? pFarg->nExpr : 0;
  71306. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71307. zId = pExpr->u.zToken;
  71308. nId = sqlite3Strlen30(zId);
  71309. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  71310. if( pDef==0 ){
  71311. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  71312. break;
  71313. }
  71314. /* Attempt a direct implementation of the built-in COALESCE() and
  71315. ** IFNULL() functions. This avoids unnecessary evalation of
  71316. ** arguments past the first non-NULL argument.
  71317. */
  71318. if( pDef->flags & SQLITE_FUNC_COALESCE ){
  71319. int endCoalesce = sqlite3VdbeMakeLabel(v);
  71320. assert( nFarg>=2 );
  71321. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  71322. for(i=1; i<nFarg; i++){
  71323. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  71324. sqlite3ExprCacheRemove(pParse, target, 1);
  71325. sqlite3ExprCachePush(pParse);
  71326. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  71327. sqlite3ExprCachePop(pParse, 1);
  71328. }
  71329. sqlite3VdbeResolveLabel(v, endCoalesce);
  71330. break;
  71331. }
  71332. if( pFarg ){
  71333. r1 = sqlite3GetTempRange(pParse, nFarg);
  71334. /* For length() and typeof() functions with a column argument,
  71335. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  71336. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  71337. ** loading.
  71338. */
  71339. if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  71340. u8 exprOp;
  71341. assert( nFarg==1 );
  71342. assert( pFarg->a[0].pExpr!=0 );
  71343. exprOp = pFarg->a[0].pExpr->op;
  71344. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  71345. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  71346. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  71347. testcase( pDef->flags==SQLITE_FUNC_LENGTH );
  71348. pFarg->a[0].pExpr->op2 = pDef->flags;
  71349. }
  71350. }
  71351. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  71352. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  71353. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  71354. }else{
  71355. r1 = 0;
  71356. }
  71357. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71358. /* Possibly overload the function if the first argument is
  71359. ** a virtual table column.
  71360. **
  71361. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  71362. ** second argument, not the first, as the argument to test to
  71363. ** see if it is a column in a virtual table. This is done because
  71364. ** the left operand of infix functions (the operand we want to
  71365. ** control overloading) ends up as the second argument to the
  71366. ** function. The expression "A glob B" is equivalent to
  71367. ** "glob(B,A). We want to use the A in "A glob B" to test
  71368. ** for function overloading. But we use the B term in "glob(B,A)".
  71369. */
  71370. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  71371. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  71372. }else if( nFarg>0 ){
  71373. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  71374. }
  71375. #endif
  71376. for(i=0; i<nFarg; i++){
  71377. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  71378. constMask |= (1<<i);
  71379. }
  71380. if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  71381. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  71382. }
  71383. }
  71384. if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
  71385. if( !pColl ) pColl = db->pDfltColl;
  71386. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  71387. }
  71388. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  71389. (char*)pDef, P4_FUNCDEF);
  71390. sqlite3VdbeChangeP5(v, (u8)nFarg);
  71391. if( nFarg ){
  71392. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  71393. }
  71394. break;
  71395. }
  71396. #ifndef SQLITE_OMIT_SUBQUERY
  71397. case TK_EXISTS:
  71398. case TK_SELECT: {
  71399. testcase( op==TK_EXISTS );
  71400. testcase( op==TK_SELECT );
  71401. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  71402. break;
  71403. }
  71404. case TK_IN: {
  71405. int destIfFalse = sqlite3VdbeMakeLabel(v);
  71406. int destIfNull = sqlite3VdbeMakeLabel(v);
  71407. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  71408. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  71409. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  71410. sqlite3VdbeResolveLabel(v, destIfFalse);
  71411. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  71412. sqlite3VdbeResolveLabel(v, destIfNull);
  71413. break;
  71414. }
  71415. #endif /* SQLITE_OMIT_SUBQUERY */
  71416. /*
  71417. ** x BETWEEN y AND z
  71418. **
  71419. ** This is equivalent to
  71420. **
  71421. ** x>=y AND x<=z
  71422. **
  71423. ** X is stored in pExpr->pLeft.
  71424. ** Y is stored in pExpr->pList->a[0].pExpr.
  71425. ** Z is stored in pExpr->pList->a[1].pExpr.
  71426. */
  71427. case TK_BETWEEN: {
  71428. Expr *pLeft = pExpr->pLeft;
  71429. struct ExprList_item *pLItem = pExpr->x.pList->a;
  71430. Expr *pRight = pLItem->pExpr;
  71431. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  71432. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  71433. testcase( regFree1==0 );
  71434. testcase( regFree2==0 );
  71435. r3 = sqlite3GetTempReg(pParse);
  71436. r4 = sqlite3GetTempReg(pParse);
  71437. codeCompare(pParse, pLeft, pRight, OP_Ge,
  71438. r1, r2, r3, SQLITE_STOREP2);
  71439. pLItem++;
  71440. pRight = pLItem->pExpr;
  71441. sqlite3ReleaseTempReg(pParse, regFree2);
  71442. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  71443. testcase( regFree2==0 );
  71444. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  71445. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  71446. sqlite3ReleaseTempReg(pParse, r3);
  71447. sqlite3ReleaseTempReg(pParse, r4);
  71448. break;
  71449. }
  71450. case TK_COLLATE:
  71451. case TK_UPLUS: {
  71452. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  71453. break;
  71454. }
  71455. case TK_TRIGGER: {
  71456. /* If the opcode is TK_TRIGGER, then the expression is a reference
  71457. ** to a column in the new.* or old.* pseudo-tables available to
  71458. ** trigger programs. In this case Expr.iTable is set to 1 for the
  71459. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  71460. ** is set to the column of the pseudo-table to read, or to -1 to
  71461. ** read the rowid field.
  71462. **
  71463. ** The expression is implemented using an OP_Param opcode. The p1
  71464. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  71465. ** to reference another column of the old.* pseudo-table, where
  71466. ** i is the index of the column. For a new.rowid reference, p1 is
  71467. ** set to (n+1), where n is the number of columns in each pseudo-table.
  71468. ** For a reference to any other column in the new.* pseudo-table, p1
  71469. ** is set to (n+2+i), where n and i are as defined previously. For
  71470. ** example, if the table on which triggers are being fired is
  71471. ** declared as:
  71472. **
  71473. ** CREATE TABLE t1(a, b);
  71474. **
  71475. ** Then p1 is interpreted as follows:
  71476. **
  71477. ** p1==0 -> old.rowid p1==3 -> new.rowid
  71478. ** p1==1 -> old.a p1==4 -> new.a
  71479. ** p1==2 -> old.b p1==5 -> new.b
  71480. */
  71481. Table *pTab = pExpr->pTab;
  71482. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  71483. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  71484. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  71485. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  71486. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  71487. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  71488. VdbeComment((v, "%s.%s -> $%d",
  71489. (pExpr->iTable ? "new" : "old"),
  71490. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  71491. target
  71492. ));
  71493. #ifndef SQLITE_OMIT_FLOATING_POINT
  71494. /* If the column has REAL affinity, it may currently be stored as an
  71495. ** integer. Use OP_RealAffinity to make sure it is really real. */
  71496. if( pExpr->iColumn>=0
  71497. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  71498. ){
  71499. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  71500. }
  71501. #endif
  71502. break;
  71503. }
  71504. /*
  71505. ** Form A:
  71506. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  71507. **
  71508. ** Form B:
  71509. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  71510. **
  71511. ** Form A is can be transformed into the equivalent form B as follows:
  71512. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  71513. ** WHEN x=eN THEN rN ELSE y END
  71514. **
  71515. ** X (if it exists) is in pExpr->pLeft.
  71516. ** Y is in pExpr->pRight. The Y is also optional. If there is no
  71517. ** ELSE clause and no other term matches, then the result of the
  71518. ** exprssion is NULL.
  71519. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  71520. **
  71521. ** The result of the expression is the Ri for the first matching Ei,
  71522. ** or if there is no matching Ei, the ELSE term Y, or if there is
  71523. ** no ELSE term, NULL.
  71524. */
  71525. default: assert( op==TK_CASE ); {
  71526. int endLabel; /* GOTO label for end of CASE stmt */
  71527. int nextCase; /* GOTO label for next WHEN clause */
  71528. int nExpr; /* 2x number of WHEN terms */
  71529. int i; /* Loop counter */
  71530. ExprList *pEList; /* List of WHEN terms */
  71531. struct ExprList_item *aListelem; /* Array of WHEN terms */
  71532. Expr opCompare; /* The X==Ei expression */
  71533. Expr cacheX; /* Cached expression X */
  71534. Expr *pX; /* The X expression */
  71535. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  71536. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  71537. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  71538. assert((pExpr->x.pList->nExpr % 2) == 0);
  71539. assert(pExpr->x.pList->nExpr > 0);
  71540. pEList = pExpr->x.pList;
  71541. aListelem = pEList->a;
  71542. nExpr = pEList->nExpr;
  71543. endLabel = sqlite3VdbeMakeLabel(v);
  71544. if( (pX = pExpr->pLeft)!=0 ){
  71545. cacheX = *pX;
  71546. testcase( pX->op==TK_COLUMN );
  71547. testcase( pX->op==TK_REGISTER );
  71548. cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
  71549. testcase( regFree1==0 );
  71550. cacheX.op = TK_REGISTER;
  71551. opCompare.op = TK_EQ;
  71552. opCompare.pLeft = &cacheX;
  71553. pTest = &opCompare;
  71554. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  71555. ** The value in regFree1 might get SCopy-ed into the file result.
  71556. ** So make sure that the regFree1 register is not reused for other
  71557. ** purposes and possibly overwritten. */
  71558. regFree1 = 0;
  71559. }
  71560. for(i=0; i<nExpr; i=i+2){
  71561. sqlite3ExprCachePush(pParse);
  71562. if( pX ){
  71563. assert( pTest!=0 );
  71564. opCompare.pRight = aListelem[i].pExpr;
  71565. }else{
  71566. pTest = aListelem[i].pExpr;
  71567. }
  71568. nextCase = sqlite3VdbeMakeLabel(v);
  71569. testcase( pTest->op==TK_COLUMN );
  71570. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  71571. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  71572. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  71573. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  71574. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  71575. sqlite3ExprCachePop(pParse, 1);
  71576. sqlite3VdbeResolveLabel(v, nextCase);
  71577. }
  71578. if( pExpr->pRight ){
  71579. sqlite3ExprCachePush(pParse);
  71580. sqlite3ExprCode(pParse, pExpr->pRight, target);
  71581. sqlite3ExprCachePop(pParse, 1);
  71582. }else{
  71583. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  71584. }
  71585. assert( db->mallocFailed || pParse->nErr>0
  71586. || pParse->iCacheLevel==iCacheLevel );
  71587. sqlite3VdbeResolveLabel(v, endLabel);
  71588. break;
  71589. }
  71590. #ifndef SQLITE_OMIT_TRIGGER
  71591. case TK_RAISE: {
  71592. assert( pExpr->affinity==OE_Rollback
  71593. || pExpr->affinity==OE_Abort
  71594. || pExpr->affinity==OE_Fail
  71595. || pExpr->affinity==OE_Ignore
  71596. );
  71597. if( !pParse->pTriggerTab ){
  71598. sqlite3ErrorMsg(pParse,
  71599. "RAISE() may only be used within a trigger-program");
  71600. return 0;
  71601. }
  71602. if( pExpr->affinity==OE_Abort ){
  71603. sqlite3MayAbort(pParse);
  71604. }
  71605. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  71606. if( pExpr->affinity==OE_Ignore ){
  71607. sqlite3VdbeAddOp4(
  71608. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  71609. }else{
  71610. sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
  71611. }
  71612. break;
  71613. }
  71614. #endif
  71615. }
  71616. sqlite3ReleaseTempReg(pParse, regFree1);
  71617. sqlite3ReleaseTempReg(pParse, regFree2);
  71618. return inReg;
  71619. }
  71620. /*
  71621. ** Generate code to evaluate an expression and store the results
  71622. ** into a register. Return the register number where the results
  71623. ** are stored.
  71624. **
  71625. ** If the register is a temporary register that can be deallocated,
  71626. ** then write its number into *pReg. If the result register is not
  71627. ** a temporary, then set *pReg to zero.
  71628. */
  71629. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  71630. int r1 = sqlite3GetTempReg(pParse);
  71631. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  71632. if( r2==r1 ){
  71633. *pReg = r1;
  71634. }else{
  71635. sqlite3ReleaseTempReg(pParse, r1);
  71636. *pReg = 0;
  71637. }
  71638. return r2;
  71639. }
  71640. /*
  71641. ** Generate code that will evaluate expression pExpr and store the
  71642. ** results in register target. The results are guaranteed to appear
  71643. ** in register target.
  71644. */
  71645. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  71646. int inReg;
  71647. assert( target>0 && target<=pParse->nMem );
  71648. if( pExpr && pExpr->op==TK_REGISTER ){
  71649. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  71650. }else{
  71651. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  71652. assert( pParse->pVdbe || pParse->db->mallocFailed );
  71653. if( inReg!=target && pParse->pVdbe ){
  71654. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  71655. }
  71656. }
  71657. return target;
  71658. }
  71659. /*
  71660. ** Generate code that evalutes the given expression and puts the result
  71661. ** in register target.
  71662. **
  71663. ** Also make a copy of the expression results into another "cache" register
  71664. ** and modify the expression so that the next time it is evaluated,
  71665. ** the result is a copy of the cache register.
  71666. **
  71667. ** This routine is used for expressions that are used multiple
  71668. ** times. They are evaluated once and the results of the expression
  71669. ** are reused.
  71670. */
  71671. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  71672. Vdbe *v = pParse->pVdbe;
  71673. int inReg;
  71674. inReg = sqlite3ExprCode(pParse, pExpr, target);
  71675. assert( target>0 );
  71676. /* This routine is called for terms to INSERT or UPDATE. And the only
  71677. ** other place where expressions can be converted into TK_REGISTER is
  71678. ** in WHERE clause processing. So as currently implemented, there is
  71679. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  71680. ** keep the ALWAYS() in case the conditions above change with future
  71681. ** modifications or enhancements. */
  71682. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  71683. int iMem;
  71684. iMem = ++pParse->nMem;
  71685. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  71686. pExpr->iTable = iMem;
  71687. pExpr->op2 = pExpr->op;
  71688. pExpr->op = TK_REGISTER;
  71689. }
  71690. return inReg;
  71691. }
  71692. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  71693. /*
  71694. ** Generate a human-readable explanation of an expression tree.
  71695. */
  71696. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  71697. int op; /* The opcode being coded */
  71698. const char *zBinOp = 0; /* Binary operator */
  71699. const char *zUniOp = 0; /* Unary operator */
  71700. if( pExpr==0 ){
  71701. op = TK_NULL;
  71702. }else{
  71703. op = pExpr->op;
  71704. }
  71705. switch( op ){
  71706. case TK_AGG_COLUMN: {
  71707. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  71708. pExpr->iTable, pExpr->iColumn);
  71709. break;
  71710. }
  71711. case TK_COLUMN: {
  71712. if( pExpr->iTable<0 ){
  71713. /* This only happens when coding check constraints */
  71714. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  71715. }else{
  71716. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  71717. pExpr->iTable, pExpr->iColumn);
  71718. }
  71719. break;
  71720. }
  71721. case TK_INTEGER: {
  71722. if( pExpr->flags & EP_IntValue ){
  71723. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  71724. }else{
  71725. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  71726. }
  71727. break;
  71728. }
  71729. #ifndef SQLITE_OMIT_FLOATING_POINT
  71730. case TK_FLOAT: {
  71731. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  71732. break;
  71733. }
  71734. #endif
  71735. case TK_STRING: {
  71736. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  71737. break;
  71738. }
  71739. case TK_NULL: {
  71740. sqlite3ExplainPrintf(pOut,"NULL");
  71741. break;
  71742. }
  71743. #ifndef SQLITE_OMIT_BLOB_LITERAL
  71744. case TK_BLOB: {
  71745. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  71746. break;
  71747. }
  71748. #endif
  71749. case TK_VARIABLE: {
  71750. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  71751. pExpr->u.zToken, pExpr->iColumn);
  71752. break;
  71753. }
  71754. case TK_REGISTER: {
  71755. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  71756. break;
  71757. }
  71758. case TK_AS: {
  71759. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71760. break;
  71761. }
  71762. #ifndef SQLITE_OMIT_CAST
  71763. case TK_CAST: {
  71764. /* Expressions of the form: CAST(pLeft AS token) */
  71765. const char *zAff = "unk";
  71766. switch( sqlite3AffinityType(pExpr->u.zToken) ){
  71767. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  71768. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  71769. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  71770. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  71771. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  71772. }
  71773. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  71774. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71775. sqlite3ExplainPrintf(pOut, ")");
  71776. break;
  71777. }
  71778. #endif /* SQLITE_OMIT_CAST */
  71779. case TK_LT: zBinOp = "LT"; break;
  71780. case TK_LE: zBinOp = "LE"; break;
  71781. case TK_GT: zBinOp = "GT"; break;
  71782. case TK_GE: zBinOp = "GE"; break;
  71783. case TK_NE: zBinOp = "NE"; break;
  71784. case TK_EQ: zBinOp = "EQ"; break;
  71785. case TK_IS: zBinOp = "IS"; break;
  71786. case TK_ISNOT: zBinOp = "ISNOT"; break;
  71787. case TK_AND: zBinOp = "AND"; break;
  71788. case TK_OR: zBinOp = "OR"; break;
  71789. case TK_PLUS: zBinOp = "ADD"; break;
  71790. case TK_STAR: zBinOp = "MUL"; break;
  71791. case TK_MINUS: zBinOp = "SUB"; break;
  71792. case TK_REM: zBinOp = "REM"; break;
  71793. case TK_BITAND: zBinOp = "BITAND"; break;
  71794. case TK_BITOR: zBinOp = "BITOR"; break;
  71795. case TK_SLASH: zBinOp = "DIV"; break;
  71796. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  71797. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  71798. case TK_CONCAT: zBinOp = "CONCAT"; break;
  71799. case TK_UMINUS: zUniOp = "UMINUS"; break;
  71800. case TK_UPLUS: zUniOp = "UPLUS"; break;
  71801. case TK_BITNOT: zUniOp = "BITNOT"; break;
  71802. case TK_NOT: zUniOp = "NOT"; break;
  71803. case TK_ISNULL: zUniOp = "ISNULL"; break;
  71804. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  71805. case TK_COLLATE: {
  71806. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71807. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  71808. break;
  71809. }
  71810. case TK_AGG_FUNCTION:
  71811. case TK_CONST_FUNC:
  71812. case TK_FUNCTION: {
  71813. ExprList *pFarg; /* List of function arguments */
  71814. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
  71815. pFarg = 0;
  71816. }else{
  71817. pFarg = pExpr->x.pList;
  71818. }
  71819. if( op==TK_AGG_FUNCTION ){
  71820. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  71821. pExpr->op2, pExpr->u.zToken);
  71822. }else{
  71823. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  71824. }
  71825. if( pFarg ){
  71826. sqlite3ExplainExprList(pOut, pFarg);
  71827. }
  71828. sqlite3ExplainPrintf(pOut, ")");
  71829. break;
  71830. }
  71831. #ifndef SQLITE_OMIT_SUBQUERY
  71832. case TK_EXISTS: {
  71833. sqlite3ExplainPrintf(pOut, "EXISTS(");
  71834. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  71835. sqlite3ExplainPrintf(pOut,")");
  71836. break;
  71837. }
  71838. case TK_SELECT: {
  71839. sqlite3ExplainPrintf(pOut, "(");
  71840. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  71841. sqlite3ExplainPrintf(pOut, ")");
  71842. break;
  71843. }
  71844. case TK_IN: {
  71845. sqlite3ExplainPrintf(pOut, "IN(");
  71846. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71847. sqlite3ExplainPrintf(pOut, ",");
  71848. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  71849. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  71850. }else{
  71851. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  71852. }
  71853. sqlite3ExplainPrintf(pOut, ")");
  71854. break;
  71855. }
  71856. #endif /* SQLITE_OMIT_SUBQUERY */
  71857. /*
  71858. ** x BETWEEN y AND z
  71859. **
  71860. ** This is equivalent to
  71861. **
  71862. ** x>=y AND x<=z
  71863. **
  71864. ** X is stored in pExpr->pLeft.
  71865. ** Y is stored in pExpr->pList->a[0].pExpr.
  71866. ** Z is stored in pExpr->pList->a[1].pExpr.
  71867. */
  71868. case TK_BETWEEN: {
  71869. Expr *pX = pExpr->pLeft;
  71870. Expr *pY = pExpr->x.pList->a[0].pExpr;
  71871. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  71872. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  71873. sqlite3ExplainExpr(pOut, pX);
  71874. sqlite3ExplainPrintf(pOut, ",");
  71875. sqlite3ExplainExpr(pOut, pY);
  71876. sqlite3ExplainPrintf(pOut, ",");
  71877. sqlite3ExplainExpr(pOut, pZ);
  71878. sqlite3ExplainPrintf(pOut, ")");
  71879. break;
  71880. }
  71881. case TK_TRIGGER: {
  71882. /* If the opcode is TK_TRIGGER, then the expression is a reference
  71883. ** to a column in the new.* or old.* pseudo-tables available to
  71884. ** trigger programs. In this case Expr.iTable is set to 1 for the
  71885. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  71886. ** is set to the column of the pseudo-table to read, or to -1 to
  71887. ** read the rowid field.
  71888. */
  71889. sqlite3ExplainPrintf(pOut, "%s(%d)",
  71890. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  71891. break;
  71892. }
  71893. case TK_CASE: {
  71894. sqlite3ExplainPrintf(pOut, "CASE(");
  71895. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71896. sqlite3ExplainPrintf(pOut, ",");
  71897. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  71898. break;
  71899. }
  71900. #ifndef SQLITE_OMIT_TRIGGER
  71901. case TK_RAISE: {
  71902. const char *zType = "unk";
  71903. switch( pExpr->affinity ){
  71904. case OE_Rollback: zType = "rollback"; break;
  71905. case OE_Abort: zType = "abort"; break;
  71906. case OE_Fail: zType = "fail"; break;
  71907. case OE_Ignore: zType = "ignore"; break;
  71908. }
  71909. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  71910. break;
  71911. }
  71912. #endif
  71913. }
  71914. if( zBinOp ){
  71915. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  71916. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71917. sqlite3ExplainPrintf(pOut,",");
  71918. sqlite3ExplainExpr(pOut, pExpr->pRight);
  71919. sqlite3ExplainPrintf(pOut,")");
  71920. }else if( zUniOp ){
  71921. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  71922. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  71923. sqlite3ExplainPrintf(pOut,")");
  71924. }
  71925. }
  71926. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  71927. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  71928. /*
  71929. ** Generate a human-readable explanation of an expression list.
  71930. */
  71931. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  71932. int i;
  71933. if( pList==0 || pList->nExpr==0 ){
  71934. sqlite3ExplainPrintf(pOut, "(empty-list)");
  71935. return;
  71936. }else if( pList->nExpr==1 ){
  71937. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  71938. }else{
  71939. sqlite3ExplainPush(pOut);
  71940. for(i=0; i<pList->nExpr; i++){
  71941. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  71942. sqlite3ExplainPush(pOut);
  71943. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  71944. sqlite3ExplainPop(pOut);
  71945. if( i<pList->nExpr-1 ){
  71946. sqlite3ExplainNL(pOut);
  71947. }
  71948. }
  71949. sqlite3ExplainPop(pOut);
  71950. }
  71951. }
  71952. #endif /* SQLITE_DEBUG */
  71953. /*
  71954. ** Return TRUE if pExpr is an constant expression that is appropriate
  71955. ** for factoring out of a loop. Appropriate expressions are:
  71956. **
  71957. ** * Any expression that evaluates to two or more opcodes.
  71958. **
  71959. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  71960. ** or OP_Variable that does not need to be placed in a
  71961. ** specific register.
  71962. **
  71963. ** There is no point in factoring out single-instruction constant
  71964. ** expressions that need to be placed in a particular register.
  71965. ** We could factor them out, but then we would end up adding an
  71966. ** OP_SCopy instruction to move the value into the correct register
  71967. ** later. We might as well just use the original instruction and
  71968. ** avoid the OP_SCopy.
  71969. */
  71970. static int isAppropriateForFactoring(Expr *p){
  71971. if( !sqlite3ExprIsConstantNotJoin(p) ){
  71972. return 0; /* Only constant expressions are appropriate for factoring */
  71973. }
  71974. if( (p->flags & EP_FixedDest)==0 ){
  71975. return 1; /* Any constant without a fixed destination is appropriate */
  71976. }
  71977. while( p->op==TK_UPLUS ) p = p->pLeft;
  71978. switch( p->op ){
  71979. #ifndef SQLITE_OMIT_BLOB_LITERAL
  71980. case TK_BLOB:
  71981. #endif
  71982. case TK_VARIABLE:
  71983. case TK_INTEGER:
  71984. case TK_FLOAT:
  71985. case TK_NULL:
  71986. case TK_STRING: {
  71987. testcase( p->op==TK_BLOB );
  71988. testcase( p->op==TK_VARIABLE );
  71989. testcase( p->op==TK_INTEGER );
  71990. testcase( p->op==TK_FLOAT );
  71991. testcase( p->op==TK_NULL );
  71992. testcase( p->op==TK_STRING );
  71993. /* Single-instruction constants with a fixed destination are
  71994. ** better done in-line. If we factor them, they will just end
  71995. ** up generating an OP_SCopy to move the value to the destination
  71996. ** register. */
  71997. return 0;
  71998. }
  71999. case TK_UMINUS: {
  72000. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  72001. return 0;
  72002. }
  72003. break;
  72004. }
  72005. default: {
  72006. break;
  72007. }
  72008. }
  72009. return 1;
  72010. }
  72011. /*
  72012. ** If pExpr is a constant expression that is appropriate for
  72013. ** factoring out of a loop, then evaluate the expression
  72014. ** into a register and convert the expression into a TK_REGISTER
  72015. ** expression.
  72016. */
  72017. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  72018. Parse *pParse = pWalker->pParse;
  72019. switch( pExpr->op ){
  72020. case TK_IN:
  72021. case TK_REGISTER: {
  72022. return WRC_Prune;
  72023. }
  72024. case TK_COLLATE: {
  72025. return WRC_Continue;
  72026. }
  72027. case TK_FUNCTION:
  72028. case TK_AGG_FUNCTION:
  72029. case TK_CONST_FUNC: {
  72030. /* The arguments to a function have a fixed destination.
  72031. ** Mark them this way to avoid generated unneeded OP_SCopy
  72032. ** instructions.
  72033. */
  72034. ExprList *pList = pExpr->x.pList;
  72035. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  72036. if( pList ){
  72037. int i = pList->nExpr;
  72038. struct ExprList_item *pItem = pList->a;
  72039. for(; i>0; i--, pItem++){
  72040. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  72041. }
  72042. }
  72043. break;
  72044. }
  72045. }
  72046. if( isAppropriateForFactoring(pExpr) ){
  72047. int r1 = ++pParse->nMem;
  72048. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  72049. /* If r2!=r1, it means that register r1 is never used. That is harmless
  72050. ** but suboptimal, so we want to know about the situation to fix it.
  72051. ** Hence the following assert: */
  72052. assert( r2==r1 );
  72053. pExpr->op2 = pExpr->op;
  72054. pExpr->op = TK_REGISTER;
  72055. pExpr->iTable = r2;
  72056. return WRC_Prune;
  72057. }
  72058. return WRC_Continue;
  72059. }
  72060. /*
  72061. ** Preevaluate constant subexpressions within pExpr and store the
  72062. ** results in registers. Modify pExpr so that the constant subexpresions
  72063. ** are TK_REGISTER opcodes that refer to the precomputed values.
  72064. **
  72065. ** This routine is a no-op if the jump to the cookie-check code has
  72066. ** already occur. Since the cookie-check jump is generated prior to
  72067. ** any other serious processing, this check ensures that there is no
  72068. ** way to accidently bypass the constant initializations.
  72069. **
  72070. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  72071. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  72072. ** interface. This allows test logic to verify that the same answer is
  72073. ** obtained for queries regardless of whether or not constants are
  72074. ** precomputed into registers or if they are inserted in-line.
  72075. */
  72076. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  72077. Walker w;
  72078. if( pParse->cookieGoto ) return;
  72079. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  72080. w.xExprCallback = evalConstExpr;
  72081. w.xSelectCallback = 0;
  72082. w.pParse = pParse;
  72083. sqlite3WalkExpr(&w, pExpr);
  72084. }
  72085. /*
  72086. ** Generate code that pushes the value of every element of the given
  72087. ** expression list into a sequence of registers beginning at target.
  72088. **
  72089. ** Return the number of elements evaluated.
  72090. */
  72091. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  72092. Parse *pParse, /* Parsing context */
  72093. ExprList *pList, /* The expression list to be coded */
  72094. int target, /* Where to write results */
  72095. int doHardCopy /* Make a hard copy of every element */
  72096. ){
  72097. struct ExprList_item *pItem;
  72098. int i, n;
  72099. assert( pList!=0 );
  72100. assert( target>0 );
  72101. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  72102. n = pList->nExpr;
  72103. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  72104. Expr *pExpr = pItem->pExpr;
  72105. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  72106. if( inReg!=target+i ){
  72107. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  72108. inReg, target+i);
  72109. }
  72110. }
  72111. return n;
  72112. }
  72113. /*
  72114. ** Generate code for a BETWEEN operator.
  72115. **
  72116. ** x BETWEEN y AND z
  72117. **
  72118. ** The above is equivalent to
  72119. **
  72120. ** x>=y AND x<=z
  72121. **
  72122. ** Code it as such, taking care to do the common subexpression
  72123. ** elementation of x.
  72124. */
  72125. static void exprCodeBetween(
  72126. Parse *pParse, /* Parsing and code generating context */
  72127. Expr *pExpr, /* The BETWEEN expression */
  72128. int dest, /* Jump here if the jump is taken */
  72129. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  72130. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  72131. ){
  72132. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  72133. Expr compLeft; /* The x>=y term */
  72134. Expr compRight; /* The x<=z term */
  72135. Expr exprX; /* The x subexpression */
  72136. int regFree1 = 0; /* Temporary use register */
  72137. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  72138. exprX = *pExpr->pLeft;
  72139. exprAnd.op = TK_AND;
  72140. exprAnd.pLeft = &compLeft;
  72141. exprAnd.pRight = &compRight;
  72142. compLeft.op = TK_GE;
  72143. compLeft.pLeft = &exprX;
  72144. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  72145. compRight.op = TK_LE;
  72146. compRight.pLeft = &exprX;
  72147. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  72148. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  72149. exprX.op = TK_REGISTER;
  72150. if( jumpIfTrue ){
  72151. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  72152. }else{
  72153. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  72154. }
  72155. sqlite3ReleaseTempReg(pParse, regFree1);
  72156. /* Ensure adequate test coverage */
  72157. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  72158. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  72159. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  72160. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  72161. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  72162. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  72163. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  72164. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  72165. }
  72166. /*
  72167. ** Generate code for a boolean expression such that a jump is made
  72168. ** to the label "dest" if the expression is true but execution
  72169. ** continues straight thru if the expression is false.
  72170. **
  72171. ** If the expression evaluates to NULL (neither true nor false), then
  72172. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  72173. **
  72174. ** This code depends on the fact that certain token values (ex: TK_EQ)
  72175. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  72176. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  72177. ** the make process cause these values to align. Assert()s in the code
  72178. ** below verify that the numbers are aligned correctly.
  72179. */
  72180. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  72181. Vdbe *v = pParse->pVdbe;
  72182. int op = 0;
  72183. int regFree1 = 0;
  72184. int regFree2 = 0;
  72185. int r1, r2;
  72186. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  72187. if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
  72188. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  72189. op = pExpr->op;
  72190. switch( op ){
  72191. case TK_AND: {
  72192. int d2 = sqlite3VdbeMakeLabel(v);
  72193. testcase( jumpIfNull==0 );
  72194. sqlite3ExprCachePush(pParse);
  72195. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  72196. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  72197. sqlite3VdbeResolveLabel(v, d2);
  72198. sqlite3ExprCachePop(pParse, 1);
  72199. break;
  72200. }
  72201. case TK_OR: {
  72202. testcase( jumpIfNull==0 );
  72203. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  72204. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  72205. break;
  72206. }
  72207. case TK_NOT: {
  72208. testcase( jumpIfNull==0 );
  72209. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  72210. break;
  72211. }
  72212. case TK_LT:
  72213. case TK_LE:
  72214. case TK_GT:
  72215. case TK_GE:
  72216. case TK_NE:
  72217. case TK_EQ: {
  72218. assert( TK_LT==OP_Lt );
  72219. assert( TK_LE==OP_Le );
  72220. assert( TK_GT==OP_Gt );
  72221. assert( TK_GE==OP_Ge );
  72222. assert( TK_EQ==OP_Eq );
  72223. assert( TK_NE==OP_Ne );
  72224. testcase( op==TK_LT );
  72225. testcase( op==TK_LE );
  72226. testcase( op==TK_GT );
  72227. testcase( op==TK_GE );
  72228. testcase( op==TK_EQ );
  72229. testcase( op==TK_NE );
  72230. testcase( jumpIfNull==0 );
  72231. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72232. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72233. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72234. r1, r2, dest, jumpIfNull);
  72235. testcase( regFree1==0 );
  72236. testcase( regFree2==0 );
  72237. break;
  72238. }
  72239. case TK_IS:
  72240. case TK_ISNOT: {
  72241. testcase( op==TK_IS );
  72242. testcase( op==TK_ISNOT );
  72243. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72244. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72245. op = (op==TK_IS) ? TK_EQ : TK_NE;
  72246. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72247. r1, r2, dest, SQLITE_NULLEQ);
  72248. testcase( regFree1==0 );
  72249. testcase( regFree2==0 );
  72250. break;
  72251. }
  72252. case TK_ISNULL:
  72253. case TK_NOTNULL: {
  72254. assert( TK_ISNULL==OP_IsNull );
  72255. assert( TK_NOTNULL==OP_NotNull );
  72256. testcase( op==TK_ISNULL );
  72257. testcase( op==TK_NOTNULL );
  72258. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72259. sqlite3VdbeAddOp2(v, op, r1, dest);
  72260. testcase( regFree1==0 );
  72261. break;
  72262. }
  72263. case TK_BETWEEN: {
  72264. testcase( jumpIfNull==0 );
  72265. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  72266. break;
  72267. }
  72268. #ifndef SQLITE_OMIT_SUBQUERY
  72269. case TK_IN: {
  72270. int destIfFalse = sqlite3VdbeMakeLabel(v);
  72271. int destIfNull = jumpIfNull ? dest : destIfFalse;
  72272. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  72273. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  72274. sqlite3VdbeResolveLabel(v, destIfFalse);
  72275. break;
  72276. }
  72277. #endif
  72278. default: {
  72279. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  72280. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  72281. testcase( regFree1==0 );
  72282. testcase( jumpIfNull==0 );
  72283. break;
  72284. }
  72285. }
  72286. sqlite3ReleaseTempReg(pParse, regFree1);
  72287. sqlite3ReleaseTempReg(pParse, regFree2);
  72288. }
  72289. /*
  72290. ** Generate code for a boolean expression such that a jump is made
  72291. ** to the label "dest" if the expression is false but execution
  72292. ** continues straight thru if the expression is true.
  72293. **
  72294. ** If the expression evaluates to NULL (neither true nor false) then
  72295. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  72296. ** is 0.
  72297. */
  72298. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  72299. Vdbe *v = pParse->pVdbe;
  72300. int op = 0;
  72301. int regFree1 = 0;
  72302. int regFree2 = 0;
  72303. int r1, r2;
  72304. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  72305. if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
  72306. if( pExpr==0 ) return;
  72307. /* The value of pExpr->op and op are related as follows:
  72308. **
  72309. ** pExpr->op op
  72310. ** --------- ----------
  72311. ** TK_ISNULL OP_NotNull
  72312. ** TK_NOTNULL OP_IsNull
  72313. ** TK_NE OP_Eq
  72314. ** TK_EQ OP_Ne
  72315. ** TK_GT OP_Le
  72316. ** TK_LE OP_Gt
  72317. ** TK_GE OP_Lt
  72318. ** TK_LT OP_Ge
  72319. **
  72320. ** For other values of pExpr->op, op is undefined and unused.
  72321. ** The value of TK_ and OP_ constants are arranged such that we
  72322. ** can compute the mapping above using the following expression.
  72323. ** Assert()s verify that the computation is correct.
  72324. */
  72325. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  72326. /* Verify correct alignment of TK_ and OP_ constants
  72327. */
  72328. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  72329. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  72330. assert( pExpr->op!=TK_NE || op==OP_Eq );
  72331. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  72332. assert( pExpr->op!=TK_LT || op==OP_Ge );
  72333. assert( pExpr->op!=TK_LE || op==OP_Gt );
  72334. assert( pExpr->op!=TK_GT || op==OP_Le );
  72335. assert( pExpr->op!=TK_GE || op==OP_Lt );
  72336. switch( pExpr->op ){
  72337. case TK_AND: {
  72338. testcase( jumpIfNull==0 );
  72339. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  72340. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  72341. break;
  72342. }
  72343. case TK_OR: {
  72344. int d2 = sqlite3VdbeMakeLabel(v);
  72345. testcase( jumpIfNull==0 );
  72346. sqlite3ExprCachePush(pParse);
  72347. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  72348. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  72349. sqlite3VdbeResolveLabel(v, d2);
  72350. sqlite3ExprCachePop(pParse, 1);
  72351. break;
  72352. }
  72353. case TK_NOT: {
  72354. testcase( jumpIfNull==0 );
  72355. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  72356. break;
  72357. }
  72358. case TK_LT:
  72359. case TK_LE:
  72360. case TK_GT:
  72361. case TK_GE:
  72362. case TK_NE:
  72363. case TK_EQ: {
  72364. testcase( op==TK_LT );
  72365. testcase( op==TK_LE );
  72366. testcase( op==TK_GT );
  72367. testcase( op==TK_GE );
  72368. testcase( op==TK_EQ );
  72369. testcase( op==TK_NE );
  72370. testcase( jumpIfNull==0 );
  72371. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72372. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72373. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72374. r1, r2, dest, jumpIfNull);
  72375. testcase( regFree1==0 );
  72376. testcase( regFree2==0 );
  72377. break;
  72378. }
  72379. case TK_IS:
  72380. case TK_ISNOT: {
  72381. testcase( pExpr->op==TK_IS );
  72382. testcase( pExpr->op==TK_ISNOT );
  72383. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72384. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  72385. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  72386. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  72387. r1, r2, dest, SQLITE_NULLEQ);
  72388. testcase( regFree1==0 );
  72389. testcase( regFree2==0 );
  72390. break;
  72391. }
  72392. case TK_ISNULL:
  72393. case TK_NOTNULL: {
  72394. testcase( op==TK_ISNULL );
  72395. testcase( op==TK_NOTNULL );
  72396. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  72397. sqlite3VdbeAddOp2(v, op, r1, dest);
  72398. testcase( regFree1==0 );
  72399. break;
  72400. }
  72401. case TK_BETWEEN: {
  72402. testcase( jumpIfNull==0 );
  72403. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  72404. break;
  72405. }
  72406. #ifndef SQLITE_OMIT_SUBQUERY
  72407. case TK_IN: {
  72408. if( jumpIfNull ){
  72409. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  72410. }else{
  72411. int destIfNull = sqlite3VdbeMakeLabel(v);
  72412. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  72413. sqlite3VdbeResolveLabel(v, destIfNull);
  72414. }
  72415. break;
  72416. }
  72417. #endif
  72418. default: {
  72419. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  72420. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  72421. testcase( regFree1==0 );
  72422. testcase( jumpIfNull==0 );
  72423. break;
  72424. }
  72425. }
  72426. sqlite3ReleaseTempReg(pParse, regFree1);
  72427. sqlite3ReleaseTempReg(pParse, regFree2);
  72428. }
  72429. /*
  72430. ** Do a deep comparison of two expression trees. Return 0 if the two
  72431. ** expressions are completely identical. Return 1 if they differ only
  72432. ** by a COLLATE operator at the top level. Return 2 if there are differences
  72433. ** other than the top-level COLLATE operator.
  72434. **
  72435. ** Sometimes this routine will return 2 even if the two expressions
  72436. ** really are equivalent. If we cannot prove that the expressions are
  72437. ** identical, we return 2 just to be safe. So if this routine
  72438. ** returns 2, then you do not really know for certain if the two
  72439. ** expressions are the same. But if you get a 0 or 1 return, then you
  72440. ** can be sure the expressions are the same. In the places where
  72441. ** this routine is used, it does not hurt to get an extra 2 - that
  72442. ** just might result in some slightly slower code. But returning
  72443. ** an incorrect 0 or 1 could lead to a malfunction.
  72444. */
  72445. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  72446. if( pA==0||pB==0 ){
  72447. return pB==pA ? 0 : 2;
  72448. }
  72449. assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
  72450. assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
  72451. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  72452. return 2;
  72453. }
  72454. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  72455. if( pA->op!=pB->op ){
  72456. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
  72457. return 1;
  72458. }
  72459. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
  72460. return 1;
  72461. }
  72462. return 2;
  72463. }
  72464. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
  72465. if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
  72466. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
  72467. if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
  72468. if( ExprHasProperty(pA, EP_IntValue) ){
  72469. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  72470. return 2;
  72471. }
  72472. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  72473. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  72474. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  72475. return pA->op==TK_COLLATE ? 1 : 2;
  72476. }
  72477. }
  72478. return 0;
  72479. }
  72480. /*
  72481. ** Compare two ExprList objects. Return 0 if they are identical and
  72482. ** non-zero if they differ in any way.
  72483. **
  72484. ** This routine might return non-zero for equivalent ExprLists. The
  72485. ** only consequence will be disabled optimizations. But this routine
  72486. ** must never return 0 if the two ExprList objects are different, or
  72487. ** a malfunction will result.
  72488. **
  72489. ** Two NULL pointers are considered to be the same. But a NULL pointer
  72490. ** always differs from a non-NULL pointer.
  72491. */
  72492. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
  72493. int i;
  72494. if( pA==0 && pB==0 ) return 0;
  72495. if( pA==0 || pB==0 ) return 1;
  72496. if( pA->nExpr!=pB->nExpr ) return 1;
  72497. for(i=0; i<pA->nExpr; i++){
  72498. Expr *pExprA = pA->a[i].pExpr;
  72499. Expr *pExprB = pB->a[i].pExpr;
  72500. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  72501. if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
  72502. }
  72503. return 0;
  72504. }
  72505. /*
  72506. ** An instance of the following structure is used by the tree walker
  72507. ** to count references to table columns in the arguments of an
  72508. ** aggregate function, in order to implement the
  72509. ** sqlite3FunctionThisSrc() routine.
  72510. */
  72511. struct SrcCount {
  72512. SrcList *pSrc; /* One particular FROM clause in a nested query */
  72513. int nThis; /* Number of references to columns in pSrcList */
  72514. int nOther; /* Number of references to columns in other FROM clauses */
  72515. };
  72516. /*
  72517. ** Count the number of references to columns.
  72518. */
  72519. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  72520. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  72521. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  72522. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  72523. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  72524. ** NEVER() will need to be removed. */
  72525. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  72526. int i;
  72527. struct SrcCount *p = pWalker->u.pSrcCount;
  72528. SrcList *pSrc = p->pSrc;
  72529. for(i=0; i<pSrc->nSrc; i++){
  72530. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  72531. }
  72532. if( i<pSrc->nSrc ){
  72533. p->nThis++;
  72534. }else{
  72535. p->nOther++;
  72536. }
  72537. }
  72538. return WRC_Continue;
  72539. }
  72540. /*
  72541. ** Determine if any of the arguments to the pExpr Function reference
  72542. ** pSrcList. Return true if they do. Also return true if the function
  72543. ** has no arguments or has only constant arguments. Return false if pExpr
  72544. ** references columns but not columns of tables found in pSrcList.
  72545. */
  72546. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  72547. Walker w;
  72548. struct SrcCount cnt;
  72549. assert( pExpr->op==TK_AGG_FUNCTION );
  72550. memset(&w, 0, sizeof(w));
  72551. w.xExprCallback = exprSrcCount;
  72552. w.u.pSrcCount = &cnt;
  72553. cnt.pSrc = pSrcList;
  72554. cnt.nThis = 0;
  72555. cnt.nOther = 0;
  72556. sqlite3WalkExprList(&w, pExpr->x.pList);
  72557. return cnt.nThis>0 || cnt.nOther==0;
  72558. }
  72559. /*
  72560. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  72561. ** the new element. Return a negative number if malloc fails.
  72562. */
  72563. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  72564. int i;
  72565. pInfo->aCol = sqlite3ArrayAllocate(
  72566. db,
  72567. pInfo->aCol,
  72568. sizeof(pInfo->aCol[0]),
  72569. &pInfo->nColumn,
  72570. &i
  72571. );
  72572. return i;
  72573. }
  72574. /*
  72575. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  72576. ** the new element. Return a negative number if malloc fails.
  72577. */
  72578. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  72579. int i;
  72580. pInfo->aFunc = sqlite3ArrayAllocate(
  72581. db,
  72582. pInfo->aFunc,
  72583. sizeof(pInfo->aFunc[0]),
  72584. &pInfo->nFunc,
  72585. &i
  72586. );
  72587. return i;
  72588. }
  72589. /*
  72590. ** This is the xExprCallback for a tree walker. It is used to
  72591. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  72592. ** for additional information.
  72593. */
  72594. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  72595. int i;
  72596. NameContext *pNC = pWalker->u.pNC;
  72597. Parse *pParse = pNC->pParse;
  72598. SrcList *pSrcList = pNC->pSrcList;
  72599. AggInfo *pAggInfo = pNC->pAggInfo;
  72600. switch( pExpr->op ){
  72601. case TK_AGG_COLUMN:
  72602. case TK_COLUMN: {
  72603. testcase( pExpr->op==TK_AGG_COLUMN );
  72604. testcase( pExpr->op==TK_COLUMN );
  72605. /* Check to see if the column is in one of the tables in the FROM
  72606. ** clause of the aggregate query */
  72607. if( ALWAYS(pSrcList!=0) ){
  72608. struct SrcList_item *pItem = pSrcList->a;
  72609. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  72610. struct AggInfo_col *pCol;
  72611. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  72612. if( pExpr->iTable==pItem->iCursor ){
  72613. /* If we reach this point, it means that pExpr refers to a table
  72614. ** that is in the FROM clause of the aggregate query.
  72615. **
  72616. ** Make an entry for the column in pAggInfo->aCol[] if there
  72617. ** is not an entry there already.
  72618. */
  72619. int k;
  72620. pCol = pAggInfo->aCol;
  72621. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  72622. if( pCol->iTable==pExpr->iTable &&
  72623. pCol->iColumn==pExpr->iColumn ){
  72624. break;
  72625. }
  72626. }
  72627. if( (k>=pAggInfo->nColumn)
  72628. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  72629. ){
  72630. pCol = &pAggInfo->aCol[k];
  72631. pCol->pTab = pExpr->pTab;
  72632. pCol->iTable = pExpr->iTable;
  72633. pCol->iColumn = pExpr->iColumn;
  72634. pCol->iMem = ++pParse->nMem;
  72635. pCol->iSorterColumn = -1;
  72636. pCol->pExpr = pExpr;
  72637. if( pAggInfo->pGroupBy ){
  72638. int j, n;
  72639. ExprList *pGB = pAggInfo->pGroupBy;
  72640. struct ExprList_item *pTerm = pGB->a;
  72641. n = pGB->nExpr;
  72642. for(j=0; j<n; j++, pTerm++){
  72643. Expr *pE = pTerm->pExpr;
  72644. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  72645. pE->iColumn==pExpr->iColumn ){
  72646. pCol->iSorterColumn = j;
  72647. break;
  72648. }
  72649. }
  72650. }
  72651. if( pCol->iSorterColumn<0 ){
  72652. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  72653. }
  72654. }
  72655. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  72656. ** because it was there before or because we just created it).
  72657. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  72658. ** pAggInfo->aCol[] entry.
  72659. */
  72660. ExprSetIrreducible(pExpr);
  72661. pExpr->pAggInfo = pAggInfo;
  72662. pExpr->op = TK_AGG_COLUMN;
  72663. pExpr->iAgg = (i16)k;
  72664. break;
  72665. } /* endif pExpr->iTable==pItem->iCursor */
  72666. } /* end loop over pSrcList */
  72667. }
  72668. return WRC_Prune;
  72669. }
  72670. case TK_AGG_FUNCTION: {
  72671. if( (pNC->ncFlags & NC_InAggFunc)==0
  72672. && pWalker->walkerDepth==pExpr->op2
  72673. ){
  72674. /* Check to see if pExpr is a duplicate of another aggregate
  72675. ** function that is already in the pAggInfo structure
  72676. */
  72677. struct AggInfo_func *pItem = pAggInfo->aFunc;
  72678. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  72679. if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
  72680. break;
  72681. }
  72682. }
  72683. if( i>=pAggInfo->nFunc ){
  72684. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  72685. */
  72686. u8 enc = ENC(pParse->db);
  72687. i = addAggInfoFunc(pParse->db, pAggInfo);
  72688. if( i>=0 ){
  72689. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  72690. pItem = &pAggInfo->aFunc[i];
  72691. pItem->pExpr = pExpr;
  72692. pItem->iMem = ++pParse->nMem;
  72693. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  72694. pItem->pFunc = sqlite3FindFunction(pParse->db,
  72695. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  72696. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  72697. if( pExpr->flags & EP_Distinct ){
  72698. pItem->iDistinct = pParse->nTab++;
  72699. }else{
  72700. pItem->iDistinct = -1;
  72701. }
  72702. }
  72703. }
  72704. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  72705. */
  72706. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  72707. ExprSetIrreducible(pExpr);
  72708. pExpr->iAgg = (i16)i;
  72709. pExpr->pAggInfo = pAggInfo;
  72710. return WRC_Prune;
  72711. }else{
  72712. return WRC_Continue;
  72713. }
  72714. }
  72715. }
  72716. return WRC_Continue;
  72717. }
  72718. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  72719. UNUSED_PARAMETER(pWalker);
  72720. UNUSED_PARAMETER(pSelect);
  72721. return WRC_Continue;
  72722. }
  72723. /*
  72724. ** Analyze the pExpr expression looking for aggregate functions and
  72725. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  72726. ** points to. Additional entries are made on the AggInfo object as
  72727. ** necessary.
  72728. **
  72729. ** This routine should only be called after the expression has been
  72730. ** analyzed by sqlite3ResolveExprNames().
  72731. */
  72732. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  72733. Walker w;
  72734. memset(&w, 0, sizeof(w));
  72735. w.xExprCallback = analyzeAggregate;
  72736. w.xSelectCallback = analyzeAggregatesInSelect;
  72737. w.u.pNC = pNC;
  72738. assert( pNC->pSrcList!=0 );
  72739. sqlite3WalkExpr(&w, pExpr);
  72740. }
  72741. /*
  72742. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  72743. ** expression list. Return the number of errors.
  72744. **
  72745. ** If an error is found, the analysis is cut short.
  72746. */
  72747. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  72748. struct ExprList_item *pItem;
  72749. int i;
  72750. if( pList ){
  72751. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  72752. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  72753. }
  72754. }
  72755. }
  72756. /*
  72757. ** Allocate a single new register for use to hold some intermediate result.
  72758. */
  72759. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  72760. if( pParse->nTempReg==0 ){
  72761. return ++pParse->nMem;
  72762. }
  72763. return pParse->aTempReg[--pParse->nTempReg];
  72764. }
  72765. /*
  72766. ** Deallocate a register, making available for reuse for some other
  72767. ** purpose.
  72768. **
  72769. ** If a register is currently being used by the column cache, then
  72770. ** the dallocation is deferred until the column cache line that uses
  72771. ** the register becomes stale.
  72772. */
  72773. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  72774. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  72775. int i;
  72776. struct yColCache *p;
  72777. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  72778. if( p->iReg==iReg ){
  72779. p->tempReg = 1;
  72780. return;
  72781. }
  72782. }
  72783. pParse->aTempReg[pParse->nTempReg++] = iReg;
  72784. }
  72785. }
  72786. /*
  72787. ** Allocate or deallocate a block of nReg consecutive registers
  72788. */
  72789. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  72790. int i, n;
  72791. i = pParse->iRangeReg;
  72792. n = pParse->nRangeReg;
  72793. if( nReg<=n ){
  72794. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  72795. pParse->iRangeReg += nReg;
  72796. pParse->nRangeReg -= nReg;
  72797. }else{
  72798. i = pParse->nMem+1;
  72799. pParse->nMem += nReg;
  72800. }
  72801. return i;
  72802. }
  72803. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  72804. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  72805. if( nReg>pParse->nRangeReg ){
  72806. pParse->nRangeReg = nReg;
  72807. pParse->iRangeReg = iReg;
  72808. }
  72809. }
  72810. /*
  72811. ** Mark all temporary registers as being unavailable for reuse.
  72812. */
  72813. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  72814. pParse->nTempReg = 0;
  72815. pParse->nRangeReg = 0;
  72816. }
  72817. /************** End of expr.c ************************************************/
  72818. /************** Begin file alter.c *******************************************/
  72819. /*
  72820. ** 2005 February 15
  72821. **
  72822. ** The author disclaims copyright to this source code. In place of
  72823. ** a legal notice, here is a blessing:
  72824. **
  72825. ** May you do good and not evil.
  72826. ** May you find forgiveness for yourself and forgive others.
  72827. ** May you share freely, never taking more than you give.
  72828. **
  72829. *************************************************************************
  72830. ** This file contains C code routines that used to generate VDBE code
  72831. ** that implements the ALTER TABLE command.
  72832. */
  72833. /*
  72834. ** The code in this file only exists if we are not omitting the
  72835. ** ALTER TABLE logic from the build.
  72836. */
  72837. #ifndef SQLITE_OMIT_ALTERTABLE
  72838. /*
  72839. ** This function is used by SQL generated to implement the
  72840. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  72841. ** CREATE INDEX command. The second is a table name. The table name in
  72842. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  72843. ** argument and the result returned. Examples:
  72844. **
  72845. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  72846. ** -> 'CREATE TABLE def(a, b, c)'
  72847. **
  72848. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  72849. ** -> 'CREATE INDEX i ON def(a, b, c)'
  72850. */
  72851. static void renameTableFunc(
  72852. sqlite3_context *context,
  72853. int NotUsed,
  72854. sqlite3_value **argv
  72855. ){
  72856. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  72857. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  72858. int token;
  72859. Token tname;
  72860. unsigned char const *zCsr = zSql;
  72861. int len = 0;
  72862. char *zRet;
  72863. sqlite3 *db = sqlite3_context_db_handle(context);
  72864. UNUSED_PARAMETER(NotUsed);
  72865. /* The principle used to locate the table name in the CREATE TABLE
  72866. ** statement is that the table name is the first non-space token that
  72867. ** is immediately followed by a TK_LP or TK_USING token.
  72868. */
  72869. if( zSql ){
  72870. do {
  72871. if( !*zCsr ){
  72872. /* Ran out of input before finding an opening bracket. Return NULL. */
  72873. return;
  72874. }
  72875. /* Store the token that zCsr points to in tname. */
  72876. tname.z = (char*)zCsr;
  72877. tname.n = len;
  72878. /* Advance zCsr to the next token. Store that token type in 'token',
  72879. ** and its length in 'len' (to be used next iteration of this loop).
  72880. */
  72881. do {
  72882. zCsr += len;
  72883. len = sqlite3GetToken(zCsr, &token);
  72884. } while( token==TK_SPACE );
  72885. assert( len>0 );
  72886. } while( token!=TK_LP && token!=TK_USING );
  72887. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  72888. zTableName, tname.z+tname.n);
  72889. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  72890. }
  72891. }
  72892. /*
  72893. ** This C function implements an SQL user function that is used by SQL code
  72894. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  72895. ** of any foreign key constraints that use the table being renamed as the
  72896. ** parent table. It is passed three arguments:
  72897. **
  72898. ** 1) The complete text of the CREATE TABLE statement being modified,
  72899. ** 2) The old name of the table being renamed, and
  72900. ** 3) The new name of the table being renamed.
  72901. **
  72902. ** It returns the new CREATE TABLE statement. For example:
  72903. **
  72904. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  72905. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  72906. */
  72907. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72908. static void renameParentFunc(
  72909. sqlite3_context *context,
  72910. int NotUsed,
  72911. sqlite3_value **argv
  72912. ){
  72913. sqlite3 *db = sqlite3_context_db_handle(context);
  72914. char *zOutput = 0;
  72915. char *zResult;
  72916. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  72917. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  72918. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  72919. unsigned const char *z; /* Pointer to token */
  72920. int n; /* Length of token z */
  72921. int token; /* Type of token */
  72922. UNUSED_PARAMETER(NotUsed);
  72923. for(z=zInput; *z; z=z+n){
  72924. n = sqlite3GetToken(z, &token);
  72925. if( token==TK_REFERENCES ){
  72926. char *zParent;
  72927. do {
  72928. z += n;
  72929. n = sqlite3GetToken(z, &token);
  72930. }while( token==TK_SPACE );
  72931. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  72932. if( zParent==0 ) break;
  72933. sqlite3Dequote(zParent);
  72934. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  72935. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  72936. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  72937. );
  72938. sqlite3DbFree(db, zOutput);
  72939. zOutput = zOut;
  72940. zInput = &z[n];
  72941. }
  72942. sqlite3DbFree(db, zParent);
  72943. }
  72944. }
  72945. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  72946. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  72947. sqlite3DbFree(db, zOutput);
  72948. }
  72949. #endif
  72950. #ifndef SQLITE_OMIT_TRIGGER
  72951. /* This function is used by SQL generated to implement the
  72952. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  72953. ** statement. The second is a table name. The table name in the CREATE
  72954. ** TRIGGER statement is replaced with the third argument and the result
  72955. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  72956. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  72957. */
  72958. static void renameTriggerFunc(
  72959. sqlite3_context *context,
  72960. int NotUsed,
  72961. sqlite3_value **argv
  72962. ){
  72963. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  72964. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  72965. int token;
  72966. Token tname;
  72967. int dist = 3;
  72968. unsigned char const *zCsr = zSql;
  72969. int len = 0;
  72970. char *zRet;
  72971. sqlite3 *db = sqlite3_context_db_handle(context);
  72972. UNUSED_PARAMETER(NotUsed);
  72973. /* The principle used to locate the table name in the CREATE TRIGGER
  72974. ** statement is that the table name is the first token that is immediatedly
  72975. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  72976. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  72977. */
  72978. if( zSql ){
  72979. do {
  72980. if( !*zCsr ){
  72981. /* Ran out of input before finding the table name. Return NULL. */
  72982. return;
  72983. }
  72984. /* Store the token that zCsr points to in tname. */
  72985. tname.z = (char*)zCsr;
  72986. tname.n = len;
  72987. /* Advance zCsr to the next token. Store that token type in 'token',
  72988. ** and its length in 'len' (to be used next iteration of this loop).
  72989. */
  72990. do {
  72991. zCsr += len;
  72992. len = sqlite3GetToken(zCsr, &token);
  72993. }while( token==TK_SPACE );
  72994. assert( len>0 );
  72995. /* Variable 'dist' stores the number of tokens read since the most
  72996. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  72997. ** token is read and 'dist' equals 2, the condition stated above
  72998. ** to be met.
  72999. **
  73000. ** Note that ON cannot be a database, table or column name, so
  73001. ** there is no need to worry about syntax like
  73002. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  73003. */
  73004. dist++;
  73005. if( token==TK_DOT || token==TK_ON ){
  73006. dist = 0;
  73007. }
  73008. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  73009. /* Variable tname now contains the token that is the old table-name
  73010. ** in the CREATE TRIGGER statement.
  73011. */
  73012. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  73013. zTableName, tname.z+tname.n);
  73014. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  73015. }
  73016. }
  73017. #endif /* !SQLITE_OMIT_TRIGGER */
  73018. /*
  73019. ** Register built-in functions used to help implement ALTER TABLE
  73020. */
  73021. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  73022. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  73023. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  73024. #ifndef SQLITE_OMIT_TRIGGER
  73025. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  73026. #endif
  73027. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73028. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  73029. #endif
  73030. };
  73031. int i;
  73032. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  73033. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  73034. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  73035. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  73036. }
  73037. }
  73038. /*
  73039. ** This function is used to create the text of expressions of the form:
  73040. **
  73041. ** name=<constant1> OR name=<constant2> OR ...
  73042. **
  73043. ** If argument zWhere is NULL, then a pointer string containing the text
  73044. ** "name=<constant>" is returned, where <constant> is the quoted version
  73045. ** of the string passed as argument zConstant. The returned buffer is
  73046. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  73047. ** caller to ensure that it is eventually freed.
  73048. **
  73049. ** If argument zWhere is not NULL, then the string returned is
  73050. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  73051. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  73052. **
  73053. */
  73054. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  73055. char *zNew;
  73056. if( !zWhere ){
  73057. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  73058. }else{
  73059. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  73060. sqlite3DbFree(db, zWhere);
  73061. }
  73062. return zNew;
  73063. }
  73064. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  73065. /*
  73066. ** Generate the text of a WHERE expression which can be used to select all
  73067. ** tables that have foreign key constraints that refer to table pTab (i.e.
  73068. ** constraints for which pTab is the parent table) from the sqlite_master
  73069. ** table.
  73070. */
  73071. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  73072. FKey *p;
  73073. char *zWhere = 0;
  73074. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  73075. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  73076. }
  73077. return zWhere;
  73078. }
  73079. #endif
  73080. /*
  73081. ** Generate the text of a WHERE expression which can be used to select all
  73082. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  73083. ** table pTab has no temporary triggers, or is itself stored in the
  73084. ** temporary database, NULL is returned.
  73085. */
  73086. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  73087. Trigger *pTrig;
  73088. char *zWhere = 0;
  73089. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  73090. /* If the table is not located in the temp-db (in which case NULL is
  73091. ** returned, loop through the tables list of triggers. For each trigger
  73092. ** that is not part of the temp-db schema, add a clause to the WHERE
  73093. ** expression being built up in zWhere.
  73094. */
  73095. if( pTab->pSchema!=pTempSchema ){
  73096. sqlite3 *db = pParse->db;
  73097. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  73098. if( pTrig->pSchema==pTempSchema ){
  73099. zWhere = whereOrName(db, zWhere, pTrig->zName);
  73100. }
  73101. }
  73102. }
  73103. if( zWhere ){
  73104. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  73105. sqlite3DbFree(pParse->db, zWhere);
  73106. zWhere = zNew;
  73107. }
  73108. return zWhere;
  73109. }
  73110. /*
  73111. ** Generate code to drop and reload the internal representation of table
  73112. ** pTab from the database, including triggers and temporary triggers.
  73113. ** Argument zName is the name of the table in the database schema at
  73114. ** the time the generated code is executed. This can be different from
  73115. ** pTab->zName if this function is being called to code part of an
  73116. ** "ALTER TABLE RENAME TO" statement.
  73117. */
  73118. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  73119. Vdbe *v;
  73120. char *zWhere;
  73121. int iDb; /* Index of database containing pTab */
  73122. #ifndef SQLITE_OMIT_TRIGGER
  73123. Trigger *pTrig;
  73124. #endif
  73125. v = sqlite3GetVdbe(pParse);
  73126. if( NEVER(v==0) ) return;
  73127. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  73128. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  73129. assert( iDb>=0 );
  73130. #ifndef SQLITE_OMIT_TRIGGER
  73131. /* Drop any table triggers from the internal schema. */
  73132. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  73133. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  73134. assert( iTrigDb==iDb || iTrigDb==1 );
  73135. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  73136. }
  73137. #endif
  73138. /* Drop the table and index from the internal schema. */
  73139. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  73140. /* Reload the table, index and permanent trigger schemas. */
  73141. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  73142. if( !zWhere ) return;
  73143. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  73144. #ifndef SQLITE_OMIT_TRIGGER
  73145. /* Now, if the table is not stored in the temp database, reload any temp
  73146. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  73147. */
  73148. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  73149. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  73150. }
  73151. #endif
  73152. }
  73153. /*
  73154. ** Parameter zName is the name of a table that is about to be altered
  73155. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  73156. ** If the table is a system table, this function leaves an error message
  73157. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  73158. **
  73159. ** Or, if zName is not a system table, zero is returned.
  73160. */
  73161. static int isSystemTable(Parse *pParse, const char *zName){
  73162. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  73163. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  73164. return 1;
  73165. }
  73166. return 0;
  73167. }
  73168. /*
  73169. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  73170. ** command.
  73171. */
  73172. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  73173. Parse *pParse, /* Parser context. */
  73174. SrcList *pSrc, /* The table to rename. */
  73175. Token *pName /* The new table name. */
  73176. ){
  73177. int iDb; /* Database that contains the table */
  73178. char *zDb; /* Name of database iDb */
  73179. Table *pTab; /* Table being renamed */
  73180. char *zName = 0; /* NULL-terminated version of pName */
  73181. sqlite3 *db = pParse->db; /* Database connection */
  73182. int nTabName; /* Number of UTF-8 characters in zTabName */
  73183. const char *zTabName; /* Original name of the table */
  73184. Vdbe *v;
  73185. #ifndef SQLITE_OMIT_TRIGGER
  73186. char *zWhere = 0; /* Where clause to locate temp triggers */
  73187. #endif
  73188. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  73189. int savedDbFlags; /* Saved value of db->flags */
  73190. savedDbFlags = db->flags;
  73191. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  73192. assert( pSrc->nSrc==1 );
  73193. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  73194. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  73195. if( !pTab ) goto exit_rename_table;
  73196. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  73197. zDb = db->aDb[iDb].zName;
  73198. db->flags |= SQLITE_PreferBuiltin;
  73199. /* Get a NULL terminated version of the new table name. */
  73200. zName = sqlite3NameFromToken(db, pName);
  73201. if( !zName ) goto exit_rename_table;
  73202. /* Check that a table or index named 'zName' does not already exist
  73203. ** in database iDb. If so, this is an error.
  73204. */
  73205. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  73206. sqlite3ErrorMsg(pParse,
  73207. "there is already another table or index with this name: %s", zName);
  73208. goto exit_rename_table;
  73209. }
  73210. /* Make sure it is not a system table being altered, or a reserved name
  73211. ** that the table is being renamed to.
  73212. */
  73213. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  73214. goto exit_rename_table;
  73215. }
  73216. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  73217. exit_rename_table;
  73218. }
  73219. #ifndef SQLITE_OMIT_VIEW
  73220. if( pTab->pSelect ){
  73221. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  73222. goto exit_rename_table;
  73223. }
  73224. #endif
  73225. #ifndef SQLITE_OMIT_AUTHORIZATION
  73226. /* Invoke the authorization callback. */
  73227. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  73228. goto exit_rename_table;
  73229. }
  73230. #endif
  73231. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73232. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  73233. goto exit_rename_table;
  73234. }
  73235. if( IsVirtual(pTab) ){
  73236. pVTab = sqlite3GetVTable(db, pTab);
  73237. if( pVTab->pVtab->pModule->xRename==0 ){
  73238. pVTab = 0;
  73239. }
  73240. }
  73241. #endif
  73242. /* Begin a transaction and code the VerifyCookie for database iDb.
  73243. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  73244. ** schema). Open a statement transaction if the table is a virtual
  73245. ** table.
  73246. */
  73247. v = sqlite3GetVdbe(pParse);
  73248. if( v==0 ){
  73249. goto exit_rename_table;
  73250. }
  73251. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  73252. sqlite3ChangeCookie(pParse, iDb);
  73253. /* If this is a virtual table, invoke the xRename() function if
  73254. ** one is defined. The xRename() callback will modify the names
  73255. ** of any resources used by the v-table implementation (including other
  73256. ** SQLite tables) that are identified by the name of the virtual table.
  73257. */
  73258. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73259. if( pVTab ){
  73260. int i = ++pParse->nMem;
  73261. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  73262. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  73263. sqlite3MayAbort(pParse);
  73264. }
  73265. #endif
  73266. /* figure out how many UTF-8 characters are in zName */
  73267. zTabName = pTab->zName;
  73268. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  73269. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  73270. if( db->flags&SQLITE_ForeignKeys ){
  73271. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  73272. ** statements corresponding to all child tables of foreign key constraints
  73273. ** for which the renamed table is the parent table. */
  73274. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  73275. sqlite3NestedParse(pParse,
  73276. "UPDATE \"%w\".%s SET "
  73277. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  73278. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  73279. sqlite3DbFree(db, zWhere);
  73280. }
  73281. }
  73282. #endif
  73283. /* Modify the sqlite_master table to use the new table name. */
  73284. sqlite3NestedParse(pParse,
  73285. "UPDATE %Q.%s SET "
  73286. #ifdef SQLITE_OMIT_TRIGGER
  73287. "sql = sqlite_rename_table(sql, %Q), "
  73288. #else
  73289. "sql = CASE "
  73290. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  73291. "ELSE sqlite_rename_table(sql, %Q) END, "
  73292. #endif
  73293. "tbl_name = %Q, "
  73294. "name = CASE "
  73295. "WHEN type='table' THEN %Q "
  73296. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  73297. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  73298. "ELSE name END "
  73299. "WHERE tbl_name=%Q COLLATE nocase AND "
  73300. "(type='table' OR type='index' OR type='trigger');",
  73301. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  73302. #ifndef SQLITE_OMIT_TRIGGER
  73303. zName,
  73304. #endif
  73305. zName, nTabName, zTabName
  73306. );
  73307. #ifndef SQLITE_OMIT_AUTOINCREMENT
  73308. /* If the sqlite_sequence table exists in this database, then update
  73309. ** it with the new table name.
  73310. */
  73311. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  73312. sqlite3NestedParse(pParse,
  73313. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  73314. zDb, zName, pTab->zName);
  73315. }
  73316. #endif
  73317. #ifndef SQLITE_OMIT_TRIGGER
  73318. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  73319. ** table. Don't do this if the table being ALTERed is itself located in
  73320. ** the temp database.
  73321. */
  73322. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  73323. sqlite3NestedParse(pParse,
  73324. "UPDATE sqlite_temp_master SET "
  73325. "sql = sqlite_rename_trigger(sql, %Q), "
  73326. "tbl_name = %Q "
  73327. "WHERE %s;", zName, zName, zWhere);
  73328. sqlite3DbFree(db, zWhere);
  73329. }
  73330. #endif
  73331. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  73332. if( db->flags&SQLITE_ForeignKeys ){
  73333. FKey *p;
  73334. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  73335. Table *pFrom = p->pFrom;
  73336. if( pFrom!=pTab ){
  73337. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  73338. }
  73339. }
  73340. }
  73341. #endif
  73342. /* Drop and reload the internal table schema. */
  73343. reloadTableSchema(pParse, pTab, zName);
  73344. exit_rename_table:
  73345. sqlite3SrcListDelete(db, pSrc);
  73346. sqlite3DbFree(db, zName);
  73347. db->flags = savedDbFlags;
  73348. }
  73349. /*
  73350. ** Generate code to make sure the file format number is at least minFormat.
  73351. ** The generated code will increase the file format number if necessary.
  73352. */
  73353. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  73354. Vdbe *v;
  73355. v = sqlite3GetVdbe(pParse);
  73356. /* The VDBE should have been allocated before this routine is called.
  73357. ** If that allocation failed, we would have quit before reaching this
  73358. ** point */
  73359. if( ALWAYS(v) ){
  73360. int r1 = sqlite3GetTempReg(pParse);
  73361. int r2 = sqlite3GetTempReg(pParse);
  73362. int j1;
  73363. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  73364. sqlite3VdbeUsesBtree(v, iDb);
  73365. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  73366. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  73367. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  73368. sqlite3VdbeJumpHere(v, j1);
  73369. sqlite3ReleaseTempReg(pParse, r1);
  73370. sqlite3ReleaseTempReg(pParse, r2);
  73371. }
  73372. }
  73373. /*
  73374. ** This function is called after an "ALTER TABLE ... ADD" statement
  73375. ** has been parsed. Argument pColDef contains the text of the new
  73376. ** column definition.
  73377. **
  73378. ** The Table structure pParse->pNewTable was extended to include
  73379. ** the new column during parsing.
  73380. */
  73381. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  73382. Table *pNew; /* Copy of pParse->pNewTable */
  73383. Table *pTab; /* Table being altered */
  73384. int iDb; /* Database number */
  73385. const char *zDb; /* Database name */
  73386. const char *zTab; /* Table name */
  73387. char *zCol; /* Null-terminated column definition */
  73388. Column *pCol; /* The new column */
  73389. Expr *pDflt; /* Default value for the new column */
  73390. sqlite3 *db; /* The database connection; */
  73391. db = pParse->db;
  73392. if( pParse->nErr || db->mallocFailed ) return;
  73393. pNew = pParse->pNewTable;
  73394. assert( pNew );
  73395. assert( sqlite3BtreeHoldsAllMutexes(db) );
  73396. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  73397. zDb = db->aDb[iDb].zName;
  73398. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  73399. pCol = &pNew->aCol[pNew->nCol-1];
  73400. pDflt = pCol->pDflt;
  73401. pTab = sqlite3FindTable(db, zTab, zDb);
  73402. assert( pTab );
  73403. #ifndef SQLITE_OMIT_AUTHORIZATION
  73404. /* Invoke the authorization callback. */
  73405. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  73406. return;
  73407. }
  73408. #endif
  73409. /* If the default value for the new column was specified with a
  73410. ** literal NULL, then set pDflt to 0. This simplifies checking
  73411. ** for an SQL NULL default below.
  73412. */
  73413. if( pDflt && pDflt->op==TK_NULL ){
  73414. pDflt = 0;
  73415. }
  73416. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  73417. ** If there is a NOT NULL constraint, then the default value for the
  73418. ** column must not be NULL.
  73419. */
  73420. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  73421. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  73422. return;
  73423. }
  73424. if( pNew->pIndex ){
  73425. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  73426. return;
  73427. }
  73428. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  73429. sqlite3ErrorMsg(pParse,
  73430. "Cannot add a REFERENCES column with non-NULL default value");
  73431. return;
  73432. }
  73433. if( pCol->notNull && !pDflt ){
  73434. sqlite3ErrorMsg(pParse,
  73435. "Cannot add a NOT NULL column with default value NULL");
  73436. return;
  73437. }
  73438. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  73439. ** can handle (i.e. not CURRENT_TIME etc.)
  73440. */
  73441. if( pDflt ){
  73442. sqlite3_value *pVal;
  73443. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  73444. db->mallocFailed = 1;
  73445. return;
  73446. }
  73447. if( !pVal ){
  73448. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  73449. return;
  73450. }
  73451. sqlite3ValueFree(pVal);
  73452. }
  73453. /* Modify the CREATE TABLE statement. */
  73454. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  73455. if( zCol ){
  73456. char *zEnd = &zCol[pColDef->n-1];
  73457. int savedDbFlags = db->flags;
  73458. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  73459. *zEnd-- = '\0';
  73460. }
  73461. db->flags |= SQLITE_PreferBuiltin;
  73462. sqlite3NestedParse(pParse,
  73463. "UPDATE \"%w\".%s SET "
  73464. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  73465. "WHERE type = 'table' AND name = %Q",
  73466. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  73467. zTab
  73468. );
  73469. sqlite3DbFree(db, zCol);
  73470. db->flags = savedDbFlags;
  73471. }
  73472. /* If the default value of the new column is NULL, then set the file
  73473. ** format to 2. If the default value of the new column is not NULL,
  73474. ** the file format becomes 3.
  73475. */
  73476. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  73477. /* Reload the schema of the modified table. */
  73478. reloadTableSchema(pParse, pTab, pTab->zName);
  73479. }
  73480. /*
  73481. ** This function is called by the parser after the table-name in
  73482. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  73483. ** pSrc is the full-name of the table being altered.
  73484. **
  73485. ** This routine makes a (partial) copy of the Table structure
  73486. ** for the table being altered and sets Parse.pNewTable to point
  73487. ** to it. Routines called by the parser as the column definition
  73488. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  73489. ** the copy. The copy of the Table structure is deleted by tokenize.c
  73490. ** after parsing is finished.
  73491. **
  73492. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  73493. ** coding the "ALTER TABLE ... ADD" statement.
  73494. */
  73495. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  73496. Table *pNew;
  73497. Table *pTab;
  73498. Vdbe *v;
  73499. int iDb;
  73500. int i;
  73501. int nAlloc;
  73502. sqlite3 *db = pParse->db;
  73503. /* Look up the table being altered. */
  73504. assert( pParse->pNewTable==0 );
  73505. assert( sqlite3BtreeHoldsAllMutexes(db) );
  73506. if( db->mallocFailed ) goto exit_begin_add_column;
  73507. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  73508. if( !pTab ) goto exit_begin_add_column;
  73509. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73510. if( IsVirtual(pTab) ){
  73511. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  73512. goto exit_begin_add_column;
  73513. }
  73514. #endif
  73515. /* Make sure this is not an attempt to ALTER a view. */
  73516. if( pTab->pSelect ){
  73517. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  73518. goto exit_begin_add_column;
  73519. }
  73520. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  73521. goto exit_begin_add_column;
  73522. }
  73523. assert( pTab->addColOffset>0 );
  73524. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73525. /* Put a copy of the Table struct in Parse.pNewTable for the
  73526. ** sqlite3AddColumn() function and friends to modify. But modify
  73527. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  73528. ** prefix, we insure that the name will not collide with an existing
  73529. ** table because user table are not allowed to have the "sqlite_"
  73530. ** prefix on their name.
  73531. */
  73532. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  73533. if( !pNew ) goto exit_begin_add_column;
  73534. pParse->pNewTable = pNew;
  73535. pNew->nRef = 1;
  73536. pNew->nCol = pTab->nCol;
  73537. assert( pNew->nCol>0 );
  73538. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  73539. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  73540. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  73541. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  73542. if( !pNew->aCol || !pNew->zName ){
  73543. db->mallocFailed = 1;
  73544. goto exit_begin_add_column;
  73545. }
  73546. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  73547. for(i=0; i<pNew->nCol; i++){
  73548. Column *pCol = &pNew->aCol[i];
  73549. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  73550. pCol->zColl = 0;
  73551. pCol->zType = 0;
  73552. pCol->pDflt = 0;
  73553. pCol->zDflt = 0;
  73554. }
  73555. pNew->pSchema = db->aDb[iDb].pSchema;
  73556. pNew->addColOffset = pTab->addColOffset;
  73557. pNew->nRef = 1;
  73558. /* Begin a transaction and increment the schema cookie. */
  73559. sqlite3BeginWriteOperation(pParse, 0, iDb);
  73560. v = sqlite3GetVdbe(pParse);
  73561. if( !v ) goto exit_begin_add_column;
  73562. sqlite3ChangeCookie(pParse, iDb);
  73563. exit_begin_add_column:
  73564. sqlite3SrcListDelete(db, pSrc);
  73565. return;
  73566. }
  73567. #endif /* SQLITE_ALTER_TABLE */
  73568. /************** End of alter.c ***********************************************/
  73569. /************** Begin file analyze.c *****************************************/
  73570. /*
  73571. ** 2005 July 8
  73572. **
  73573. ** The author disclaims copyright to this source code. In place of
  73574. ** a legal notice, here is a blessing:
  73575. **
  73576. ** May you do good and not evil.
  73577. ** May you find forgiveness for yourself and forgive others.
  73578. ** May you share freely, never taking more than you give.
  73579. **
  73580. *************************************************************************
  73581. ** This file contains code associated with the ANALYZE command.
  73582. **
  73583. ** The ANALYZE command gather statistics about the content of tables
  73584. ** and indices. These statistics are made available to the query planner
  73585. ** to help it make better decisions about how to perform queries.
  73586. **
  73587. ** The following system tables are or have been supported:
  73588. **
  73589. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  73590. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  73591. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  73592. **
  73593. ** Additional tables might be added in future releases of SQLite.
  73594. ** The sqlite_stat2 table is not created or used unless the SQLite version
  73595. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  73596. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  73597. ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
  73598. ** created and used by SQLite versions 3.7.9 and later and with
  73599. ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
  73600. ** is a superset of sqlite_stat2.
  73601. **
  73602. ** Format of sqlite_stat1:
  73603. **
  73604. ** There is normally one row per index, with the index identified by the
  73605. ** name in the idx column. The tbl column is the name of the table to
  73606. ** which the index belongs. In each such row, the stat column will be
  73607. ** a string consisting of a list of integers. The first integer in this
  73608. ** list is the number of rows in the index and in the table. The second
  73609. ** integer is the average number of rows in the index that have the same
  73610. ** value in the first column of the index. The third integer is the average
  73611. ** number of rows in the index that have the same value for the first two
  73612. ** columns. The N-th integer (for N>1) is the average number of rows in
  73613. ** the index which have the same value for the first N-1 columns. For
  73614. ** a K-column index, there will be K+1 integers in the stat column. If
  73615. ** the index is unique, then the last integer will be 1.
  73616. **
  73617. ** The list of integers in the stat column can optionally be followed
  73618. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  73619. ** must be separated from the last integer by a single space. If the
  73620. ** "unordered" keyword is present, then the query planner assumes that
  73621. ** the index is unordered and will not use the index for a range query.
  73622. **
  73623. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  73624. ** column contains a single integer which is the (estimated) number of
  73625. ** rows in the table identified by sqlite_stat1.tbl.
  73626. **
  73627. ** Format of sqlite_stat2:
  73628. **
  73629. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  73630. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  73631. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  73632. ** about the distribution of keys within an index. The index is identified by
  73633. ** the "idx" column and the "tbl" column is the name of the table to which
  73634. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  73635. ** table for each index.
  73636. **
  73637. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  73638. ** inclusive are samples of the left-most key value in the index taken at
  73639. ** evenly spaced points along the index. Let the number of samples be S
  73640. ** (10 in the standard build) and let C be the number of rows in the index.
  73641. ** Then the sampled rows are given by:
  73642. **
  73643. ** rownumber = (i*C*2 + C)/(S*2)
  73644. **
  73645. ** For i between 0 and S-1. Conceptually, the index space is divided into
  73646. ** S uniform buckets and the samples are the middle row from each bucket.
  73647. **
  73648. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  73649. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  73650. ** writes the sqlite_stat2 table. This version of SQLite only supports
  73651. ** sqlite_stat3.
  73652. **
  73653. ** Format for sqlite_stat3:
  73654. **
  73655. ** The sqlite_stat3 is an enhancement to sqlite_stat2. A new name is
  73656. ** used to avoid compatibility problems.
  73657. **
  73658. ** The format of the sqlite_stat3 table is similar to the format of
  73659. ** the sqlite_stat2 table. There are multiple entries for each index.
  73660. ** The idx column names the index and the tbl column is the table of the
  73661. ** index. If the idx and tbl columns are the same, then the sample is
  73662. ** of the INTEGER PRIMARY KEY. The sample column is a value taken from
  73663. ** the left-most column of the index. The nEq column is the approximate
  73664. ** number of entires in the index whose left-most column exactly matches
  73665. ** the sample. nLt is the approximate number of entires whose left-most
  73666. ** column is less than the sample. The nDLt column is the approximate
  73667. ** number of distinct left-most entries in the index that are less than
  73668. ** the sample.
  73669. **
  73670. ** Future versions of SQLite might change to store a string containing
  73671. ** multiple integers values in the nDLt column of sqlite_stat3. The first
  73672. ** integer will be the number of prior index entires that are distinct in
  73673. ** the left-most column. The second integer will be the number of prior index
  73674. ** entries that are distinct in the first two columns. The third integer
  73675. ** will be the number of prior index entries that are distinct in the first
  73676. ** three columns. And so forth. With that extension, the nDLt field is
  73677. ** similar in function to the sqlite_stat1.stat field.
  73678. **
  73679. ** There can be an arbitrary number of sqlite_stat3 entries per index.
  73680. ** The ANALYZE command will typically generate sqlite_stat3 tables
  73681. ** that contain between 10 and 40 samples which are distributed across
  73682. ** the key space, though not uniformly, and which include samples with
  73683. ** largest possible nEq values.
  73684. */
  73685. #ifndef SQLITE_OMIT_ANALYZE
  73686. /*
  73687. ** This routine generates code that opens the sqlite_stat1 table for
  73688. ** writing with cursor iStatCur. If the library was built with the
  73689. ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
  73690. ** opened for writing using cursor (iStatCur+1)
  73691. **
  73692. ** If the sqlite_stat1 tables does not previously exist, it is created.
  73693. ** Similarly, if the sqlite_stat3 table does not exist and the library
  73694. ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
  73695. **
  73696. ** Argument zWhere may be a pointer to a buffer containing a table name,
  73697. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  73698. ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
  73699. ** with the named table are deleted. If zWhere==0, then code is generated
  73700. ** to delete all stat table entries.
  73701. */
  73702. static void openStatTable(
  73703. Parse *pParse, /* Parsing context */
  73704. int iDb, /* The database we are looking in */
  73705. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  73706. const char *zWhere, /* Delete entries for this table or index */
  73707. const char *zWhereType /* Either "tbl" or "idx" */
  73708. ){
  73709. static const struct {
  73710. const char *zName;
  73711. const char *zCols;
  73712. } aTable[] = {
  73713. { "sqlite_stat1", "tbl,idx,stat" },
  73714. #ifdef SQLITE_ENABLE_STAT3
  73715. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  73716. #endif
  73717. };
  73718. int aRoot[] = {0, 0};
  73719. u8 aCreateTbl[] = {0, 0};
  73720. int i;
  73721. sqlite3 *db = pParse->db;
  73722. Db *pDb;
  73723. Vdbe *v = sqlite3GetVdbe(pParse);
  73724. if( v==0 ) return;
  73725. assert( sqlite3BtreeHoldsAllMutexes(db) );
  73726. assert( sqlite3VdbeDb(v)==db );
  73727. pDb = &db->aDb[iDb];
  73728. /* Create new statistic tables if they do not exist, or clear them
  73729. ** if they do already exist.
  73730. */
  73731. for(i=0; i<ArraySize(aTable); i++){
  73732. const char *zTab = aTable[i].zName;
  73733. Table *pStat;
  73734. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  73735. /* The sqlite_stat[12] table does not exist. Create it. Note that a
  73736. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  73737. ** of the new table in register pParse->regRoot. This is important
  73738. ** because the OpenWrite opcode below will be needing it. */
  73739. sqlite3NestedParse(pParse,
  73740. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  73741. );
  73742. aRoot[i] = pParse->regRoot;
  73743. aCreateTbl[i] = OPFLAG_P2ISREG;
  73744. }else{
  73745. /* The table already exists. If zWhere is not NULL, delete all entries
  73746. ** associated with the table zWhere. If zWhere is NULL, delete the
  73747. ** entire contents of the table. */
  73748. aRoot[i] = pStat->tnum;
  73749. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  73750. if( zWhere ){
  73751. sqlite3NestedParse(pParse,
  73752. "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
  73753. );
  73754. }else{
  73755. /* The sqlite_stat[12] table already exists. Delete all rows. */
  73756. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  73757. }
  73758. }
  73759. }
  73760. /* Open the sqlite_stat[13] tables for writing. */
  73761. for(i=0; i<ArraySize(aTable); i++){
  73762. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  73763. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  73764. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  73765. }
  73766. }
  73767. /*
  73768. ** Recommended number of samples for sqlite_stat3
  73769. */
  73770. #ifndef SQLITE_STAT3_SAMPLES
  73771. # define SQLITE_STAT3_SAMPLES 24
  73772. #endif
  73773. /*
  73774. ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
  73775. ** share an instance of the following structure to hold their state
  73776. ** information.
  73777. */
  73778. typedef struct Stat3Accum Stat3Accum;
  73779. struct Stat3Accum {
  73780. tRowcnt nRow; /* Number of rows in the entire table */
  73781. tRowcnt nPSample; /* How often to do a periodic sample */
  73782. int iMin; /* Index of entry with minimum nEq and hash */
  73783. int mxSample; /* Maximum number of samples to accumulate */
  73784. int nSample; /* Current number of samples */
  73785. u32 iPrn; /* Pseudo-random number used for sampling */
  73786. struct Stat3Sample {
  73787. i64 iRowid; /* Rowid in main table of the key */
  73788. tRowcnt nEq; /* sqlite_stat3.nEq */
  73789. tRowcnt nLt; /* sqlite_stat3.nLt */
  73790. tRowcnt nDLt; /* sqlite_stat3.nDLt */
  73791. u8 isPSample; /* True if a periodic sample */
  73792. u32 iHash; /* Tiebreaker hash */
  73793. } *a; /* An array of samples */
  73794. };
  73795. #ifdef SQLITE_ENABLE_STAT3
  73796. /*
  73797. ** Implementation of the stat3_init(C,S) SQL function. The two parameters
  73798. ** are the number of rows in the table or index (C) and the number of samples
  73799. ** to accumulate (S).
  73800. **
  73801. ** This routine allocates the Stat3Accum object.
  73802. **
  73803. ** The return value is the Stat3Accum object (P).
  73804. */
  73805. static void stat3Init(
  73806. sqlite3_context *context,
  73807. int argc,
  73808. sqlite3_value **argv
  73809. ){
  73810. Stat3Accum *p;
  73811. tRowcnt nRow;
  73812. int mxSample;
  73813. int n;
  73814. UNUSED_PARAMETER(argc);
  73815. nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
  73816. mxSample = sqlite3_value_int(argv[1]);
  73817. n = sizeof(*p) + sizeof(p->a[0])*mxSample;
  73818. p = sqlite3MallocZero( n );
  73819. if( p==0 ){
  73820. sqlite3_result_error_nomem(context);
  73821. return;
  73822. }
  73823. p->a = (struct Stat3Sample*)&p[1];
  73824. p->nRow = nRow;
  73825. p->mxSample = mxSample;
  73826. p->nPSample = p->nRow/(mxSample/3+1) + 1;
  73827. sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
  73828. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  73829. }
  73830. static const FuncDef stat3InitFuncdef = {
  73831. 2, /* nArg */
  73832. SQLITE_UTF8, /* iPrefEnc */
  73833. 0, /* flags */
  73834. 0, /* pUserData */
  73835. 0, /* pNext */
  73836. stat3Init, /* xFunc */
  73837. 0, /* xStep */
  73838. 0, /* xFinalize */
  73839. "stat3_init", /* zName */
  73840. 0, /* pHash */
  73841. 0 /* pDestructor */
  73842. };
  73843. /*
  73844. ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function. The
  73845. ** arguments describe a single key instance. This routine makes the
  73846. ** decision about whether or not to retain this key for the sqlite_stat3
  73847. ** table.
  73848. **
  73849. ** The return value is NULL.
  73850. */
  73851. static void stat3Push(
  73852. sqlite3_context *context,
  73853. int argc,
  73854. sqlite3_value **argv
  73855. ){
  73856. Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
  73857. tRowcnt nEq = sqlite3_value_int64(argv[0]);
  73858. tRowcnt nLt = sqlite3_value_int64(argv[1]);
  73859. tRowcnt nDLt = sqlite3_value_int64(argv[2]);
  73860. i64 rowid = sqlite3_value_int64(argv[3]);
  73861. u8 isPSample = 0;
  73862. u8 doInsert = 0;
  73863. int iMin = p->iMin;
  73864. struct Stat3Sample *pSample;
  73865. int i;
  73866. u32 h;
  73867. UNUSED_PARAMETER(context);
  73868. UNUSED_PARAMETER(argc);
  73869. if( nEq==0 ) return;
  73870. h = p->iPrn = p->iPrn*1103515245 + 12345;
  73871. if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
  73872. doInsert = isPSample = 1;
  73873. }else if( p->nSample<p->mxSample ){
  73874. doInsert = 1;
  73875. }else{
  73876. if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
  73877. doInsert = 1;
  73878. }
  73879. }
  73880. if( !doInsert ) return;
  73881. if( p->nSample==p->mxSample ){
  73882. assert( p->nSample - iMin - 1 >= 0 );
  73883. memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
  73884. pSample = &p->a[p->nSample-1];
  73885. }else{
  73886. pSample = &p->a[p->nSample++];
  73887. }
  73888. pSample->iRowid = rowid;
  73889. pSample->nEq = nEq;
  73890. pSample->nLt = nLt;
  73891. pSample->nDLt = nDLt;
  73892. pSample->iHash = h;
  73893. pSample->isPSample = isPSample;
  73894. /* Find the new minimum */
  73895. if( p->nSample==p->mxSample ){
  73896. pSample = p->a;
  73897. i = 0;
  73898. while( pSample->isPSample ){
  73899. i++;
  73900. pSample++;
  73901. assert( i<p->nSample );
  73902. }
  73903. nEq = pSample->nEq;
  73904. h = pSample->iHash;
  73905. iMin = i;
  73906. for(i++, pSample++; i<p->nSample; i++, pSample++){
  73907. if( pSample->isPSample ) continue;
  73908. if( pSample->nEq<nEq
  73909. || (pSample->nEq==nEq && pSample->iHash<h)
  73910. ){
  73911. iMin = i;
  73912. nEq = pSample->nEq;
  73913. h = pSample->iHash;
  73914. }
  73915. }
  73916. p->iMin = iMin;
  73917. }
  73918. }
  73919. static const FuncDef stat3PushFuncdef = {
  73920. 5, /* nArg */
  73921. SQLITE_UTF8, /* iPrefEnc */
  73922. 0, /* flags */
  73923. 0, /* pUserData */
  73924. 0, /* pNext */
  73925. stat3Push, /* xFunc */
  73926. 0, /* xStep */
  73927. 0, /* xFinalize */
  73928. "stat3_push", /* zName */
  73929. 0, /* pHash */
  73930. 0 /* pDestructor */
  73931. };
  73932. /*
  73933. ** Implementation of the stat3_get(P,N,...) SQL function. This routine is
  73934. ** used to query the results. Content is returned for the Nth sqlite_stat3
  73935. ** row where N is between 0 and S-1 and S is the number of samples. The
  73936. ** value returned depends on the number of arguments.
  73937. **
  73938. ** argc==2 result: rowid
  73939. ** argc==3 result: nEq
  73940. ** argc==4 result: nLt
  73941. ** argc==5 result: nDLt
  73942. */
  73943. static void stat3Get(
  73944. sqlite3_context *context,
  73945. int argc,
  73946. sqlite3_value **argv
  73947. ){
  73948. int n = sqlite3_value_int(argv[1]);
  73949. Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
  73950. assert( p!=0 );
  73951. if( p->nSample<=n ) return;
  73952. switch( argc ){
  73953. case 2: sqlite3_result_int64(context, p->a[n].iRowid); break;
  73954. case 3: sqlite3_result_int64(context, p->a[n].nEq); break;
  73955. case 4: sqlite3_result_int64(context, p->a[n].nLt); break;
  73956. default: sqlite3_result_int64(context, p->a[n].nDLt); break;
  73957. }
  73958. }
  73959. static const FuncDef stat3GetFuncdef = {
  73960. -1, /* nArg */
  73961. SQLITE_UTF8, /* iPrefEnc */
  73962. 0, /* flags */
  73963. 0, /* pUserData */
  73964. 0, /* pNext */
  73965. stat3Get, /* xFunc */
  73966. 0, /* xStep */
  73967. 0, /* xFinalize */
  73968. "stat3_get", /* zName */
  73969. 0, /* pHash */
  73970. 0 /* pDestructor */
  73971. };
  73972. #endif /* SQLITE_ENABLE_STAT3 */
  73973. /*
  73974. ** Generate code to do an analysis of all indices associated with
  73975. ** a single table.
  73976. */
  73977. static void analyzeOneTable(
  73978. Parse *pParse, /* Parser context */
  73979. Table *pTab, /* Table whose indices are to be analyzed */
  73980. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  73981. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  73982. int iMem /* Available memory locations begin here */
  73983. ){
  73984. sqlite3 *db = pParse->db; /* Database handle */
  73985. Index *pIdx; /* An index to being analyzed */
  73986. int iIdxCur; /* Cursor open on index being analyzed */
  73987. Vdbe *v; /* The virtual machine being built up */
  73988. int i; /* Loop counter */
  73989. int topOfLoop; /* The top of the loop */
  73990. int endOfLoop; /* The end of the loop */
  73991. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  73992. int iDb; /* Index of database containing pTab */
  73993. int regTabname = iMem++; /* Register containing table name */
  73994. int regIdxname = iMem++; /* Register containing index name */
  73995. int regStat1 = iMem++; /* The stat column of sqlite_stat1 */
  73996. #ifdef SQLITE_ENABLE_STAT3
  73997. int regNumEq = regStat1; /* Number of instances. Same as regStat1 */
  73998. int regNumLt = iMem++; /* Number of keys less than regSample */
  73999. int regNumDLt = iMem++; /* Number of distinct keys less than regSample */
  74000. int regSample = iMem++; /* The next sample value */
  74001. int regRowid = regSample; /* Rowid of a sample */
  74002. int regAccum = iMem++; /* Register to hold Stat3Accum object */
  74003. int regLoop = iMem++; /* Loop counter */
  74004. int regCount = iMem++; /* Number of rows in the table or index */
  74005. int regTemp1 = iMem++; /* Intermediate register */
  74006. int regTemp2 = iMem++; /* Intermediate register */
  74007. int once = 1; /* One-time initialization */
  74008. int shortJump = 0; /* Instruction address */
  74009. int iTabCur = pParse->nTab++; /* Table cursor */
  74010. #endif
  74011. int regCol = iMem++; /* Content of a column in analyzed table */
  74012. int regRec = iMem++; /* Register holding completed record */
  74013. int regTemp = iMem++; /* Temporary use register */
  74014. int regNewRowid = iMem++; /* Rowid for the inserted record */
  74015. v = sqlite3GetVdbe(pParse);
  74016. if( v==0 || NEVER(pTab==0) ){
  74017. return;
  74018. }
  74019. if( pTab->tnum==0 ){
  74020. /* Do not gather statistics on views or virtual tables */
  74021. return;
  74022. }
  74023. if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
  74024. /* Do not gather statistics on system tables */
  74025. return;
  74026. }
  74027. assert( sqlite3BtreeHoldsAllMutexes(db) );
  74028. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  74029. assert( iDb>=0 );
  74030. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  74031. #ifndef SQLITE_OMIT_AUTHORIZATION
  74032. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  74033. db->aDb[iDb].zName ) ){
  74034. return;
  74035. }
  74036. #endif
  74037. /* Establish a read-lock on the table at the shared-cache level. */
  74038. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  74039. iIdxCur = pParse->nTab++;
  74040. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  74041. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  74042. int nCol;
  74043. KeyInfo *pKey;
  74044. int addrIfNot = 0; /* address of OP_IfNot */
  74045. int *aChngAddr; /* Array of jump instruction addresses */
  74046. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  74047. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  74048. nCol = pIdx->nColumn;
  74049. aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
  74050. if( aChngAddr==0 ) continue;
  74051. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  74052. if( iMem+1+(nCol*2)>pParse->nMem ){
  74053. pParse->nMem = iMem+1+(nCol*2);
  74054. }
  74055. /* Open a cursor to the index to be analyzed. */
  74056. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  74057. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
  74058. (char *)pKey, P4_KEYINFO_HANDOFF);
  74059. VdbeComment((v, "%s", pIdx->zName));
  74060. /* Populate the register containing the index name. */
  74061. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  74062. #ifdef SQLITE_ENABLE_STAT3
  74063. if( once ){
  74064. once = 0;
  74065. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  74066. }
  74067. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
  74068. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
  74069. sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
  74070. sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
  74071. sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
  74072. sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
  74073. sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
  74074. (char*)&stat3InitFuncdef, P4_FUNCDEF);
  74075. sqlite3VdbeChangeP5(v, 2);
  74076. #endif /* SQLITE_ENABLE_STAT3 */
  74077. /* The block of memory cells initialized here is used as follows.
  74078. **
  74079. ** iMem:
  74080. ** The total number of rows in the table.
  74081. **
  74082. ** iMem+1 .. iMem+nCol:
  74083. ** Number of distinct entries in index considering the
  74084. ** left-most N columns only, where N is between 1 and nCol,
  74085. ** inclusive.
  74086. **
  74087. ** iMem+nCol+1 .. Mem+2*nCol:
  74088. ** Previous value of indexed columns, from left to right.
  74089. **
  74090. ** Cells iMem through iMem+nCol are initialized to 0. The others are
  74091. ** initialized to contain an SQL NULL.
  74092. */
  74093. for(i=0; i<=nCol; i++){
  74094. sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
  74095. }
  74096. for(i=0; i<nCol; i++){
  74097. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
  74098. }
  74099. /* Start the analysis loop. This loop runs through all the entries in
  74100. ** the index b-tree. */
  74101. endOfLoop = sqlite3VdbeMakeLabel(v);
  74102. sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
  74103. topOfLoop = sqlite3VdbeCurrentAddr(v);
  74104. sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1); /* Increment row counter */
  74105. for(i=0; i<nCol; i++){
  74106. CollSeq *pColl;
  74107. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
  74108. if( i==0 ){
  74109. /* Always record the very first row */
  74110. addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
  74111. }
  74112. assert( pIdx->azColl!=0 );
  74113. assert( pIdx->azColl[i]!=0 );
  74114. pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  74115. aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
  74116. (char*)pColl, P4_COLLSEQ);
  74117. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  74118. VdbeComment((v, "jump if column %d changed", i));
  74119. #ifdef SQLITE_ENABLE_STAT3
  74120. if( i==0 ){
  74121. sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
  74122. VdbeComment((v, "incr repeat count"));
  74123. }
  74124. #endif
  74125. }
  74126. sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
  74127. for(i=0; i<nCol; i++){
  74128. sqlite3VdbeJumpHere(v, aChngAddr[i]); /* Set jump dest for the OP_Ne */
  74129. if( i==0 ){
  74130. sqlite3VdbeJumpHere(v, addrIfNot); /* Jump dest for OP_IfNot */
  74131. #ifdef SQLITE_ENABLE_STAT3
  74132. sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
  74133. (char*)&stat3PushFuncdef, P4_FUNCDEF);
  74134. sqlite3VdbeChangeP5(v, 5);
  74135. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
  74136. sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
  74137. sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
  74138. sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
  74139. #endif
  74140. }
  74141. sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
  74142. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
  74143. }
  74144. sqlite3DbFree(db, aChngAddr);
  74145. /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
  74146. sqlite3VdbeResolveLabel(v, endOfLoop);
  74147. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
  74148. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  74149. #ifdef SQLITE_ENABLE_STAT3
  74150. sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
  74151. (char*)&stat3PushFuncdef, P4_FUNCDEF);
  74152. sqlite3VdbeChangeP5(v, 5);
  74153. sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
  74154. shortJump =
  74155. sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
  74156. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
  74157. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  74158. sqlite3VdbeChangeP5(v, 2);
  74159. sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
  74160. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
  74161. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
  74162. sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
  74163. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
  74164. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  74165. sqlite3VdbeChangeP5(v, 3);
  74166. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
  74167. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  74168. sqlite3VdbeChangeP5(v, 4);
  74169. sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
  74170. (char*)&stat3GetFuncdef, P4_FUNCDEF);
  74171. sqlite3VdbeChangeP5(v, 5);
  74172. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
  74173. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  74174. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
  74175. sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
  74176. sqlite3VdbeJumpHere(v, shortJump+2);
  74177. #endif
  74178. /* Store the results in sqlite_stat1.
  74179. **
  74180. ** The result is a single row of the sqlite_stat1 table. The first
  74181. ** two columns are the names of the table and index. The third column
  74182. ** is a string composed of a list of integer statistics about the
  74183. ** index. The first integer in the list is the total number of entries
  74184. ** in the index. There is one additional integer in the list for each
  74185. ** column of the table. This additional integer is a guess of how many
  74186. ** rows of the table the index will select. If D is the count of distinct
  74187. ** values and K is the total number of rows, then the integer is computed
  74188. ** as:
  74189. **
  74190. ** I = (K+D-1)/D
  74191. **
  74192. ** If K==0 then no entry is made into the sqlite_stat1 table.
  74193. ** If K>0 then it is always the case the D>0 so division by zero
  74194. ** is never possible.
  74195. */
  74196. sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
  74197. if( jZeroRows<0 ){
  74198. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
  74199. }
  74200. for(i=0; i<nCol; i++){
  74201. sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
  74202. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
  74203. sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
  74204. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  74205. sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
  74206. sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
  74207. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
  74208. }
  74209. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  74210. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  74211. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
  74212. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  74213. }
  74214. /* If the table has no indices, create a single sqlite_stat1 entry
  74215. ** containing NULL as the index name and the row count as the content.
  74216. */
  74217. if( pTab->pIndex==0 ){
  74218. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
  74219. VdbeComment((v, "%s", pTab->zName));
  74220. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
  74221. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  74222. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  74223. }else{
  74224. sqlite3VdbeJumpHere(v, jZeroRows);
  74225. jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
  74226. }
  74227. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  74228. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  74229. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  74230. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
  74231. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  74232. if( pParse->nMem<regRec ) pParse->nMem = regRec;
  74233. sqlite3VdbeJumpHere(v, jZeroRows);
  74234. }
  74235. /*
  74236. ** Generate code that will cause the most recent index analysis to
  74237. ** be loaded into internal hash tables where is can be used.
  74238. */
  74239. static void loadAnalysis(Parse *pParse, int iDb){
  74240. Vdbe *v = sqlite3GetVdbe(pParse);
  74241. if( v ){
  74242. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  74243. }
  74244. }
  74245. /*
  74246. ** Generate code that will do an analysis of an entire database
  74247. */
  74248. static void analyzeDatabase(Parse *pParse, int iDb){
  74249. sqlite3 *db = pParse->db;
  74250. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  74251. HashElem *k;
  74252. int iStatCur;
  74253. int iMem;
  74254. sqlite3BeginWriteOperation(pParse, 0, iDb);
  74255. iStatCur = pParse->nTab;
  74256. pParse->nTab += 3;
  74257. openStatTable(pParse, iDb, iStatCur, 0, 0);
  74258. iMem = pParse->nMem+1;
  74259. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  74260. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  74261. Table *pTab = (Table*)sqliteHashData(k);
  74262. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
  74263. }
  74264. loadAnalysis(pParse, iDb);
  74265. }
  74266. /*
  74267. ** Generate code that will do an analysis of a single table in
  74268. ** a database. If pOnlyIdx is not NULL then it is a single index
  74269. ** in pTab that should be analyzed.
  74270. */
  74271. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  74272. int iDb;
  74273. int iStatCur;
  74274. assert( pTab!=0 );
  74275. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  74276. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  74277. sqlite3BeginWriteOperation(pParse, 0, iDb);
  74278. iStatCur = pParse->nTab;
  74279. pParse->nTab += 3;
  74280. if( pOnlyIdx ){
  74281. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  74282. }else{
  74283. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  74284. }
  74285. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
  74286. loadAnalysis(pParse, iDb);
  74287. }
  74288. /*
  74289. ** Generate code for the ANALYZE command. The parser calls this routine
  74290. ** when it recognizes an ANALYZE command.
  74291. **
  74292. ** ANALYZE -- 1
  74293. ** ANALYZE <database> -- 2
  74294. ** ANALYZE ?<database>.?<tablename> -- 3
  74295. **
  74296. ** Form 1 causes all indices in all attached databases to be analyzed.
  74297. ** Form 2 analyzes all indices the single database named.
  74298. ** Form 3 analyzes all indices associated with the named table.
  74299. */
  74300. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  74301. sqlite3 *db = pParse->db;
  74302. int iDb;
  74303. int i;
  74304. char *z, *zDb;
  74305. Table *pTab;
  74306. Index *pIdx;
  74307. Token *pTableName;
  74308. /* Read the database schema. If an error occurs, leave an error message
  74309. ** and code in pParse and return NULL. */
  74310. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  74311. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  74312. return;
  74313. }
  74314. assert( pName2!=0 || pName1==0 );
  74315. if( pName1==0 ){
  74316. /* Form 1: Analyze everything */
  74317. for(i=0; i<db->nDb; i++){
  74318. if( i==1 ) continue; /* Do not analyze the TEMP database */
  74319. analyzeDatabase(pParse, i);
  74320. }
  74321. }else if( pName2->n==0 ){
  74322. /* Form 2: Analyze the database or table named */
  74323. iDb = sqlite3FindDb(db, pName1);
  74324. if( iDb>=0 ){
  74325. analyzeDatabase(pParse, iDb);
  74326. }else{
  74327. z = sqlite3NameFromToken(db, pName1);
  74328. if( z ){
  74329. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  74330. analyzeTable(pParse, pIdx->pTable, pIdx);
  74331. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  74332. analyzeTable(pParse, pTab, 0);
  74333. }
  74334. sqlite3DbFree(db, z);
  74335. }
  74336. }
  74337. }else{
  74338. /* Form 3: Analyze the fully qualified table name */
  74339. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  74340. if( iDb>=0 ){
  74341. zDb = db->aDb[iDb].zName;
  74342. z = sqlite3NameFromToken(db, pTableName);
  74343. if( z ){
  74344. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  74345. analyzeTable(pParse, pIdx->pTable, pIdx);
  74346. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  74347. analyzeTable(pParse, pTab, 0);
  74348. }
  74349. sqlite3DbFree(db, z);
  74350. }
  74351. }
  74352. }
  74353. }
  74354. /*
  74355. ** Used to pass information from the analyzer reader through to the
  74356. ** callback routine.
  74357. */
  74358. typedef struct analysisInfo analysisInfo;
  74359. struct analysisInfo {
  74360. sqlite3 *db;
  74361. const char *zDatabase;
  74362. };
  74363. /*
  74364. ** This callback is invoked once for each index when reading the
  74365. ** sqlite_stat1 table.
  74366. **
  74367. ** argv[0] = name of the table
  74368. ** argv[1] = name of the index (might be NULL)
  74369. ** argv[2] = results of analysis - on integer for each column
  74370. **
  74371. ** Entries for which argv[1]==NULL simply record the number of rows in
  74372. ** the table.
  74373. */
  74374. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  74375. analysisInfo *pInfo = (analysisInfo*)pData;
  74376. Index *pIndex;
  74377. Table *pTable;
  74378. int i, c, n;
  74379. tRowcnt v;
  74380. const char *z;
  74381. assert( argc==3 );
  74382. UNUSED_PARAMETER2(NotUsed, argc);
  74383. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  74384. return 0;
  74385. }
  74386. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  74387. if( pTable==0 ){
  74388. return 0;
  74389. }
  74390. if( argv[1] ){
  74391. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  74392. }else{
  74393. pIndex = 0;
  74394. }
  74395. n = pIndex ? pIndex->nColumn : 0;
  74396. z = argv[2];
  74397. for(i=0; *z && i<=n; i++){
  74398. v = 0;
  74399. while( (c=z[0])>='0' && c<='9' ){
  74400. v = v*10 + c - '0';
  74401. z++;
  74402. }
  74403. if( i==0 ) pTable->nRowEst = v;
  74404. if( pIndex==0 ) break;
  74405. pIndex->aiRowEst[i] = v;
  74406. if( *z==' ' ) z++;
  74407. if( memcmp(z, "unordered", 10)==0 ){
  74408. pIndex->bUnordered = 1;
  74409. break;
  74410. }
  74411. }
  74412. return 0;
  74413. }
  74414. /*
  74415. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  74416. ** and its contents.
  74417. */
  74418. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  74419. #ifdef SQLITE_ENABLE_STAT3
  74420. if( pIdx->aSample ){
  74421. int j;
  74422. for(j=0; j<pIdx->nSample; j++){
  74423. IndexSample *p = &pIdx->aSample[j];
  74424. if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
  74425. sqlite3DbFree(db, p->u.z);
  74426. }
  74427. }
  74428. sqlite3DbFree(db, pIdx->aSample);
  74429. }
  74430. if( db && db->pnBytesFreed==0 ){
  74431. pIdx->nSample = 0;
  74432. pIdx->aSample = 0;
  74433. }
  74434. #else
  74435. UNUSED_PARAMETER(db);
  74436. UNUSED_PARAMETER(pIdx);
  74437. #endif
  74438. }
  74439. #ifdef SQLITE_ENABLE_STAT3
  74440. /*
  74441. ** Load content from the sqlite_stat3 table into the Index.aSample[]
  74442. ** arrays of all indices.
  74443. */
  74444. static int loadStat3(sqlite3 *db, const char *zDb){
  74445. int rc; /* Result codes from subroutines */
  74446. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  74447. char *zSql; /* Text of the SQL statement */
  74448. Index *pPrevIdx = 0; /* Previous index in the loop */
  74449. int idx = 0; /* slot in pIdx->aSample[] for next sample */
  74450. int eType; /* Datatype of a sample */
  74451. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  74452. assert( db->lookaside.bEnabled==0 );
  74453. if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  74454. return SQLITE_OK;
  74455. }
  74456. zSql = sqlite3MPrintf(db,
  74457. "SELECT idx,count(*) FROM %Q.sqlite_stat3"
  74458. " GROUP BY idx", zDb);
  74459. if( !zSql ){
  74460. return SQLITE_NOMEM;
  74461. }
  74462. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  74463. sqlite3DbFree(db, zSql);
  74464. if( rc ) return rc;
  74465. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  74466. char *zIndex; /* Index name */
  74467. Index *pIdx; /* Pointer to the index object */
  74468. int nSample; /* Number of samples */
  74469. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  74470. if( zIndex==0 ) continue;
  74471. nSample = sqlite3_column_int(pStmt, 1);
  74472. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  74473. if( pIdx==0 ) continue;
  74474. assert( pIdx->nSample==0 );
  74475. pIdx->nSample = nSample;
  74476. pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
  74477. pIdx->avgEq = pIdx->aiRowEst[1];
  74478. if( pIdx->aSample==0 ){
  74479. db->mallocFailed = 1;
  74480. sqlite3_finalize(pStmt);
  74481. return SQLITE_NOMEM;
  74482. }
  74483. }
  74484. rc = sqlite3_finalize(pStmt);
  74485. if( rc ) return rc;
  74486. zSql = sqlite3MPrintf(db,
  74487. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
  74488. if( !zSql ){
  74489. return SQLITE_NOMEM;
  74490. }
  74491. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  74492. sqlite3DbFree(db, zSql);
  74493. if( rc ) return rc;
  74494. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  74495. char *zIndex; /* Index name */
  74496. Index *pIdx; /* Pointer to the index object */
  74497. int i; /* Loop counter */
  74498. tRowcnt sumEq; /* Sum of the nEq values */
  74499. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  74500. if( zIndex==0 ) continue;
  74501. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  74502. if( pIdx==0 ) continue;
  74503. if( pIdx==pPrevIdx ){
  74504. idx++;
  74505. }else{
  74506. pPrevIdx = pIdx;
  74507. idx = 0;
  74508. }
  74509. assert( idx<pIdx->nSample );
  74510. pSample = &pIdx->aSample[idx];
  74511. pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
  74512. pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
  74513. pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
  74514. if( idx==pIdx->nSample-1 ){
  74515. if( pSample->nDLt>0 ){
  74516. for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
  74517. pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
  74518. }
  74519. if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
  74520. }
  74521. eType = sqlite3_column_type(pStmt, 4);
  74522. pSample->eType = (u8)eType;
  74523. switch( eType ){
  74524. case SQLITE_INTEGER: {
  74525. pSample->u.i = sqlite3_column_int64(pStmt, 4);
  74526. break;
  74527. }
  74528. case SQLITE_FLOAT: {
  74529. pSample->u.r = sqlite3_column_double(pStmt, 4);
  74530. break;
  74531. }
  74532. case SQLITE_NULL: {
  74533. break;
  74534. }
  74535. default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
  74536. const char *z = (const char *)(
  74537. (eType==SQLITE_BLOB) ?
  74538. sqlite3_column_blob(pStmt, 4):
  74539. sqlite3_column_text(pStmt, 4)
  74540. );
  74541. int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
  74542. pSample->nByte = n;
  74543. if( n < 1){
  74544. pSample->u.z = 0;
  74545. }else{
  74546. pSample->u.z = sqlite3DbMallocRaw(db, n);
  74547. if( pSample->u.z==0 ){
  74548. db->mallocFailed = 1;
  74549. sqlite3_finalize(pStmt);
  74550. return SQLITE_NOMEM;
  74551. }
  74552. memcpy(pSample->u.z, z, n);
  74553. }
  74554. }
  74555. }
  74556. }
  74557. return sqlite3_finalize(pStmt);
  74558. }
  74559. #endif /* SQLITE_ENABLE_STAT3 */
  74560. /*
  74561. ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
  74562. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  74563. ** arrays. The contents of sqlite_stat3 are used to populate the
  74564. ** Index.aSample[] arrays.
  74565. **
  74566. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  74567. ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
  74568. ** during compilation and the sqlite_stat3 table is present, no data is
  74569. ** read from it.
  74570. **
  74571. ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
  74572. ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
  74573. ** returned. However, in this case, data is read from the sqlite_stat1
  74574. ** table (if it is present) before returning.
  74575. **
  74576. ** If an OOM error occurs, this function always sets db->mallocFailed.
  74577. ** This means if the caller does not care about other errors, the return
  74578. ** code may be ignored.
  74579. */
  74580. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  74581. analysisInfo sInfo;
  74582. HashElem *i;
  74583. char *zSql;
  74584. int rc;
  74585. assert( iDb>=0 && iDb<db->nDb );
  74586. assert( db->aDb[iDb].pBt!=0 );
  74587. /* Clear any prior statistics */
  74588. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  74589. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  74590. Index *pIdx = sqliteHashData(i);
  74591. sqlite3DefaultRowEst(pIdx);
  74592. #ifdef SQLITE_ENABLE_STAT3
  74593. sqlite3DeleteIndexSamples(db, pIdx);
  74594. pIdx->aSample = 0;
  74595. #endif
  74596. }
  74597. /* Check to make sure the sqlite_stat1 table exists */
  74598. sInfo.db = db;
  74599. sInfo.zDatabase = db->aDb[iDb].zName;
  74600. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  74601. return SQLITE_ERROR;
  74602. }
  74603. /* Load new statistics out of the sqlite_stat1 table */
  74604. zSql = sqlite3MPrintf(db,
  74605. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  74606. if( zSql==0 ){
  74607. rc = SQLITE_NOMEM;
  74608. }else{
  74609. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  74610. sqlite3DbFree(db, zSql);
  74611. }
  74612. /* Load the statistics from the sqlite_stat3 table. */
  74613. #ifdef SQLITE_ENABLE_STAT3
  74614. if( rc==SQLITE_OK ){
  74615. int lookasideEnabled = db->lookaside.bEnabled;
  74616. db->lookaside.bEnabled = 0;
  74617. rc = loadStat3(db, sInfo.zDatabase);
  74618. db->lookaside.bEnabled = lookasideEnabled;
  74619. }
  74620. #endif
  74621. if( rc==SQLITE_NOMEM ){
  74622. db->mallocFailed = 1;
  74623. }
  74624. return rc;
  74625. }
  74626. #endif /* SQLITE_OMIT_ANALYZE */
  74627. /************** End of analyze.c *********************************************/
  74628. /************** Begin file attach.c ******************************************/
  74629. /*
  74630. ** 2003 April 6
  74631. **
  74632. ** The author disclaims copyright to this source code. In place of
  74633. ** a legal notice, here is a blessing:
  74634. **
  74635. ** May you do good and not evil.
  74636. ** May you find forgiveness for yourself and forgive others.
  74637. ** May you share freely, never taking more than you give.
  74638. **
  74639. *************************************************************************
  74640. ** This file contains code used to implement the ATTACH and DETACH commands.
  74641. */
  74642. #ifndef SQLITE_OMIT_ATTACH
  74643. /*
  74644. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  74645. ** is slightly different from resolving a normal SQL expression, because simple
  74646. ** identifiers are treated as strings, not possible column names or aliases.
  74647. **
  74648. ** i.e. if the parser sees:
  74649. **
  74650. ** ATTACH DATABASE abc AS def
  74651. **
  74652. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  74653. ** looking for columns of the same name.
  74654. **
  74655. ** This only applies to the root node of pExpr, so the statement:
  74656. **
  74657. ** ATTACH DATABASE abc||def AS 'db2'
  74658. **
  74659. ** will fail because neither abc or def can be resolved.
  74660. */
  74661. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  74662. {
  74663. int rc = SQLITE_OK;
  74664. if( pExpr ){
  74665. if( pExpr->op!=TK_ID ){
  74666. rc = sqlite3ResolveExprNames(pName, pExpr);
  74667. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  74668. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  74669. return SQLITE_ERROR;
  74670. }
  74671. }else{
  74672. pExpr->op = TK_STRING;
  74673. }
  74674. }
  74675. return rc;
  74676. }
  74677. /*
  74678. ** An SQL user-function registered to do the work of an ATTACH statement. The
  74679. ** three arguments to the function come directly from an attach statement:
  74680. **
  74681. ** ATTACH DATABASE x AS y KEY z
  74682. **
  74683. ** SELECT sqlite_attach(x, y, z)
  74684. **
  74685. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  74686. ** third argument.
  74687. */
  74688. static void attachFunc(
  74689. sqlite3_context *context,
  74690. int NotUsed,
  74691. sqlite3_value **argv
  74692. ){
  74693. int i;
  74694. int rc = 0;
  74695. sqlite3 *db = sqlite3_context_db_handle(context);
  74696. const char *zName;
  74697. const char *zFile;
  74698. char *zPath = 0;
  74699. char *zErr = 0;
  74700. unsigned int flags;
  74701. Db *aNew;
  74702. char *zErrDyn = 0;
  74703. sqlite3_vfs *pVfs;
  74704. UNUSED_PARAMETER(NotUsed);
  74705. zFile = (const char *)sqlite3_value_text(argv[0]);
  74706. zName = (const char *)sqlite3_value_text(argv[1]);
  74707. if( zFile==0 ) zFile = "";
  74708. if( zName==0 ) zName = "";
  74709. /* Check for the following errors:
  74710. **
  74711. ** * Too many attached databases,
  74712. ** * Transaction currently open
  74713. ** * Specified database name already being used.
  74714. */
  74715. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  74716. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  74717. db->aLimit[SQLITE_LIMIT_ATTACHED]
  74718. );
  74719. goto attach_error;
  74720. }
  74721. if( !db->autoCommit ){
  74722. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  74723. goto attach_error;
  74724. }
  74725. for(i=0; i<db->nDb; i++){
  74726. char *z = db->aDb[i].zName;
  74727. assert( z && zName );
  74728. if( sqlite3StrICmp(z, zName)==0 ){
  74729. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  74730. goto attach_error;
  74731. }
  74732. }
  74733. /* Allocate the new entry in the db->aDb[] array and initialise the schema
  74734. ** hash tables.
  74735. */
  74736. if( db->aDb==db->aDbStatic ){
  74737. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  74738. if( aNew==0 ) return;
  74739. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  74740. }else{
  74741. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  74742. if( aNew==0 ) return;
  74743. }
  74744. db->aDb = aNew;
  74745. aNew = &db->aDb[db->nDb];
  74746. memset(aNew, 0, sizeof(*aNew));
  74747. /* Open the database file. If the btree is successfully opened, use
  74748. ** it to obtain the database schema. At this point the schema may
  74749. ** or may not be initialised.
  74750. */
  74751. flags = db->openFlags;
  74752. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  74753. if( rc!=SQLITE_OK ){
  74754. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  74755. sqlite3_result_error(context, zErr, -1);
  74756. sqlite3_free(zErr);
  74757. return;
  74758. }
  74759. assert( pVfs );
  74760. flags |= SQLITE_OPEN_MAIN_DB;
  74761. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  74762. sqlite3_free( zPath );
  74763. db->nDb++;
  74764. if( rc==SQLITE_CONSTRAINT ){
  74765. rc = SQLITE_ERROR;
  74766. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  74767. }else if( rc==SQLITE_OK ){
  74768. Pager *pPager;
  74769. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  74770. if( !aNew->pSchema ){
  74771. rc = SQLITE_NOMEM;
  74772. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  74773. zErrDyn = sqlite3MPrintf(db,
  74774. "attached databases must use the same text encoding as main database");
  74775. rc = SQLITE_ERROR;
  74776. }
  74777. pPager = sqlite3BtreePager(aNew->pBt);
  74778. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  74779. sqlite3BtreeSecureDelete(aNew->pBt,
  74780. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  74781. }
  74782. aNew->safety_level = 3;
  74783. aNew->zName = sqlite3DbStrDup(db, zName);
  74784. if( rc==SQLITE_OK && aNew->zName==0 ){
  74785. rc = SQLITE_NOMEM;
  74786. }
  74787. #ifdef SQLITE_HAS_CODEC
  74788. if( rc==SQLITE_OK ){
  74789. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  74790. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  74791. int nKey;
  74792. char *zKey;
  74793. int t = sqlite3_value_type(argv[2]);
  74794. switch( t ){
  74795. case SQLITE_INTEGER:
  74796. case SQLITE_FLOAT:
  74797. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  74798. rc = SQLITE_ERROR;
  74799. break;
  74800. case SQLITE_TEXT:
  74801. case SQLITE_BLOB:
  74802. nKey = sqlite3_value_bytes(argv[2]);
  74803. zKey = (char *)sqlite3_value_blob(argv[2]);
  74804. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  74805. break;
  74806. case SQLITE_NULL:
  74807. /* No key specified. Use the key from the main database */
  74808. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  74809. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  74810. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  74811. }
  74812. break;
  74813. }
  74814. }
  74815. #endif
  74816. /* If the file was opened successfully, read the schema for the new database.
  74817. ** If this fails, or if opening the file failed, then close the file and
  74818. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  74819. ** we found it.
  74820. */
  74821. if( rc==SQLITE_OK ){
  74822. sqlite3BtreeEnterAll(db);
  74823. rc = sqlite3Init(db, &zErrDyn);
  74824. sqlite3BtreeLeaveAll(db);
  74825. }
  74826. if( rc ){
  74827. int iDb = db->nDb - 1;
  74828. assert( iDb>=2 );
  74829. if( db->aDb[iDb].pBt ){
  74830. sqlite3BtreeClose(db->aDb[iDb].pBt);
  74831. db->aDb[iDb].pBt = 0;
  74832. db->aDb[iDb].pSchema = 0;
  74833. }
  74834. sqlite3ResetAllSchemasOfConnection(db);
  74835. db->nDb = iDb;
  74836. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  74837. db->mallocFailed = 1;
  74838. sqlite3DbFree(db, zErrDyn);
  74839. zErrDyn = sqlite3MPrintf(db, "out of memory");
  74840. }else if( zErrDyn==0 ){
  74841. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  74842. }
  74843. goto attach_error;
  74844. }
  74845. return;
  74846. attach_error:
  74847. /* Return an error if we get here */
  74848. if( zErrDyn ){
  74849. sqlite3_result_error(context, zErrDyn, -1);
  74850. sqlite3DbFree(db, zErrDyn);
  74851. }
  74852. if( rc ) sqlite3_result_error_code(context, rc);
  74853. }
  74854. /*
  74855. ** An SQL user-function registered to do the work of an DETACH statement. The
  74856. ** three arguments to the function come directly from a detach statement:
  74857. **
  74858. ** DETACH DATABASE x
  74859. **
  74860. ** SELECT sqlite_detach(x)
  74861. */
  74862. static void detachFunc(
  74863. sqlite3_context *context,
  74864. int NotUsed,
  74865. sqlite3_value **argv
  74866. ){
  74867. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  74868. sqlite3 *db = sqlite3_context_db_handle(context);
  74869. int i;
  74870. Db *pDb = 0;
  74871. char zErr[128];
  74872. UNUSED_PARAMETER(NotUsed);
  74873. if( zName==0 ) zName = "";
  74874. for(i=0; i<db->nDb; i++){
  74875. pDb = &db->aDb[i];
  74876. if( pDb->pBt==0 ) continue;
  74877. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  74878. }
  74879. if( i>=db->nDb ){
  74880. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  74881. goto detach_error;
  74882. }
  74883. if( i<2 ){
  74884. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  74885. goto detach_error;
  74886. }
  74887. if( !db->autoCommit ){
  74888. sqlite3_snprintf(sizeof(zErr), zErr,
  74889. "cannot DETACH database within transaction");
  74890. goto detach_error;
  74891. }
  74892. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  74893. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  74894. goto detach_error;
  74895. }
  74896. sqlite3BtreeClose(pDb->pBt);
  74897. pDb->pBt = 0;
  74898. pDb->pSchema = 0;
  74899. sqlite3ResetAllSchemasOfConnection(db);
  74900. return;
  74901. detach_error:
  74902. sqlite3_result_error(context, zErr, -1);
  74903. }
  74904. /*
  74905. ** This procedure generates VDBE code for a single invocation of either the
  74906. ** sqlite_detach() or sqlite_attach() SQL user functions.
  74907. */
  74908. static void codeAttach(
  74909. Parse *pParse, /* The parser context */
  74910. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  74911. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  74912. Expr *pAuthArg, /* Expression to pass to authorization callback */
  74913. Expr *pFilename, /* Name of database file */
  74914. Expr *pDbname, /* Name of the database to use internally */
  74915. Expr *pKey /* Database key for encryption extension */
  74916. ){
  74917. int rc;
  74918. NameContext sName;
  74919. Vdbe *v;
  74920. sqlite3* db = pParse->db;
  74921. int regArgs;
  74922. memset(&sName, 0, sizeof(NameContext));
  74923. sName.pParse = pParse;
  74924. if(
  74925. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  74926. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  74927. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  74928. ){
  74929. pParse->nErr++;
  74930. goto attach_end;
  74931. }
  74932. #ifndef SQLITE_OMIT_AUTHORIZATION
  74933. if( pAuthArg ){
  74934. char *zAuthArg;
  74935. if( pAuthArg->op==TK_STRING ){
  74936. zAuthArg = pAuthArg->u.zToken;
  74937. }else{
  74938. zAuthArg = 0;
  74939. }
  74940. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  74941. if(rc!=SQLITE_OK ){
  74942. goto attach_end;
  74943. }
  74944. }
  74945. #endif /* SQLITE_OMIT_AUTHORIZATION */
  74946. v = sqlite3GetVdbe(pParse);
  74947. regArgs = sqlite3GetTempRange(pParse, 4);
  74948. sqlite3ExprCode(pParse, pFilename, regArgs);
  74949. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  74950. sqlite3ExprCode(pParse, pKey, regArgs+2);
  74951. assert( v || db->mallocFailed );
  74952. if( v ){
  74953. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  74954. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  74955. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  74956. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  74957. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  74958. ** statement only). For DETACH, set it to false (expire all existing
  74959. ** statements).
  74960. */
  74961. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  74962. }
  74963. attach_end:
  74964. sqlite3ExprDelete(db, pFilename);
  74965. sqlite3ExprDelete(db, pDbname);
  74966. sqlite3ExprDelete(db, pKey);
  74967. }
  74968. /*
  74969. ** Called by the parser to compile a DETACH statement.
  74970. **
  74971. ** DETACH pDbname
  74972. */
  74973. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  74974. static const FuncDef detach_func = {
  74975. 1, /* nArg */
  74976. SQLITE_UTF8, /* iPrefEnc */
  74977. 0, /* flags */
  74978. 0, /* pUserData */
  74979. 0, /* pNext */
  74980. detachFunc, /* xFunc */
  74981. 0, /* xStep */
  74982. 0, /* xFinalize */
  74983. "sqlite_detach", /* zName */
  74984. 0, /* pHash */
  74985. 0 /* pDestructor */
  74986. };
  74987. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  74988. }
  74989. /*
  74990. ** Called by the parser to compile an ATTACH statement.
  74991. **
  74992. ** ATTACH p AS pDbname KEY pKey
  74993. */
  74994. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  74995. static const FuncDef attach_func = {
  74996. 3, /* nArg */
  74997. SQLITE_UTF8, /* iPrefEnc */
  74998. 0, /* flags */
  74999. 0, /* pUserData */
  75000. 0, /* pNext */
  75001. attachFunc, /* xFunc */
  75002. 0, /* xStep */
  75003. 0, /* xFinalize */
  75004. "sqlite_attach", /* zName */
  75005. 0, /* pHash */
  75006. 0 /* pDestructor */
  75007. };
  75008. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  75009. }
  75010. #endif /* SQLITE_OMIT_ATTACH */
  75011. /*
  75012. ** Initialize a DbFixer structure. This routine must be called prior
  75013. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  75014. **
  75015. ** The return value indicates whether or not fixation is required. TRUE
  75016. ** means we do need to fix the database references, FALSE means we do not.
  75017. */
  75018. SQLITE_PRIVATE int sqlite3FixInit(
  75019. DbFixer *pFix, /* The fixer to be initialized */
  75020. Parse *pParse, /* Error messages will be written here */
  75021. int iDb, /* This is the database that must be used */
  75022. const char *zType, /* "view", "trigger", or "index" */
  75023. const Token *pName /* Name of the view, trigger, or index */
  75024. ){
  75025. sqlite3 *db;
  75026. if( NEVER(iDb<0) || iDb==1 ) return 0;
  75027. db = pParse->db;
  75028. assert( db->nDb>iDb );
  75029. pFix->pParse = pParse;
  75030. pFix->zDb = db->aDb[iDb].zName;
  75031. pFix->pSchema = db->aDb[iDb].pSchema;
  75032. pFix->zType = zType;
  75033. pFix->pName = pName;
  75034. return 1;
  75035. }
  75036. /*
  75037. ** The following set of routines walk through the parse tree and assign
  75038. ** a specific database to all table references where the database name
  75039. ** was left unspecified in the original SQL statement. The pFix structure
  75040. ** must have been initialized by a prior call to sqlite3FixInit().
  75041. **
  75042. ** These routines are used to make sure that an index, trigger, or
  75043. ** view in one database does not refer to objects in a different database.
  75044. ** (Exception: indices, triggers, and views in the TEMP database are
  75045. ** allowed to refer to anything.) If a reference is explicitly made
  75046. ** to an object in a different database, an error message is added to
  75047. ** pParse->zErrMsg and these routines return non-zero. If everything
  75048. ** checks out, these routines return 0.
  75049. */
  75050. SQLITE_PRIVATE int sqlite3FixSrcList(
  75051. DbFixer *pFix, /* Context of the fixation */
  75052. SrcList *pList /* The Source list to check and modify */
  75053. ){
  75054. int i;
  75055. const char *zDb;
  75056. struct SrcList_item *pItem;
  75057. if( NEVER(pList==0) ) return 0;
  75058. zDb = pFix->zDb;
  75059. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  75060. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  75061. sqlite3ErrorMsg(pFix->pParse,
  75062. "%s %T cannot reference objects in database %s",
  75063. pFix->zType, pFix->pName, pItem->zDatabase);
  75064. return 1;
  75065. }
  75066. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  75067. pItem->zDatabase = 0;
  75068. pItem->pSchema = pFix->pSchema;
  75069. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  75070. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  75071. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  75072. #endif
  75073. }
  75074. return 0;
  75075. }
  75076. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  75077. SQLITE_PRIVATE int sqlite3FixSelect(
  75078. DbFixer *pFix, /* Context of the fixation */
  75079. Select *pSelect /* The SELECT statement to be fixed to one database */
  75080. ){
  75081. while( pSelect ){
  75082. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  75083. return 1;
  75084. }
  75085. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  75086. return 1;
  75087. }
  75088. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  75089. return 1;
  75090. }
  75091. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  75092. return 1;
  75093. }
  75094. pSelect = pSelect->pPrior;
  75095. }
  75096. return 0;
  75097. }
  75098. SQLITE_PRIVATE int sqlite3FixExpr(
  75099. DbFixer *pFix, /* Context of the fixation */
  75100. Expr *pExpr /* The expression to be fixed to one database */
  75101. ){
  75102. while( pExpr ){
  75103. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
  75104. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75105. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  75106. }else{
  75107. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  75108. }
  75109. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  75110. return 1;
  75111. }
  75112. pExpr = pExpr->pLeft;
  75113. }
  75114. return 0;
  75115. }
  75116. SQLITE_PRIVATE int sqlite3FixExprList(
  75117. DbFixer *pFix, /* Context of the fixation */
  75118. ExprList *pList /* The expression to be fixed to one database */
  75119. ){
  75120. int i;
  75121. struct ExprList_item *pItem;
  75122. if( pList==0 ) return 0;
  75123. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  75124. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  75125. return 1;
  75126. }
  75127. }
  75128. return 0;
  75129. }
  75130. #endif
  75131. #ifndef SQLITE_OMIT_TRIGGER
  75132. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  75133. DbFixer *pFix, /* Context of the fixation */
  75134. TriggerStep *pStep /* The trigger step be fixed to one database */
  75135. ){
  75136. while( pStep ){
  75137. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  75138. return 1;
  75139. }
  75140. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  75141. return 1;
  75142. }
  75143. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  75144. return 1;
  75145. }
  75146. pStep = pStep->pNext;
  75147. }
  75148. return 0;
  75149. }
  75150. #endif
  75151. /************** End of attach.c **********************************************/
  75152. /************** Begin file auth.c ********************************************/
  75153. /*
  75154. ** 2003 January 11
  75155. **
  75156. ** The author disclaims copyright to this source code. In place of
  75157. ** a legal notice, here is a blessing:
  75158. **
  75159. ** May you do good and not evil.
  75160. ** May you find forgiveness for yourself and forgive others.
  75161. ** May you share freely, never taking more than you give.
  75162. **
  75163. *************************************************************************
  75164. ** This file contains code used to implement the sqlite3_set_authorizer()
  75165. ** API. This facility is an optional feature of the library. Embedded
  75166. ** systems that do not need this facility may omit it by recompiling
  75167. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  75168. */
  75169. /*
  75170. ** All of the code in this file may be omitted by defining a single
  75171. ** macro.
  75172. */
  75173. #ifndef SQLITE_OMIT_AUTHORIZATION
  75174. /*
  75175. ** Set or clear the access authorization function.
  75176. **
  75177. ** The access authorization function is be called during the compilation
  75178. ** phase to verify that the user has read and/or write access permission on
  75179. ** various fields of the database. The first argument to the auth function
  75180. ** is a copy of the 3rd argument to this routine. The second argument
  75181. ** to the auth function is one of these constants:
  75182. **
  75183. ** SQLITE_CREATE_INDEX
  75184. ** SQLITE_CREATE_TABLE
  75185. ** SQLITE_CREATE_TEMP_INDEX
  75186. ** SQLITE_CREATE_TEMP_TABLE
  75187. ** SQLITE_CREATE_TEMP_TRIGGER
  75188. ** SQLITE_CREATE_TEMP_VIEW
  75189. ** SQLITE_CREATE_TRIGGER
  75190. ** SQLITE_CREATE_VIEW
  75191. ** SQLITE_DELETE
  75192. ** SQLITE_DROP_INDEX
  75193. ** SQLITE_DROP_TABLE
  75194. ** SQLITE_DROP_TEMP_INDEX
  75195. ** SQLITE_DROP_TEMP_TABLE
  75196. ** SQLITE_DROP_TEMP_TRIGGER
  75197. ** SQLITE_DROP_TEMP_VIEW
  75198. ** SQLITE_DROP_TRIGGER
  75199. ** SQLITE_DROP_VIEW
  75200. ** SQLITE_INSERT
  75201. ** SQLITE_PRAGMA
  75202. ** SQLITE_READ
  75203. ** SQLITE_SELECT
  75204. ** SQLITE_TRANSACTION
  75205. ** SQLITE_UPDATE
  75206. **
  75207. ** The third and fourth arguments to the auth function are the name of
  75208. ** the table and the column that are being accessed. The auth function
  75209. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  75210. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  75211. ** means that the SQL statement will never-run - the sqlite3_exec() call
  75212. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  75213. ** should run but attempts to read the specified column will return NULL
  75214. ** and attempts to write the column will be ignored.
  75215. **
  75216. ** Setting the auth function to NULL disables this hook. The default
  75217. ** setting of the auth function is NULL.
  75218. */
  75219. SQLITE_API int sqlite3_set_authorizer(
  75220. sqlite3 *db,
  75221. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  75222. void *pArg
  75223. ){
  75224. sqlite3_mutex_enter(db->mutex);
  75225. db->xAuth = xAuth;
  75226. db->pAuthArg = pArg;
  75227. sqlite3ExpirePreparedStatements(db);
  75228. sqlite3_mutex_leave(db->mutex);
  75229. return SQLITE_OK;
  75230. }
  75231. /*
  75232. ** Write an error message into pParse->zErrMsg that explains that the
  75233. ** user-supplied authorization function returned an illegal value.
  75234. */
  75235. static void sqliteAuthBadReturnCode(Parse *pParse){
  75236. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  75237. pParse->rc = SQLITE_ERROR;
  75238. }
  75239. /*
  75240. ** Invoke the authorization callback for permission to read column zCol from
  75241. ** table zTab in database zDb. This function assumes that an authorization
  75242. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  75243. **
  75244. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  75245. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  75246. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  75247. */
  75248. SQLITE_PRIVATE int sqlite3AuthReadCol(
  75249. Parse *pParse, /* The parser context */
  75250. const char *zTab, /* Table name */
  75251. const char *zCol, /* Column name */
  75252. int iDb /* Index of containing database. */
  75253. ){
  75254. sqlite3 *db = pParse->db; /* Database handle */
  75255. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  75256. int rc; /* Auth callback return code */
  75257. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  75258. if( rc==SQLITE_DENY ){
  75259. if( db->nDb>2 || iDb!=0 ){
  75260. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  75261. }else{
  75262. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  75263. }
  75264. pParse->rc = SQLITE_AUTH;
  75265. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  75266. sqliteAuthBadReturnCode(pParse);
  75267. }
  75268. return rc;
  75269. }
  75270. /*
  75271. ** The pExpr should be a TK_COLUMN expression. The table referred to
  75272. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  75273. ** Check to see if it is OK to read this particular column.
  75274. **
  75275. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  75276. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  75277. ** then generate an error.
  75278. */
  75279. SQLITE_PRIVATE void sqlite3AuthRead(
  75280. Parse *pParse, /* The parser context */
  75281. Expr *pExpr, /* The expression to check authorization on */
  75282. Schema *pSchema, /* The schema of the expression */
  75283. SrcList *pTabList /* All table that pExpr might refer to */
  75284. ){
  75285. sqlite3 *db = pParse->db;
  75286. Table *pTab = 0; /* The table being read */
  75287. const char *zCol; /* Name of the column of the table */
  75288. int iSrc; /* Index in pTabList->a[] of table being read */
  75289. int iDb; /* The index of the database the expression refers to */
  75290. int iCol; /* Index of column in table */
  75291. if( db->xAuth==0 ) return;
  75292. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  75293. if( iDb<0 ){
  75294. /* An attempt to read a column out of a subquery or other
  75295. ** temporary table. */
  75296. return;
  75297. }
  75298. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  75299. if( pExpr->op==TK_TRIGGER ){
  75300. pTab = pParse->pTriggerTab;
  75301. }else{
  75302. assert( pTabList );
  75303. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  75304. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  75305. pTab = pTabList->a[iSrc].pTab;
  75306. break;
  75307. }
  75308. }
  75309. }
  75310. iCol = pExpr->iColumn;
  75311. if( NEVER(pTab==0) ) return;
  75312. if( iCol>=0 ){
  75313. assert( iCol<pTab->nCol );
  75314. zCol = pTab->aCol[iCol].zName;
  75315. }else if( pTab->iPKey>=0 ){
  75316. assert( pTab->iPKey<pTab->nCol );
  75317. zCol = pTab->aCol[pTab->iPKey].zName;
  75318. }else{
  75319. zCol = "ROWID";
  75320. }
  75321. assert( iDb>=0 && iDb<db->nDb );
  75322. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  75323. pExpr->op = TK_NULL;
  75324. }
  75325. }
  75326. /*
  75327. ** Do an authorization check using the code and arguments given. Return
  75328. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  75329. ** is returned, then the error count and error message in pParse are
  75330. ** modified appropriately.
  75331. */
  75332. SQLITE_PRIVATE int sqlite3AuthCheck(
  75333. Parse *pParse,
  75334. int code,
  75335. const char *zArg1,
  75336. const char *zArg2,
  75337. const char *zArg3
  75338. ){
  75339. sqlite3 *db = pParse->db;
  75340. int rc;
  75341. /* Don't do any authorization checks if the database is initialising
  75342. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  75343. */
  75344. if( db->init.busy || IN_DECLARE_VTAB ){
  75345. return SQLITE_OK;
  75346. }
  75347. if( db->xAuth==0 ){
  75348. return SQLITE_OK;
  75349. }
  75350. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  75351. if( rc==SQLITE_DENY ){
  75352. sqlite3ErrorMsg(pParse, "not authorized");
  75353. pParse->rc = SQLITE_AUTH;
  75354. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  75355. rc = SQLITE_DENY;
  75356. sqliteAuthBadReturnCode(pParse);
  75357. }
  75358. return rc;
  75359. }
  75360. /*
  75361. ** Push an authorization context. After this routine is called, the
  75362. ** zArg3 argument to authorization callbacks will be zContext until
  75363. ** popped. Or if pParse==0, this routine is a no-op.
  75364. */
  75365. SQLITE_PRIVATE void sqlite3AuthContextPush(
  75366. Parse *pParse,
  75367. AuthContext *pContext,
  75368. const char *zContext
  75369. ){
  75370. assert( pParse );
  75371. pContext->pParse = pParse;
  75372. pContext->zAuthContext = pParse->zAuthContext;
  75373. pParse->zAuthContext = zContext;
  75374. }
  75375. /*
  75376. ** Pop an authorization context that was previously pushed
  75377. ** by sqlite3AuthContextPush
  75378. */
  75379. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  75380. if( pContext->pParse ){
  75381. pContext->pParse->zAuthContext = pContext->zAuthContext;
  75382. pContext->pParse = 0;
  75383. }
  75384. }
  75385. #endif /* SQLITE_OMIT_AUTHORIZATION */
  75386. /************** End of auth.c ************************************************/
  75387. /************** Begin file build.c *******************************************/
  75388. /*
  75389. ** 2001 September 15
  75390. **
  75391. ** The author disclaims copyright to this source code. In place of
  75392. ** a legal notice, here is a blessing:
  75393. **
  75394. ** May you do good and not evil.
  75395. ** May you find forgiveness for yourself and forgive others.
  75396. ** May you share freely, never taking more than you give.
  75397. **
  75398. *************************************************************************
  75399. ** This file contains C code routines that are called by the SQLite parser
  75400. ** when syntax rules are reduced. The routines in this file handle the
  75401. ** following kinds of SQL syntax:
  75402. **
  75403. ** CREATE TABLE
  75404. ** DROP TABLE
  75405. ** CREATE INDEX
  75406. ** DROP INDEX
  75407. ** creating ID lists
  75408. ** BEGIN TRANSACTION
  75409. ** COMMIT
  75410. ** ROLLBACK
  75411. */
  75412. /*
  75413. ** This routine is called when a new SQL statement is beginning to
  75414. ** be parsed. Initialize the pParse structure as needed.
  75415. */
  75416. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  75417. pParse->explain = (u8)explainFlag;
  75418. pParse->nVar = 0;
  75419. }
  75420. #ifndef SQLITE_OMIT_SHARED_CACHE
  75421. /*
  75422. ** The TableLock structure is only used by the sqlite3TableLock() and
  75423. ** codeTableLocks() functions.
  75424. */
  75425. struct TableLock {
  75426. int iDb; /* The database containing the table to be locked */
  75427. int iTab; /* The root page of the table to be locked */
  75428. u8 isWriteLock; /* True for write lock. False for a read lock */
  75429. const char *zName; /* Name of the table */
  75430. };
  75431. /*
  75432. ** Record the fact that we want to lock a table at run-time.
  75433. **
  75434. ** The table to be locked has root page iTab and is found in database iDb.
  75435. ** A read or a write lock can be taken depending on isWritelock.
  75436. **
  75437. ** This routine just records the fact that the lock is desired. The
  75438. ** code to make the lock occur is generated by a later call to
  75439. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  75440. */
  75441. SQLITE_PRIVATE void sqlite3TableLock(
  75442. Parse *pParse, /* Parsing context */
  75443. int iDb, /* Index of the database containing the table to lock */
  75444. int iTab, /* Root page number of the table to be locked */
  75445. u8 isWriteLock, /* True for a write lock */
  75446. const char *zName /* Name of the table to be locked */
  75447. ){
  75448. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  75449. int i;
  75450. int nBytes;
  75451. TableLock *p;
  75452. assert( iDb>=0 );
  75453. for(i=0; i<pToplevel->nTableLock; i++){
  75454. p = &pToplevel->aTableLock[i];
  75455. if( p->iDb==iDb && p->iTab==iTab ){
  75456. p->isWriteLock = (p->isWriteLock || isWriteLock);
  75457. return;
  75458. }
  75459. }
  75460. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  75461. pToplevel->aTableLock =
  75462. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  75463. if( pToplevel->aTableLock ){
  75464. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  75465. p->iDb = iDb;
  75466. p->iTab = iTab;
  75467. p->isWriteLock = isWriteLock;
  75468. p->zName = zName;
  75469. }else{
  75470. pToplevel->nTableLock = 0;
  75471. pToplevel->db->mallocFailed = 1;
  75472. }
  75473. }
  75474. /*
  75475. ** Code an OP_TableLock instruction for each table locked by the
  75476. ** statement (configured by calls to sqlite3TableLock()).
  75477. */
  75478. static void codeTableLocks(Parse *pParse){
  75479. int i;
  75480. Vdbe *pVdbe;
  75481. pVdbe = sqlite3GetVdbe(pParse);
  75482. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  75483. for(i=0; i<pParse->nTableLock; i++){
  75484. TableLock *p = &pParse->aTableLock[i];
  75485. int p1 = p->iDb;
  75486. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  75487. p->zName, P4_STATIC);
  75488. }
  75489. }
  75490. #else
  75491. #define codeTableLocks(x)
  75492. #endif
  75493. /*
  75494. ** This routine is called after a single SQL statement has been
  75495. ** parsed and a VDBE program to execute that statement has been
  75496. ** prepared. This routine puts the finishing touches on the
  75497. ** VDBE program and resets the pParse structure for the next
  75498. ** parse.
  75499. **
  75500. ** Note that if an error occurred, it might be the case that
  75501. ** no VDBE code was generated.
  75502. */
  75503. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  75504. sqlite3 *db;
  75505. Vdbe *v;
  75506. assert( pParse->pToplevel==0 );
  75507. db = pParse->db;
  75508. if( db->mallocFailed ) return;
  75509. if( pParse->nested ) return;
  75510. if( pParse->nErr ) return;
  75511. /* Begin by generating some termination code at the end of the
  75512. ** vdbe program
  75513. */
  75514. v = sqlite3GetVdbe(pParse);
  75515. assert( !pParse->isMultiWrite
  75516. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  75517. if( v ){
  75518. sqlite3VdbeAddOp0(v, OP_Halt);
  75519. /* The cookie mask contains one bit for each database file open.
  75520. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  75521. ** set for each database that is used. Generate code to start a
  75522. ** transaction on each used database and to verify the schema cookie
  75523. ** on each used database.
  75524. */
  75525. if( pParse->cookieGoto>0 ){
  75526. yDbMask mask;
  75527. int iDb;
  75528. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  75529. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  75530. if( (mask & pParse->cookieMask)==0 ) continue;
  75531. sqlite3VdbeUsesBtree(v, iDb);
  75532. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  75533. if( db->init.busy==0 ){
  75534. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75535. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  75536. iDb, pParse->cookieValue[iDb],
  75537. db->aDb[iDb].pSchema->iGeneration);
  75538. }
  75539. }
  75540. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75541. {
  75542. int i;
  75543. for(i=0; i<pParse->nVtabLock; i++){
  75544. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  75545. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  75546. }
  75547. pParse->nVtabLock = 0;
  75548. }
  75549. #endif
  75550. /* Once all the cookies have been verified and transactions opened,
  75551. ** obtain the required table-locks. This is a no-op unless the
  75552. ** shared-cache feature is enabled.
  75553. */
  75554. codeTableLocks(pParse);
  75555. /* Initialize any AUTOINCREMENT data structures required.
  75556. */
  75557. sqlite3AutoincrementBegin(pParse);
  75558. /* Finally, jump back to the beginning of the executable code. */
  75559. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  75560. }
  75561. }
  75562. /* Get the VDBE program ready for execution
  75563. */
  75564. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  75565. #ifdef SQLITE_DEBUG
  75566. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  75567. sqlite3VdbeTrace(v, trace);
  75568. #endif
  75569. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  75570. /* A minimum of one cursor is required if autoincrement is used
  75571. * See ticket [a696379c1f08866] */
  75572. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  75573. sqlite3VdbeMakeReady(v, pParse);
  75574. pParse->rc = SQLITE_DONE;
  75575. pParse->colNamesSet = 0;
  75576. }else{
  75577. pParse->rc = SQLITE_ERROR;
  75578. }
  75579. pParse->nTab = 0;
  75580. pParse->nMem = 0;
  75581. pParse->nSet = 0;
  75582. pParse->nVar = 0;
  75583. pParse->cookieMask = 0;
  75584. pParse->cookieGoto = 0;
  75585. }
  75586. /*
  75587. ** Run the parser and code generator recursively in order to generate
  75588. ** code for the SQL statement given onto the end of the pParse context
  75589. ** currently under construction. When the parser is run recursively
  75590. ** this way, the final OP_Halt is not appended and other initialization
  75591. ** and finalization steps are omitted because those are handling by the
  75592. ** outermost parser.
  75593. **
  75594. ** Not everything is nestable. This facility is designed to permit
  75595. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  75596. ** care if you decide to try to use this routine for some other purposes.
  75597. */
  75598. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  75599. va_list ap;
  75600. char *zSql;
  75601. char *zErrMsg = 0;
  75602. sqlite3 *db = pParse->db;
  75603. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  75604. char saveBuf[SAVE_SZ];
  75605. if( pParse->nErr ) return;
  75606. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  75607. va_start(ap, zFormat);
  75608. zSql = sqlite3VMPrintf(db, zFormat, ap);
  75609. va_end(ap);
  75610. if( zSql==0 ){
  75611. return; /* A malloc must have failed */
  75612. }
  75613. pParse->nested++;
  75614. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  75615. memset(&pParse->nVar, 0, SAVE_SZ);
  75616. sqlite3RunParser(pParse, zSql, &zErrMsg);
  75617. sqlite3DbFree(db, zErrMsg);
  75618. sqlite3DbFree(db, zSql);
  75619. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  75620. pParse->nested--;
  75621. }
  75622. /*
  75623. ** Locate the in-memory structure that describes a particular database
  75624. ** table given the name of that table and (optionally) the name of the
  75625. ** database containing the table. Return NULL if not found.
  75626. **
  75627. ** If zDatabase is 0, all databases are searched for the table and the
  75628. ** first matching table is returned. (No checking for duplicate table
  75629. ** names is done.) The search order is TEMP first, then MAIN, then any
  75630. ** auxiliary databases added using the ATTACH command.
  75631. **
  75632. ** See also sqlite3LocateTable().
  75633. */
  75634. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  75635. Table *p = 0;
  75636. int i;
  75637. int nName;
  75638. assert( zName!=0 );
  75639. nName = sqlite3Strlen30(zName);
  75640. /* All mutexes are required for schema access. Make sure we hold them. */
  75641. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  75642. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  75643. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  75644. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  75645. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  75646. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  75647. if( p ) break;
  75648. }
  75649. return p;
  75650. }
  75651. /*
  75652. ** Locate the in-memory structure that describes a particular database
  75653. ** table given the name of that table and (optionally) the name of the
  75654. ** database containing the table. Return NULL if not found. Also leave an
  75655. ** error message in pParse->zErrMsg.
  75656. **
  75657. ** The difference between this routine and sqlite3FindTable() is that this
  75658. ** routine leaves an error message in pParse->zErrMsg where
  75659. ** sqlite3FindTable() does not.
  75660. */
  75661. SQLITE_PRIVATE Table *sqlite3LocateTable(
  75662. Parse *pParse, /* context in which to report errors */
  75663. int isView, /* True if looking for a VIEW rather than a TABLE */
  75664. const char *zName, /* Name of the table we are looking for */
  75665. const char *zDbase /* Name of the database. Might be NULL */
  75666. ){
  75667. Table *p;
  75668. /* Read the database schema. If an error occurs, leave an error message
  75669. ** and code in pParse and return NULL. */
  75670. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  75671. return 0;
  75672. }
  75673. p = sqlite3FindTable(pParse->db, zName, zDbase);
  75674. if( p==0 ){
  75675. const char *zMsg = isView ? "no such view" : "no such table";
  75676. if( zDbase ){
  75677. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  75678. }else{
  75679. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  75680. }
  75681. pParse->checkSchema = 1;
  75682. }
  75683. return p;
  75684. }
  75685. /*
  75686. ** Locate the table identified by *p.
  75687. **
  75688. ** This is a wrapper around sqlite3LocateTable(). The difference between
  75689. ** sqlite3LocateTable() and this function is that this function restricts
  75690. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  75691. ** non-NULL if it is part of a view or trigger program definition. See
  75692. ** sqlite3FixSrcList() for details.
  75693. */
  75694. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  75695. Parse *pParse,
  75696. int isView,
  75697. struct SrcList_item *p
  75698. ){
  75699. const char *zDb;
  75700. assert( p->pSchema==0 || p->zDatabase==0 );
  75701. if( p->pSchema ){
  75702. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  75703. zDb = pParse->db->aDb[iDb].zName;
  75704. }else{
  75705. zDb = p->zDatabase;
  75706. }
  75707. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  75708. }
  75709. /*
  75710. ** Locate the in-memory structure that describes
  75711. ** a particular index given the name of that index
  75712. ** and the name of the database that contains the index.
  75713. ** Return NULL if not found.
  75714. **
  75715. ** If zDatabase is 0, all databases are searched for the
  75716. ** table and the first matching index is returned. (No checking
  75717. ** for duplicate index names is done.) The search order is
  75718. ** TEMP first, then MAIN, then any auxiliary databases added
  75719. ** using the ATTACH command.
  75720. */
  75721. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  75722. Index *p = 0;
  75723. int i;
  75724. int nName = sqlite3Strlen30(zName);
  75725. /* All mutexes are required for schema access. Make sure we hold them. */
  75726. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  75727. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  75728. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  75729. Schema *pSchema = db->aDb[j].pSchema;
  75730. assert( pSchema );
  75731. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  75732. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  75733. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  75734. if( p ) break;
  75735. }
  75736. return p;
  75737. }
  75738. /*
  75739. ** Reclaim the memory used by an index
  75740. */
  75741. static void freeIndex(sqlite3 *db, Index *p){
  75742. #ifndef SQLITE_OMIT_ANALYZE
  75743. sqlite3DeleteIndexSamples(db, p);
  75744. #endif
  75745. sqlite3DbFree(db, p->zColAff);
  75746. sqlite3DbFree(db, p);
  75747. }
  75748. /*
  75749. ** For the index called zIdxName which is found in the database iDb,
  75750. ** unlike that index from its Table then remove the index from
  75751. ** the index hash table and free all memory structures associated
  75752. ** with the index.
  75753. */
  75754. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  75755. Index *pIndex;
  75756. int len;
  75757. Hash *pHash;
  75758. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75759. pHash = &db->aDb[iDb].pSchema->idxHash;
  75760. len = sqlite3Strlen30(zIdxName);
  75761. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  75762. if( ALWAYS(pIndex) ){
  75763. if( pIndex->pTable->pIndex==pIndex ){
  75764. pIndex->pTable->pIndex = pIndex->pNext;
  75765. }else{
  75766. Index *p;
  75767. /* Justification of ALWAYS(); The index must be on the list of
  75768. ** indices. */
  75769. p = pIndex->pTable->pIndex;
  75770. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  75771. if( ALWAYS(p && p->pNext==pIndex) ){
  75772. p->pNext = pIndex->pNext;
  75773. }
  75774. }
  75775. freeIndex(db, pIndex);
  75776. }
  75777. db->flags |= SQLITE_InternChanges;
  75778. }
  75779. /*
  75780. ** Look through the list of open database files in db->aDb[] and if
  75781. ** any have been closed, remove them from the list. Reallocate the
  75782. ** db->aDb[] structure to a smaller size, if possible.
  75783. **
  75784. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  75785. ** are never candidates for being collapsed.
  75786. */
  75787. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  75788. int i, j;
  75789. for(i=j=2; i<db->nDb; i++){
  75790. struct Db *pDb = &db->aDb[i];
  75791. if( pDb->pBt==0 ){
  75792. sqlite3DbFree(db, pDb->zName);
  75793. pDb->zName = 0;
  75794. continue;
  75795. }
  75796. if( j<i ){
  75797. db->aDb[j] = db->aDb[i];
  75798. }
  75799. j++;
  75800. }
  75801. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  75802. db->nDb = j;
  75803. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  75804. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  75805. sqlite3DbFree(db, db->aDb);
  75806. db->aDb = db->aDbStatic;
  75807. }
  75808. }
  75809. /*
  75810. ** Reset the schema for the database at index iDb. Also reset the
  75811. ** TEMP schema.
  75812. */
  75813. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  75814. Db *pDb;
  75815. assert( iDb<db->nDb );
  75816. /* Case 1: Reset the single schema identified by iDb */
  75817. pDb = &db->aDb[iDb];
  75818. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75819. assert( pDb->pSchema!=0 );
  75820. sqlite3SchemaClear(pDb->pSchema);
  75821. /* If any database other than TEMP is reset, then also reset TEMP
  75822. ** since TEMP might be holding triggers that reference tables in the
  75823. ** other database.
  75824. */
  75825. if( iDb!=1 ){
  75826. pDb = &db->aDb[1];
  75827. assert( pDb->pSchema!=0 );
  75828. sqlite3SchemaClear(pDb->pSchema);
  75829. }
  75830. return;
  75831. }
  75832. /*
  75833. ** Erase all schema information from all attached databases (including
  75834. ** "main" and "temp") for a single database connection.
  75835. */
  75836. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  75837. int i;
  75838. sqlite3BtreeEnterAll(db);
  75839. for(i=0; i<db->nDb; i++){
  75840. Db *pDb = &db->aDb[i];
  75841. if( pDb->pSchema ){
  75842. sqlite3SchemaClear(pDb->pSchema);
  75843. }
  75844. }
  75845. db->flags &= ~SQLITE_InternChanges;
  75846. sqlite3VtabUnlockList(db);
  75847. sqlite3BtreeLeaveAll(db);
  75848. sqlite3CollapseDatabaseArray(db);
  75849. }
  75850. /*
  75851. ** This routine is called when a commit occurs.
  75852. */
  75853. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  75854. db->flags &= ~SQLITE_InternChanges;
  75855. }
  75856. /*
  75857. ** Delete memory allocated for the column names of a table or view (the
  75858. ** Table.aCol[] array).
  75859. */
  75860. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  75861. int i;
  75862. Column *pCol;
  75863. assert( pTable!=0 );
  75864. if( (pCol = pTable->aCol)!=0 ){
  75865. for(i=0; i<pTable->nCol; i++, pCol++){
  75866. sqlite3DbFree(db, pCol->zName);
  75867. sqlite3ExprDelete(db, pCol->pDflt);
  75868. sqlite3DbFree(db, pCol->zDflt);
  75869. sqlite3DbFree(db, pCol->zType);
  75870. sqlite3DbFree(db, pCol->zColl);
  75871. }
  75872. sqlite3DbFree(db, pTable->aCol);
  75873. }
  75874. }
  75875. /*
  75876. ** Remove the memory data structures associated with the given
  75877. ** Table. No changes are made to disk by this routine.
  75878. **
  75879. ** This routine just deletes the data structure. It does not unlink
  75880. ** the table data structure from the hash table. But it does destroy
  75881. ** memory structures of the indices and foreign keys associated with
  75882. ** the table.
  75883. **
  75884. ** The db parameter is optional. It is needed if the Table object
  75885. ** contains lookaside memory. (Table objects in the schema do not use
  75886. ** lookaside memory, but some ephemeral Table objects do.) Or the
  75887. ** db parameter can be used with db->pnBytesFreed to measure the memory
  75888. ** used by the Table object.
  75889. */
  75890. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  75891. Index *pIndex, *pNext;
  75892. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  75893. assert( !pTable || pTable->nRef>0 );
  75894. /* Do not delete the table until the reference count reaches zero. */
  75895. if( !pTable ) return;
  75896. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  75897. /* Record the number of outstanding lookaside allocations in schema Tables
  75898. ** prior to doing any free() operations. Since schema Tables do not use
  75899. ** lookaside, this number should not change. */
  75900. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  75901. db->lookaside.nOut : 0 );
  75902. /* Delete all indices associated with this table. */
  75903. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  75904. pNext = pIndex->pNext;
  75905. assert( pIndex->pSchema==pTable->pSchema );
  75906. if( !db || db->pnBytesFreed==0 ){
  75907. char *zName = pIndex->zName;
  75908. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  75909. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  75910. );
  75911. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  75912. assert( pOld==pIndex || pOld==0 );
  75913. }
  75914. freeIndex(db, pIndex);
  75915. }
  75916. /* Delete any foreign keys attached to this table. */
  75917. sqlite3FkDelete(db, pTable);
  75918. /* Delete the Table structure itself.
  75919. */
  75920. sqliteDeleteColumnNames(db, pTable);
  75921. sqlite3DbFree(db, pTable->zName);
  75922. sqlite3DbFree(db, pTable->zColAff);
  75923. sqlite3SelectDelete(db, pTable->pSelect);
  75924. #ifndef SQLITE_OMIT_CHECK
  75925. sqlite3ExprListDelete(db, pTable->pCheck);
  75926. #endif
  75927. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75928. sqlite3VtabClear(db, pTable);
  75929. #endif
  75930. sqlite3DbFree(db, pTable);
  75931. /* Verify that no lookaside memory was used by schema tables */
  75932. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  75933. }
  75934. /*
  75935. ** Unlink the given table from the hash tables and the delete the
  75936. ** table structure with all its indices and foreign keys.
  75937. */
  75938. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  75939. Table *p;
  75940. Db *pDb;
  75941. assert( db!=0 );
  75942. assert( iDb>=0 && iDb<db->nDb );
  75943. assert( zTabName );
  75944. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  75945. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  75946. pDb = &db->aDb[iDb];
  75947. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  75948. sqlite3Strlen30(zTabName),0);
  75949. sqlite3DeleteTable(db, p);
  75950. db->flags |= SQLITE_InternChanges;
  75951. }
  75952. /*
  75953. ** Given a token, return a string that consists of the text of that
  75954. ** token. Space to hold the returned string
  75955. ** is obtained from sqliteMalloc() and must be freed by the calling
  75956. ** function.
  75957. **
  75958. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  75959. ** surround the body of the token are removed.
  75960. **
  75961. ** Tokens are often just pointers into the original SQL text and so
  75962. ** are not \000 terminated and are not persistent. The returned string
  75963. ** is \000 terminated and is persistent.
  75964. */
  75965. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  75966. char *zName;
  75967. if( pName ){
  75968. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  75969. sqlite3Dequote(zName);
  75970. }else{
  75971. zName = 0;
  75972. }
  75973. return zName;
  75974. }
  75975. /*
  75976. ** Open the sqlite_master table stored in database number iDb for
  75977. ** writing. The table is opened using cursor 0.
  75978. */
  75979. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  75980. Vdbe *v = sqlite3GetVdbe(p);
  75981. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  75982. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  75983. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  75984. if( p->nTab==0 ){
  75985. p->nTab = 1;
  75986. }
  75987. }
  75988. /*
  75989. ** Parameter zName points to a nul-terminated buffer containing the name
  75990. ** of a database ("main", "temp" or the name of an attached db). This
  75991. ** function returns the index of the named database in db->aDb[], or
  75992. ** -1 if the named db cannot be found.
  75993. */
  75994. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  75995. int i = -1; /* Database number */
  75996. if( zName ){
  75997. Db *pDb;
  75998. int n = sqlite3Strlen30(zName);
  75999. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  76000. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  76001. 0==sqlite3StrICmp(pDb->zName, zName) ){
  76002. break;
  76003. }
  76004. }
  76005. }
  76006. return i;
  76007. }
  76008. /*
  76009. ** The token *pName contains the name of a database (either "main" or
  76010. ** "temp" or the name of an attached db). This routine returns the
  76011. ** index of the named database in db->aDb[], or -1 if the named db
  76012. ** does not exist.
  76013. */
  76014. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  76015. int i; /* Database number */
  76016. char *zName; /* Name we are searching for */
  76017. zName = sqlite3NameFromToken(db, pName);
  76018. i = sqlite3FindDbName(db, zName);
  76019. sqlite3DbFree(db, zName);
  76020. return i;
  76021. }
  76022. /* The table or view or trigger name is passed to this routine via tokens
  76023. ** pName1 and pName2. If the table name was fully qualified, for example:
  76024. **
  76025. ** CREATE TABLE xxx.yyy (...);
  76026. **
  76027. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  76028. ** the table name is not fully qualified, i.e.:
  76029. **
  76030. ** CREATE TABLE yyy(...);
  76031. **
  76032. ** Then pName1 is set to "yyy" and pName2 is "".
  76033. **
  76034. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  76035. ** pName2) that stores the unqualified table name. The index of the
  76036. ** database "xxx" is returned.
  76037. */
  76038. SQLITE_PRIVATE int sqlite3TwoPartName(
  76039. Parse *pParse, /* Parsing and code generating context */
  76040. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  76041. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  76042. Token **pUnqual /* Write the unqualified object name here */
  76043. ){
  76044. int iDb; /* Database holding the object */
  76045. sqlite3 *db = pParse->db;
  76046. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  76047. if( db->init.busy ) {
  76048. sqlite3ErrorMsg(pParse, "corrupt database");
  76049. pParse->nErr++;
  76050. return -1;
  76051. }
  76052. *pUnqual = pName2;
  76053. iDb = sqlite3FindDb(db, pName1);
  76054. if( iDb<0 ){
  76055. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  76056. pParse->nErr++;
  76057. return -1;
  76058. }
  76059. }else{
  76060. assert( db->init.iDb==0 || db->init.busy );
  76061. iDb = db->init.iDb;
  76062. *pUnqual = pName1;
  76063. }
  76064. return iDb;
  76065. }
  76066. /*
  76067. ** This routine is used to check if the UTF-8 string zName is a legal
  76068. ** unqualified name for a new schema object (table, index, view or
  76069. ** trigger). All names are legal except those that begin with the string
  76070. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  76071. ** is reserved for internal use.
  76072. */
  76073. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  76074. if( !pParse->db->init.busy && pParse->nested==0
  76075. && (pParse->db->flags & SQLITE_WriteSchema)==0
  76076. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  76077. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  76078. return SQLITE_ERROR;
  76079. }
  76080. return SQLITE_OK;
  76081. }
  76082. /*
  76083. ** Begin constructing a new table representation in memory. This is
  76084. ** the first of several action routines that get called in response
  76085. ** to a CREATE TABLE statement. In particular, this routine is called
  76086. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  76087. ** flag is true if the table should be stored in the auxiliary database
  76088. ** file instead of in the main database file. This is normally the case
  76089. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  76090. ** CREATE and TABLE.
  76091. **
  76092. ** The new table record is initialized and put in pParse->pNewTable.
  76093. ** As more of the CREATE TABLE statement is parsed, additional action
  76094. ** routines will be called to add more information to this record.
  76095. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  76096. ** is called to complete the construction of the new table record.
  76097. */
  76098. SQLITE_PRIVATE void sqlite3StartTable(
  76099. Parse *pParse, /* Parser context */
  76100. Token *pName1, /* First part of the name of the table or view */
  76101. Token *pName2, /* Second part of the name of the table or view */
  76102. int isTemp, /* True if this is a TEMP table */
  76103. int isView, /* True if this is a VIEW */
  76104. int isVirtual, /* True if this is a VIRTUAL table */
  76105. int noErr /* Do nothing if table already exists */
  76106. ){
  76107. Table *pTable;
  76108. char *zName = 0; /* The name of the new table */
  76109. sqlite3 *db = pParse->db;
  76110. Vdbe *v;
  76111. int iDb; /* Database number to create the table in */
  76112. Token *pName; /* Unqualified name of the table to create */
  76113. /* The table or view name to create is passed to this routine via tokens
  76114. ** pName1 and pName2. If the table name was fully qualified, for example:
  76115. **
  76116. ** CREATE TABLE xxx.yyy (...);
  76117. **
  76118. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  76119. ** the table name is not fully qualified, i.e.:
  76120. **
  76121. ** CREATE TABLE yyy(...);
  76122. **
  76123. ** Then pName1 is set to "yyy" and pName2 is "".
  76124. **
  76125. ** The call below sets the pName pointer to point at the token (pName1 or
  76126. ** pName2) that stores the unqualified table name. The variable iDb is
  76127. ** set to the index of the database that the table or view is to be
  76128. ** created in.
  76129. */
  76130. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  76131. if( iDb<0 ) return;
  76132. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  76133. /* If creating a temp table, the name may not be qualified. Unless
  76134. ** the database name is "temp" anyway. */
  76135. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  76136. return;
  76137. }
  76138. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  76139. pParse->sNameToken = *pName;
  76140. zName = sqlite3NameFromToken(db, pName);
  76141. if( zName==0 ) return;
  76142. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  76143. goto begin_table_error;
  76144. }
  76145. if( db->init.iDb==1 ) isTemp = 1;
  76146. #ifndef SQLITE_OMIT_AUTHORIZATION
  76147. assert( (isTemp & 1)==isTemp );
  76148. {
  76149. int code;
  76150. char *zDb = db->aDb[iDb].zName;
  76151. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  76152. goto begin_table_error;
  76153. }
  76154. if( isView ){
  76155. if( !OMIT_TEMPDB && isTemp ){
  76156. code = SQLITE_CREATE_TEMP_VIEW;
  76157. }else{
  76158. code = SQLITE_CREATE_VIEW;
  76159. }
  76160. }else{
  76161. if( !OMIT_TEMPDB && isTemp ){
  76162. code = SQLITE_CREATE_TEMP_TABLE;
  76163. }else{
  76164. code = SQLITE_CREATE_TABLE;
  76165. }
  76166. }
  76167. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  76168. goto begin_table_error;
  76169. }
  76170. }
  76171. #endif
  76172. /* Make sure the new table name does not collide with an existing
  76173. ** index or table name in the same database. Issue an error message if
  76174. ** it does. The exception is if the statement being parsed was passed
  76175. ** to an sqlite3_declare_vtab() call. In that case only the column names
  76176. ** and types will be used, so there is no need to test for namespace
  76177. ** collisions.
  76178. */
  76179. if( !IN_DECLARE_VTAB ){
  76180. char *zDb = db->aDb[iDb].zName;
  76181. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  76182. goto begin_table_error;
  76183. }
  76184. pTable = sqlite3FindTable(db, zName, zDb);
  76185. if( pTable ){
  76186. if( !noErr ){
  76187. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  76188. }else{
  76189. assert( !db->init.busy );
  76190. sqlite3CodeVerifySchema(pParse, iDb);
  76191. }
  76192. goto begin_table_error;
  76193. }
  76194. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  76195. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  76196. goto begin_table_error;
  76197. }
  76198. }
  76199. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  76200. if( pTable==0 ){
  76201. db->mallocFailed = 1;
  76202. pParse->rc = SQLITE_NOMEM;
  76203. pParse->nErr++;
  76204. goto begin_table_error;
  76205. }
  76206. pTable->zName = zName;
  76207. pTable->iPKey = -1;
  76208. pTable->pSchema = db->aDb[iDb].pSchema;
  76209. pTable->nRef = 1;
  76210. pTable->nRowEst = 1000000;
  76211. assert( pParse->pNewTable==0 );
  76212. pParse->pNewTable = pTable;
  76213. /* If this is the magic sqlite_sequence table used by autoincrement,
  76214. ** then record a pointer to this table in the main database structure
  76215. ** so that INSERT can find the table easily.
  76216. */
  76217. #ifndef SQLITE_OMIT_AUTOINCREMENT
  76218. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  76219. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76220. pTable->pSchema->pSeqTab = pTable;
  76221. }
  76222. #endif
  76223. /* Begin generating the code that will insert the table record into
  76224. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  76225. ** and allocate the record number for the table entry now. Before any
  76226. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  76227. ** indices to be created and the table record must come before the
  76228. ** indices. Hence, the record number for the table must be allocated
  76229. ** now.
  76230. */
  76231. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  76232. int j1;
  76233. int fileFormat;
  76234. int reg1, reg2, reg3;
  76235. sqlite3BeginWriteOperation(pParse, 0, iDb);
  76236. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76237. if( isVirtual ){
  76238. sqlite3VdbeAddOp0(v, OP_VBegin);
  76239. }
  76240. #endif
  76241. /* If the file format and encoding in the database have not been set,
  76242. ** set them now.
  76243. */
  76244. reg1 = pParse->regRowid = ++pParse->nMem;
  76245. reg2 = pParse->regRoot = ++pParse->nMem;
  76246. reg3 = ++pParse->nMem;
  76247. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  76248. sqlite3VdbeUsesBtree(v, iDb);
  76249. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  76250. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  76251. 1 : SQLITE_MAX_FILE_FORMAT;
  76252. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  76253. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  76254. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  76255. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  76256. sqlite3VdbeJumpHere(v, j1);
  76257. /* This just creates a place-holder record in the sqlite_master table.
  76258. ** The record created does not contain anything yet. It will be replaced
  76259. ** by the real entry in code generated at sqlite3EndTable().
  76260. **
  76261. ** The rowid for the new entry is left in register pParse->regRowid.
  76262. ** The root page number of the new table is left in reg pParse->regRoot.
  76263. ** The rowid and root page number values are needed by the code that
  76264. ** sqlite3EndTable will generate.
  76265. */
  76266. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  76267. if( isView || isVirtual ){
  76268. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  76269. }else
  76270. #endif
  76271. {
  76272. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  76273. }
  76274. sqlite3OpenMasterTable(pParse, iDb);
  76275. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  76276. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  76277. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  76278. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  76279. sqlite3VdbeAddOp0(v, OP_Close);
  76280. }
  76281. /* Normal (non-error) return. */
  76282. return;
  76283. /* If an error occurs, we jump here */
  76284. begin_table_error:
  76285. sqlite3DbFree(db, zName);
  76286. return;
  76287. }
  76288. /*
  76289. ** This macro is used to compare two strings in a case-insensitive manner.
  76290. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  76291. ** produces larger code.
  76292. **
  76293. ** WARNING: This macro is not compatible with the strcmp() family. It
  76294. ** returns true if the two strings are equal, otherwise false.
  76295. */
  76296. #define STRICMP(x, y) (\
  76297. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  76298. sqlite3UpperToLower[*(unsigned char *)(y)] \
  76299. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  76300. /*
  76301. ** Add a new column to the table currently being constructed.
  76302. **
  76303. ** The parser calls this routine once for each column declaration
  76304. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  76305. ** first to get things going. Then this routine is called for each
  76306. ** column.
  76307. */
  76308. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  76309. Table *p;
  76310. int i;
  76311. char *z;
  76312. Column *pCol;
  76313. sqlite3 *db = pParse->db;
  76314. if( (p = pParse->pNewTable)==0 ) return;
  76315. #if SQLITE_MAX_COLUMN
  76316. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  76317. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  76318. return;
  76319. }
  76320. #endif
  76321. z = sqlite3NameFromToken(db, pName);
  76322. if( z==0 ) return;
  76323. for(i=0; i<p->nCol; i++){
  76324. if( STRICMP(z, p->aCol[i].zName) ){
  76325. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  76326. sqlite3DbFree(db, z);
  76327. return;
  76328. }
  76329. }
  76330. if( (p->nCol & 0x7)==0 ){
  76331. Column *aNew;
  76332. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  76333. if( aNew==0 ){
  76334. sqlite3DbFree(db, z);
  76335. return;
  76336. }
  76337. p->aCol = aNew;
  76338. }
  76339. pCol = &p->aCol[p->nCol];
  76340. memset(pCol, 0, sizeof(p->aCol[0]));
  76341. pCol->zName = z;
  76342. /* If there is no type specified, columns have the default affinity
  76343. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  76344. ** be called next to set pCol->affinity correctly.
  76345. */
  76346. pCol->affinity = SQLITE_AFF_NONE;
  76347. p->nCol++;
  76348. }
  76349. /*
  76350. ** This routine is called by the parser while in the middle of
  76351. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  76352. ** been seen on a column. This routine sets the notNull flag on
  76353. ** the column currently under construction.
  76354. */
  76355. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  76356. Table *p;
  76357. p = pParse->pNewTable;
  76358. if( p==0 || NEVER(p->nCol<1) ) return;
  76359. p->aCol[p->nCol-1].notNull = (u8)onError;
  76360. }
  76361. /*
  76362. ** Scan the column type name zType (length nType) and return the
  76363. ** associated affinity type.
  76364. **
  76365. ** This routine does a case-independent search of zType for the
  76366. ** substrings in the following table. If one of the substrings is
  76367. ** found, the corresponding affinity is returned. If zType contains
  76368. ** more than one of the substrings, entries toward the top of
  76369. ** the table take priority. For example, if zType is 'BLOBINT',
  76370. ** SQLITE_AFF_INTEGER is returned.
  76371. **
  76372. ** Substring | Affinity
  76373. ** --------------------------------
  76374. ** 'INT' | SQLITE_AFF_INTEGER
  76375. ** 'CHAR' | SQLITE_AFF_TEXT
  76376. ** 'CLOB' | SQLITE_AFF_TEXT
  76377. ** 'TEXT' | SQLITE_AFF_TEXT
  76378. ** 'BLOB' | SQLITE_AFF_NONE
  76379. ** 'REAL' | SQLITE_AFF_REAL
  76380. ** 'FLOA' | SQLITE_AFF_REAL
  76381. ** 'DOUB' | SQLITE_AFF_REAL
  76382. **
  76383. ** If none of the substrings in the above table are found,
  76384. ** SQLITE_AFF_NUMERIC is returned.
  76385. */
  76386. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
  76387. u32 h = 0;
  76388. char aff = SQLITE_AFF_NUMERIC;
  76389. if( zIn ) while( zIn[0] ){
  76390. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  76391. zIn++;
  76392. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  76393. aff = SQLITE_AFF_TEXT;
  76394. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  76395. aff = SQLITE_AFF_TEXT;
  76396. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  76397. aff = SQLITE_AFF_TEXT;
  76398. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  76399. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  76400. aff = SQLITE_AFF_NONE;
  76401. #ifndef SQLITE_OMIT_FLOATING_POINT
  76402. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  76403. && aff==SQLITE_AFF_NUMERIC ){
  76404. aff = SQLITE_AFF_REAL;
  76405. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  76406. && aff==SQLITE_AFF_NUMERIC ){
  76407. aff = SQLITE_AFF_REAL;
  76408. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  76409. && aff==SQLITE_AFF_NUMERIC ){
  76410. aff = SQLITE_AFF_REAL;
  76411. #endif
  76412. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  76413. aff = SQLITE_AFF_INTEGER;
  76414. break;
  76415. }
  76416. }
  76417. return aff;
  76418. }
  76419. /*
  76420. ** This routine is called by the parser while in the middle of
  76421. ** parsing a CREATE TABLE statement. The pFirst token is the first
  76422. ** token in the sequence of tokens that describe the type of the
  76423. ** column currently under construction. pLast is the last token
  76424. ** in the sequence. Use this information to construct a string
  76425. ** that contains the typename of the column and store that string
  76426. ** in zType.
  76427. */
  76428. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  76429. Table *p;
  76430. Column *pCol;
  76431. p = pParse->pNewTable;
  76432. if( p==0 || NEVER(p->nCol<1) ) return;
  76433. pCol = &p->aCol[p->nCol-1];
  76434. assert( pCol->zType==0 );
  76435. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  76436. pCol->affinity = sqlite3AffinityType(pCol->zType);
  76437. }
  76438. /*
  76439. ** The expression is the default value for the most recently added column
  76440. ** of the table currently under construction.
  76441. **
  76442. ** Default value expressions must be constant. Raise an exception if this
  76443. ** is not the case.
  76444. **
  76445. ** This routine is called by the parser while in the middle of
  76446. ** parsing a CREATE TABLE statement.
  76447. */
  76448. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  76449. Table *p;
  76450. Column *pCol;
  76451. sqlite3 *db = pParse->db;
  76452. p = pParse->pNewTable;
  76453. if( p!=0 ){
  76454. pCol = &(p->aCol[p->nCol-1]);
  76455. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  76456. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  76457. pCol->zName);
  76458. }else{
  76459. /* A copy of pExpr is used instead of the original, as pExpr contains
  76460. ** tokens that point to volatile memory. The 'span' of the expression
  76461. ** is required by pragma table_info.
  76462. */
  76463. sqlite3ExprDelete(db, pCol->pDflt);
  76464. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  76465. sqlite3DbFree(db, pCol->zDflt);
  76466. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  76467. (int)(pSpan->zEnd - pSpan->zStart));
  76468. }
  76469. }
  76470. sqlite3ExprDelete(db, pSpan->pExpr);
  76471. }
  76472. /*
  76473. ** Designate the PRIMARY KEY for the table. pList is a list of names
  76474. ** of columns that form the primary key. If pList is NULL, then the
  76475. ** most recently added column of the table is the primary key.
  76476. **
  76477. ** A table can have at most one primary key. If the table already has
  76478. ** a primary key (and this is the second primary key) then create an
  76479. ** error.
  76480. **
  76481. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  76482. ** then we will try to use that column as the rowid. Set the Table.iPKey
  76483. ** field of the table under construction to be the index of the
  76484. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  76485. ** no INTEGER PRIMARY KEY.
  76486. **
  76487. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  76488. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  76489. */
  76490. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  76491. Parse *pParse, /* Parsing context */
  76492. ExprList *pList, /* List of field names to be indexed */
  76493. int onError, /* What to do with a uniqueness conflict */
  76494. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  76495. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  76496. ){
  76497. Table *pTab = pParse->pNewTable;
  76498. char *zType = 0;
  76499. int iCol = -1, i;
  76500. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  76501. if( pTab->tabFlags & TF_HasPrimaryKey ){
  76502. sqlite3ErrorMsg(pParse,
  76503. "table \"%s\" has more than one primary key", pTab->zName);
  76504. goto primary_key_exit;
  76505. }
  76506. pTab->tabFlags |= TF_HasPrimaryKey;
  76507. if( pList==0 ){
  76508. iCol = pTab->nCol - 1;
  76509. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  76510. }else{
  76511. for(i=0; i<pList->nExpr; i++){
  76512. for(iCol=0; iCol<pTab->nCol; iCol++){
  76513. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  76514. break;
  76515. }
  76516. }
  76517. if( iCol<pTab->nCol ){
  76518. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  76519. }
  76520. }
  76521. if( pList->nExpr>1 ) iCol = -1;
  76522. }
  76523. if( iCol>=0 && iCol<pTab->nCol ){
  76524. zType = pTab->aCol[iCol].zType;
  76525. }
  76526. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  76527. && sortOrder==SQLITE_SO_ASC ){
  76528. pTab->iPKey = iCol;
  76529. pTab->keyConf = (u8)onError;
  76530. assert( autoInc==0 || autoInc==1 );
  76531. pTab->tabFlags |= autoInc*TF_Autoincrement;
  76532. }else if( autoInc ){
  76533. #ifndef SQLITE_OMIT_AUTOINCREMENT
  76534. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  76535. "INTEGER PRIMARY KEY");
  76536. #endif
  76537. }else{
  76538. Index *p;
  76539. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  76540. if( p ){
  76541. p->autoIndex = 2;
  76542. }
  76543. pList = 0;
  76544. }
  76545. primary_key_exit:
  76546. sqlite3ExprListDelete(pParse->db, pList);
  76547. return;
  76548. }
  76549. /*
  76550. ** Add a new CHECK constraint to the table currently under construction.
  76551. */
  76552. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  76553. Parse *pParse, /* Parsing context */
  76554. Expr *pCheckExpr /* The check expression */
  76555. ){
  76556. #ifndef SQLITE_OMIT_CHECK
  76557. Table *pTab = pParse->pNewTable;
  76558. if( pTab && !IN_DECLARE_VTAB ){
  76559. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  76560. if( pParse->constraintName.n ){
  76561. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  76562. }
  76563. }else
  76564. #endif
  76565. {
  76566. sqlite3ExprDelete(pParse->db, pCheckExpr);
  76567. }
  76568. }
  76569. /*
  76570. ** Set the collation function of the most recently parsed table column
  76571. ** to the CollSeq given.
  76572. */
  76573. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  76574. Table *p;
  76575. int i;
  76576. char *zColl; /* Dequoted name of collation sequence */
  76577. sqlite3 *db;
  76578. if( (p = pParse->pNewTable)==0 ) return;
  76579. i = p->nCol-1;
  76580. db = pParse->db;
  76581. zColl = sqlite3NameFromToken(db, pToken);
  76582. if( !zColl ) return;
  76583. if( sqlite3LocateCollSeq(pParse, zColl) ){
  76584. Index *pIdx;
  76585. p->aCol[i].zColl = zColl;
  76586. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  76587. ** then an index may have been created on this column before the
  76588. ** collation type was added. Correct this if it is the case.
  76589. */
  76590. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  76591. assert( pIdx->nColumn==1 );
  76592. if( pIdx->aiColumn[0]==i ){
  76593. pIdx->azColl[0] = p->aCol[i].zColl;
  76594. }
  76595. }
  76596. }else{
  76597. sqlite3DbFree(db, zColl);
  76598. }
  76599. }
  76600. /*
  76601. ** This function returns the collation sequence for database native text
  76602. ** encoding identified by the string zName, length nName.
  76603. **
  76604. ** If the requested collation sequence is not available, or not available
  76605. ** in the database native encoding, the collation factory is invoked to
  76606. ** request it. If the collation factory does not supply such a sequence,
  76607. ** and the sequence is available in another text encoding, then that is
  76608. ** returned instead.
  76609. **
  76610. ** If no versions of the requested collations sequence are available, or
  76611. ** another error occurs, NULL is returned and an error message written into
  76612. ** pParse.
  76613. **
  76614. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  76615. ** invokes the collation factory if the named collation cannot be found
  76616. ** and generates an error message.
  76617. **
  76618. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  76619. */
  76620. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  76621. sqlite3 *db = pParse->db;
  76622. u8 enc = ENC(db);
  76623. u8 initbusy = db->init.busy;
  76624. CollSeq *pColl;
  76625. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  76626. if( !initbusy && (!pColl || !pColl->xCmp) ){
  76627. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  76628. }
  76629. return pColl;
  76630. }
  76631. /*
  76632. ** Generate code that will increment the schema cookie.
  76633. **
  76634. ** The schema cookie is used to determine when the schema for the
  76635. ** database changes. After each schema change, the cookie value
  76636. ** changes. When a process first reads the schema it records the
  76637. ** cookie. Thereafter, whenever it goes to access the database,
  76638. ** it checks the cookie to make sure the schema has not changed
  76639. ** since it was last read.
  76640. **
  76641. ** This plan is not completely bullet-proof. It is possible for
  76642. ** the schema to change multiple times and for the cookie to be
  76643. ** set back to prior value. But schema changes are infrequent
  76644. ** and the probability of hitting the same cookie value is only
  76645. ** 1 chance in 2^32. So we're safe enough.
  76646. */
  76647. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  76648. int r1 = sqlite3GetTempReg(pParse);
  76649. sqlite3 *db = pParse->db;
  76650. Vdbe *v = pParse->pVdbe;
  76651. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76652. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  76653. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  76654. sqlite3ReleaseTempReg(pParse, r1);
  76655. }
  76656. /*
  76657. ** Measure the number of characters needed to output the given
  76658. ** identifier. The number returned includes any quotes used
  76659. ** but does not include the null terminator.
  76660. **
  76661. ** The estimate is conservative. It might be larger that what is
  76662. ** really needed.
  76663. */
  76664. static int identLength(const char *z){
  76665. int n;
  76666. for(n=0; *z; n++, z++){
  76667. if( *z=='"' ){ n++; }
  76668. }
  76669. return n + 2;
  76670. }
  76671. /*
  76672. ** The first parameter is a pointer to an output buffer. The second
  76673. ** parameter is a pointer to an integer that contains the offset at
  76674. ** which to write into the output buffer. This function copies the
  76675. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  76676. ** to the specified offset in the buffer and updates *pIdx to refer
  76677. ** to the first byte after the last byte written before returning.
  76678. **
  76679. ** If the string zSignedIdent consists entirely of alpha-numeric
  76680. ** characters, does not begin with a digit and is not an SQL keyword,
  76681. ** then it is copied to the output buffer exactly as it is. Otherwise,
  76682. ** it is quoted using double-quotes.
  76683. */
  76684. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  76685. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  76686. int i, j, needQuote;
  76687. i = *pIdx;
  76688. for(j=0; zIdent[j]; j++){
  76689. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  76690. }
  76691. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  76692. if( !needQuote ){
  76693. needQuote = zIdent[j];
  76694. }
  76695. if( needQuote ) z[i++] = '"';
  76696. for(j=0; zIdent[j]; j++){
  76697. z[i++] = zIdent[j];
  76698. if( zIdent[j]=='"' ) z[i++] = '"';
  76699. }
  76700. if( needQuote ) z[i++] = '"';
  76701. z[i] = 0;
  76702. *pIdx = i;
  76703. }
  76704. /*
  76705. ** Generate a CREATE TABLE statement appropriate for the given
  76706. ** table. Memory to hold the text of the statement is obtained
  76707. ** from sqliteMalloc() and must be freed by the calling function.
  76708. */
  76709. static char *createTableStmt(sqlite3 *db, Table *p){
  76710. int i, k, n;
  76711. char *zStmt;
  76712. char *zSep, *zSep2, *zEnd;
  76713. Column *pCol;
  76714. n = 0;
  76715. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  76716. n += identLength(pCol->zName) + 5;
  76717. }
  76718. n += identLength(p->zName);
  76719. if( n<50 ){
  76720. zSep = "";
  76721. zSep2 = ",";
  76722. zEnd = ")";
  76723. }else{
  76724. zSep = "\n ";
  76725. zSep2 = ",\n ";
  76726. zEnd = "\n)";
  76727. }
  76728. n += 35 + 6*p->nCol;
  76729. zStmt = sqlite3DbMallocRaw(0, n);
  76730. if( zStmt==0 ){
  76731. db->mallocFailed = 1;
  76732. return 0;
  76733. }
  76734. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  76735. k = sqlite3Strlen30(zStmt);
  76736. identPut(zStmt, &k, p->zName);
  76737. zStmt[k++] = '(';
  76738. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  76739. static const char * const azType[] = {
  76740. /* SQLITE_AFF_TEXT */ " TEXT",
  76741. /* SQLITE_AFF_NONE */ "",
  76742. /* SQLITE_AFF_NUMERIC */ " NUM",
  76743. /* SQLITE_AFF_INTEGER */ " INT",
  76744. /* SQLITE_AFF_REAL */ " REAL"
  76745. };
  76746. int len;
  76747. const char *zType;
  76748. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  76749. k += sqlite3Strlen30(&zStmt[k]);
  76750. zSep = zSep2;
  76751. identPut(zStmt, &k, pCol->zName);
  76752. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  76753. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  76754. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  76755. testcase( pCol->affinity==SQLITE_AFF_NONE );
  76756. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  76757. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  76758. testcase( pCol->affinity==SQLITE_AFF_REAL );
  76759. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  76760. len = sqlite3Strlen30(zType);
  76761. assert( pCol->affinity==SQLITE_AFF_NONE
  76762. || pCol->affinity==sqlite3AffinityType(zType) );
  76763. memcpy(&zStmt[k], zType, len);
  76764. k += len;
  76765. assert( k<=n );
  76766. }
  76767. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  76768. return zStmt;
  76769. }
  76770. /*
  76771. ** This routine is called to report the final ")" that terminates
  76772. ** a CREATE TABLE statement.
  76773. **
  76774. ** The table structure that other action routines have been building
  76775. ** is added to the internal hash tables, assuming no errors have
  76776. ** occurred.
  76777. **
  76778. ** An entry for the table is made in the master table on disk, unless
  76779. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  76780. ** it means we are reading the sqlite_master table because we just
  76781. ** connected to the database or because the sqlite_master table has
  76782. ** recently changed, so the entry for this table already exists in
  76783. ** the sqlite_master table. We do not want to create it again.
  76784. **
  76785. ** If the pSelect argument is not NULL, it means that this routine
  76786. ** was called to create a table generated from a
  76787. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  76788. ** the new table will match the result set of the SELECT.
  76789. */
  76790. SQLITE_PRIVATE void sqlite3EndTable(
  76791. Parse *pParse, /* Parse context */
  76792. Token *pCons, /* The ',' token after the last column defn. */
  76793. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  76794. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  76795. ){
  76796. Table *p;
  76797. sqlite3 *db = pParse->db;
  76798. int iDb;
  76799. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  76800. return;
  76801. }
  76802. p = pParse->pNewTable;
  76803. if( p==0 ) return;
  76804. assert( !db->init.busy || !pSelect );
  76805. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  76806. #ifndef SQLITE_OMIT_CHECK
  76807. /* Resolve names in all CHECK constraint expressions.
  76808. */
  76809. if( p->pCheck ){
  76810. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  76811. NameContext sNC; /* Name context for pParse->pNewTable */
  76812. ExprList *pList; /* List of all CHECK constraints */
  76813. int i; /* Loop counter */
  76814. memset(&sNC, 0, sizeof(sNC));
  76815. memset(&sSrc, 0, sizeof(sSrc));
  76816. sSrc.nSrc = 1;
  76817. sSrc.a[0].zName = p->zName;
  76818. sSrc.a[0].pTab = p;
  76819. sSrc.a[0].iCursor = -1;
  76820. sNC.pParse = pParse;
  76821. sNC.pSrcList = &sSrc;
  76822. sNC.ncFlags = NC_IsCheck;
  76823. pList = p->pCheck;
  76824. for(i=0; i<pList->nExpr; i++){
  76825. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  76826. return;
  76827. }
  76828. }
  76829. }
  76830. #endif /* !defined(SQLITE_OMIT_CHECK) */
  76831. /* If the db->init.busy is 1 it means we are reading the SQL off the
  76832. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  76833. ** So do not write to the disk again. Extract the root page number
  76834. ** for the table from the db->init.newTnum field. (The page number
  76835. ** should have been put there by the sqliteOpenCb routine.)
  76836. */
  76837. if( db->init.busy ){
  76838. p->tnum = db->init.newTnum;
  76839. }
  76840. /* If not initializing, then create a record for the new table
  76841. ** in the SQLITE_MASTER table of the database.
  76842. **
  76843. ** If this is a TEMPORARY table, write the entry into the auxiliary
  76844. ** file instead of into the main database file.
  76845. */
  76846. if( !db->init.busy ){
  76847. int n;
  76848. Vdbe *v;
  76849. char *zType; /* "view" or "table" */
  76850. char *zType2; /* "VIEW" or "TABLE" */
  76851. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  76852. v = sqlite3GetVdbe(pParse);
  76853. if( NEVER(v==0) ) return;
  76854. sqlite3VdbeAddOp1(v, OP_Close, 0);
  76855. /*
  76856. ** Initialize zType for the new view or table.
  76857. */
  76858. if( p->pSelect==0 ){
  76859. /* A regular table */
  76860. zType = "table";
  76861. zType2 = "TABLE";
  76862. #ifndef SQLITE_OMIT_VIEW
  76863. }else{
  76864. /* A view */
  76865. zType = "view";
  76866. zType2 = "VIEW";
  76867. #endif
  76868. }
  76869. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  76870. ** statement to populate the new table. The root-page number for the
  76871. ** new table is in register pParse->regRoot.
  76872. **
  76873. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  76874. ** suitable state to query for the column names and types to be used
  76875. ** by the new table.
  76876. **
  76877. ** A shared-cache write-lock is not required to write to the new table,
  76878. ** as a schema-lock must have already been obtained to create it. Since
  76879. ** a schema-lock excludes all other database users, the write-lock would
  76880. ** be redundant.
  76881. */
  76882. if( pSelect ){
  76883. SelectDest dest;
  76884. Table *pSelTab;
  76885. assert(pParse->nTab==1);
  76886. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  76887. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  76888. pParse->nTab = 2;
  76889. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  76890. sqlite3Select(pParse, pSelect, &dest);
  76891. sqlite3VdbeAddOp1(v, OP_Close, 1);
  76892. if( pParse->nErr==0 ){
  76893. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  76894. if( pSelTab==0 ) return;
  76895. assert( p->aCol==0 );
  76896. p->nCol = pSelTab->nCol;
  76897. p->aCol = pSelTab->aCol;
  76898. pSelTab->nCol = 0;
  76899. pSelTab->aCol = 0;
  76900. sqlite3DeleteTable(db, pSelTab);
  76901. }
  76902. }
  76903. /* Compute the complete text of the CREATE statement */
  76904. if( pSelect ){
  76905. zStmt = createTableStmt(db, p);
  76906. }else{
  76907. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  76908. zStmt = sqlite3MPrintf(db,
  76909. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  76910. );
  76911. }
  76912. /* A slot for the record has already been allocated in the
  76913. ** SQLITE_MASTER table. We just need to update that slot with all
  76914. ** the information we've collected.
  76915. */
  76916. sqlite3NestedParse(pParse,
  76917. "UPDATE %Q.%s "
  76918. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  76919. "WHERE rowid=#%d",
  76920. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  76921. zType,
  76922. p->zName,
  76923. p->zName,
  76924. pParse->regRoot,
  76925. zStmt,
  76926. pParse->regRowid
  76927. );
  76928. sqlite3DbFree(db, zStmt);
  76929. sqlite3ChangeCookie(pParse, iDb);
  76930. #ifndef SQLITE_OMIT_AUTOINCREMENT
  76931. /* Check to see if we need to create an sqlite_sequence table for
  76932. ** keeping track of autoincrement keys.
  76933. */
  76934. if( p->tabFlags & TF_Autoincrement ){
  76935. Db *pDb = &db->aDb[iDb];
  76936. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76937. if( pDb->pSchema->pSeqTab==0 ){
  76938. sqlite3NestedParse(pParse,
  76939. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  76940. pDb->zName
  76941. );
  76942. }
  76943. }
  76944. #endif
  76945. /* Reparse everything to update our internal data structures */
  76946. sqlite3VdbeAddParseSchemaOp(v, iDb,
  76947. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  76948. }
  76949. /* Add the table to the in-memory representation of the database.
  76950. */
  76951. if( db->init.busy ){
  76952. Table *pOld;
  76953. Schema *pSchema = p->pSchema;
  76954. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76955. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  76956. sqlite3Strlen30(p->zName),p);
  76957. if( pOld ){
  76958. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  76959. db->mallocFailed = 1;
  76960. return;
  76961. }
  76962. pParse->pNewTable = 0;
  76963. db->flags |= SQLITE_InternChanges;
  76964. #ifndef SQLITE_OMIT_ALTERTABLE
  76965. if( !p->pSelect ){
  76966. const char *zName = (const char *)pParse->sNameToken.z;
  76967. int nName;
  76968. assert( !pSelect && pCons && pEnd );
  76969. if( pCons->z==0 ){
  76970. pCons = pEnd;
  76971. }
  76972. nName = (int)((const char *)pCons->z - zName);
  76973. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  76974. }
  76975. #endif
  76976. }
  76977. }
  76978. #ifndef SQLITE_OMIT_VIEW
  76979. /*
  76980. ** The parser calls this routine in order to create a new VIEW
  76981. */
  76982. SQLITE_PRIVATE void sqlite3CreateView(
  76983. Parse *pParse, /* The parsing context */
  76984. Token *pBegin, /* The CREATE token that begins the statement */
  76985. Token *pName1, /* The token that holds the name of the view */
  76986. Token *pName2, /* The token that holds the name of the view */
  76987. Select *pSelect, /* A SELECT statement that will become the new view */
  76988. int isTemp, /* TRUE for a TEMPORARY view */
  76989. int noErr /* Suppress error messages if VIEW already exists */
  76990. ){
  76991. Table *p;
  76992. int n;
  76993. const char *z;
  76994. Token sEnd;
  76995. DbFixer sFix;
  76996. Token *pName = 0;
  76997. int iDb;
  76998. sqlite3 *db = pParse->db;
  76999. if( pParse->nVar>0 ){
  77000. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  77001. sqlite3SelectDelete(db, pSelect);
  77002. return;
  77003. }
  77004. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  77005. p = pParse->pNewTable;
  77006. if( p==0 || pParse->nErr ){
  77007. sqlite3SelectDelete(db, pSelect);
  77008. return;
  77009. }
  77010. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  77011. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  77012. if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  77013. && sqlite3FixSelect(&sFix, pSelect)
  77014. ){
  77015. sqlite3SelectDelete(db, pSelect);
  77016. return;
  77017. }
  77018. /* Make a copy of the entire SELECT statement that defines the view.
  77019. ** This will force all the Expr.token.z values to be dynamically
  77020. ** allocated rather than point to the input string - which means that
  77021. ** they will persist after the current sqlite3_exec() call returns.
  77022. */
  77023. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  77024. sqlite3SelectDelete(db, pSelect);
  77025. if( db->mallocFailed ){
  77026. return;
  77027. }
  77028. if( !db->init.busy ){
  77029. sqlite3ViewGetColumnNames(pParse, p);
  77030. }
  77031. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  77032. ** the end.
  77033. */
  77034. sEnd = pParse->sLastToken;
  77035. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  77036. sEnd.z += sEnd.n;
  77037. }
  77038. sEnd.n = 0;
  77039. n = (int)(sEnd.z - pBegin->z);
  77040. z = pBegin->z;
  77041. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  77042. sEnd.z = &z[n-1];
  77043. sEnd.n = 1;
  77044. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  77045. sqlite3EndTable(pParse, 0, &sEnd, 0);
  77046. return;
  77047. }
  77048. #endif /* SQLITE_OMIT_VIEW */
  77049. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  77050. /*
  77051. ** The Table structure pTable is really a VIEW. Fill in the names of
  77052. ** the columns of the view in the pTable structure. Return the number
  77053. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  77054. */
  77055. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  77056. Table *pSelTab; /* A fake table from which we get the result set */
  77057. Select *pSel; /* Copy of the SELECT that implements the view */
  77058. int nErr = 0; /* Number of errors encountered */
  77059. int n; /* Temporarily holds the number of cursors assigned */
  77060. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  77061. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  77062. assert( pTable );
  77063. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77064. if( sqlite3VtabCallConnect(pParse, pTable) ){
  77065. return SQLITE_ERROR;
  77066. }
  77067. if( IsVirtual(pTable) ) return 0;
  77068. #endif
  77069. #ifndef SQLITE_OMIT_VIEW
  77070. /* A positive nCol means the columns names for this view are
  77071. ** already known.
  77072. */
  77073. if( pTable->nCol>0 ) return 0;
  77074. /* A negative nCol is a special marker meaning that we are currently
  77075. ** trying to compute the column names. If we enter this routine with
  77076. ** a negative nCol, it means two or more views form a loop, like this:
  77077. **
  77078. ** CREATE VIEW one AS SELECT * FROM two;
  77079. ** CREATE VIEW two AS SELECT * FROM one;
  77080. **
  77081. ** Actually, the error above is now caught prior to reaching this point.
  77082. ** But the following test is still important as it does come up
  77083. ** in the following:
  77084. **
  77085. ** CREATE TABLE main.ex1(a);
  77086. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  77087. ** SELECT * FROM temp.ex1;
  77088. */
  77089. if( pTable->nCol<0 ){
  77090. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  77091. return 1;
  77092. }
  77093. assert( pTable->nCol>=0 );
  77094. /* If we get this far, it means we need to compute the table names.
  77095. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  77096. ** "*" elements in the results set of the view and will assign cursors
  77097. ** to the elements of the FROM clause. But we do not want these changes
  77098. ** to be permanent. So the computation is done on a copy of the SELECT
  77099. ** statement that defines the view.
  77100. */
  77101. assert( pTable->pSelect );
  77102. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  77103. if( pSel ){
  77104. u8 enableLookaside = db->lookaside.bEnabled;
  77105. n = pParse->nTab;
  77106. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  77107. pTable->nCol = -1;
  77108. db->lookaside.bEnabled = 0;
  77109. #ifndef SQLITE_OMIT_AUTHORIZATION
  77110. xAuth = db->xAuth;
  77111. db->xAuth = 0;
  77112. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  77113. db->xAuth = xAuth;
  77114. #else
  77115. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  77116. #endif
  77117. db->lookaside.bEnabled = enableLookaside;
  77118. pParse->nTab = n;
  77119. if( pSelTab ){
  77120. assert( pTable->aCol==0 );
  77121. pTable->nCol = pSelTab->nCol;
  77122. pTable->aCol = pSelTab->aCol;
  77123. pSelTab->nCol = 0;
  77124. pSelTab->aCol = 0;
  77125. sqlite3DeleteTable(db, pSelTab);
  77126. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  77127. pTable->pSchema->flags |= DB_UnresetViews;
  77128. }else{
  77129. pTable->nCol = 0;
  77130. nErr++;
  77131. }
  77132. sqlite3SelectDelete(db, pSel);
  77133. } else {
  77134. nErr++;
  77135. }
  77136. #endif /* SQLITE_OMIT_VIEW */
  77137. return nErr;
  77138. }
  77139. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  77140. #ifndef SQLITE_OMIT_VIEW
  77141. /*
  77142. ** Clear the column names from every VIEW in database idx.
  77143. */
  77144. static void sqliteViewResetAll(sqlite3 *db, int idx){
  77145. HashElem *i;
  77146. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  77147. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  77148. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  77149. Table *pTab = sqliteHashData(i);
  77150. if( pTab->pSelect ){
  77151. sqliteDeleteColumnNames(db, pTab);
  77152. pTab->aCol = 0;
  77153. pTab->nCol = 0;
  77154. }
  77155. }
  77156. DbClearProperty(db, idx, DB_UnresetViews);
  77157. }
  77158. #else
  77159. # define sqliteViewResetAll(A,B)
  77160. #endif /* SQLITE_OMIT_VIEW */
  77161. /*
  77162. ** This function is called by the VDBE to adjust the internal schema
  77163. ** used by SQLite when the btree layer moves a table root page. The
  77164. ** root-page of a table or index in database iDb has changed from iFrom
  77165. ** to iTo.
  77166. **
  77167. ** Ticket #1728: The symbol table might still contain information
  77168. ** on tables and/or indices that are the process of being deleted.
  77169. ** If you are unlucky, one of those deleted indices or tables might
  77170. ** have the same rootpage number as the real table or index that is
  77171. ** being moved. So we cannot stop searching after the first match
  77172. ** because the first match might be for one of the deleted indices
  77173. ** or tables and not the table/index that is actually being moved.
  77174. ** We must continue looping until all tables and indices with
  77175. ** rootpage==iFrom have been converted to have a rootpage of iTo
  77176. ** in order to be certain that we got the right one.
  77177. */
  77178. #ifndef SQLITE_OMIT_AUTOVACUUM
  77179. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  77180. HashElem *pElem;
  77181. Hash *pHash;
  77182. Db *pDb;
  77183. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77184. pDb = &db->aDb[iDb];
  77185. pHash = &pDb->pSchema->tblHash;
  77186. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  77187. Table *pTab = sqliteHashData(pElem);
  77188. if( pTab->tnum==iFrom ){
  77189. pTab->tnum = iTo;
  77190. }
  77191. }
  77192. pHash = &pDb->pSchema->idxHash;
  77193. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  77194. Index *pIdx = sqliteHashData(pElem);
  77195. if( pIdx->tnum==iFrom ){
  77196. pIdx->tnum = iTo;
  77197. }
  77198. }
  77199. }
  77200. #endif
  77201. /*
  77202. ** Write code to erase the table with root-page iTable from database iDb.
  77203. ** Also write code to modify the sqlite_master table and internal schema
  77204. ** if a root-page of another table is moved by the btree-layer whilst
  77205. ** erasing iTable (this can happen with an auto-vacuum database).
  77206. */
  77207. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  77208. Vdbe *v = sqlite3GetVdbe(pParse);
  77209. int r1 = sqlite3GetTempReg(pParse);
  77210. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  77211. sqlite3MayAbort(pParse);
  77212. #ifndef SQLITE_OMIT_AUTOVACUUM
  77213. /* OP_Destroy stores an in integer r1. If this integer
  77214. ** is non-zero, then it is the root page number of a table moved to
  77215. ** location iTable. The following code modifies the sqlite_master table to
  77216. ** reflect this.
  77217. **
  77218. ** The "#NNN" in the SQL is a special constant that means whatever value
  77219. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  77220. ** token for additional information.
  77221. */
  77222. sqlite3NestedParse(pParse,
  77223. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  77224. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  77225. #endif
  77226. sqlite3ReleaseTempReg(pParse, r1);
  77227. }
  77228. /*
  77229. ** Write VDBE code to erase table pTab and all associated indices on disk.
  77230. ** Code to update the sqlite_master tables and internal schema definitions
  77231. ** in case a root-page belonging to another table is moved by the btree layer
  77232. ** is also added (this can happen with an auto-vacuum database).
  77233. */
  77234. static void destroyTable(Parse *pParse, Table *pTab){
  77235. #ifdef SQLITE_OMIT_AUTOVACUUM
  77236. Index *pIdx;
  77237. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  77238. destroyRootPage(pParse, pTab->tnum, iDb);
  77239. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  77240. destroyRootPage(pParse, pIdx->tnum, iDb);
  77241. }
  77242. #else
  77243. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  77244. ** is not defined), then it is important to call OP_Destroy on the
  77245. ** table and index root-pages in order, starting with the numerically
  77246. ** largest root-page number. This guarantees that none of the root-pages
  77247. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  77248. ** following were coded:
  77249. **
  77250. ** OP_Destroy 4 0
  77251. ** ...
  77252. ** OP_Destroy 5 0
  77253. **
  77254. ** and root page 5 happened to be the largest root-page number in the
  77255. ** database, then root page 5 would be moved to page 4 by the
  77256. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  77257. ** a free-list page.
  77258. */
  77259. int iTab = pTab->tnum;
  77260. int iDestroyed = 0;
  77261. while( 1 ){
  77262. Index *pIdx;
  77263. int iLargest = 0;
  77264. if( iDestroyed==0 || iTab<iDestroyed ){
  77265. iLargest = iTab;
  77266. }
  77267. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  77268. int iIdx = pIdx->tnum;
  77269. assert( pIdx->pSchema==pTab->pSchema );
  77270. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  77271. iLargest = iIdx;
  77272. }
  77273. }
  77274. if( iLargest==0 ){
  77275. return;
  77276. }else{
  77277. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  77278. assert( iDb>=0 && iDb<pParse->db->nDb );
  77279. destroyRootPage(pParse, iLargest, iDb);
  77280. iDestroyed = iLargest;
  77281. }
  77282. }
  77283. #endif
  77284. }
  77285. /*
  77286. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  77287. ** after a DROP INDEX or DROP TABLE command.
  77288. */
  77289. static void sqlite3ClearStatTables(
  77290. Parse *pParse, /* The parsing context */
  77291. int iDb, /* The database number */
  77292. const char *zType, /* "idx" or "tbl" */
  77293. const char *zName /* Name of index or table */
  77294. ){
  77295. int i;
  77296. const char *zDbName = pParse->db->aDb[iDb].zName;
  77297. for(i=1; i<=3; i++){
  77298. char zTab[24];
  77299. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  77300. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  77301. sqlite3NestedParse(pParse,
  77302. "DELETE FROM %Q.%s WHERE %s=%Q",
  77303. zDbName, zTab, zType, zName
  77304. );
  77305. }
  77306. }
  77307. }
  77308. /*
  77309. ** Generate code to drop a table.
  77310. */
  77311. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  77312. Vdbe *v;
  77313. sqlite3 *db = pParse->db;
  77314. Trigger *pTrigger;
  77315. Db *pDb = &db->aDb[iDb];
  77316. v = sqlite3GetVdbe(pParse);
  77317. assert( v!=0 );
  77318. sqlite3BeginWriteOperation(pParse, 1, iDb);
  77319. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77320. if( IsVirtual(pTab) ){
  77321. sqlite3VdbeAddOp0(v, OP_VBegin);
  77322. }
  77323. #endif
  77324. /* Drop all triggers associated with the table being dropped. Code
  77325. ** is generated to remove entries from sqlite_master and/or
  77326. ** sqlite_temp_master if required.
  77327. */
  77328. pTrigger = sqlite3TriggerList(pParse, pTab);
  77329. while( pTrigger ){
  77330. assert( pTrigger->pSchema==pTab->pSchema ||
  77331. pTrigger->pSchema==db->aDb[1].pSchema );
  77332. sqlite3DropTriggerPtr(pParse, pTrigger);
  77333. pTrigger = pTrigger->pNext;
  77334. }
  77335. #ifndef SQLITE_OMIT_AUTOINCREMENT
  77336. /* Remove any entries of the sqlite_sequence table associated with
  77337. ** the table being dropped. This is done before the table is dropped
  77338. ** at the btree level, in case the sqlite_sequence table needs to
  77339. ** move as a result of the drop (can happen in auto-vacuum mode).
  77340. */
  77341. if( pTab->tabFlags & TF_Autoincrement ){
  77342. sqlite3NestedParse(pParse,
  77343. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  77344. pDb->zName, pTab->zName
  77345. );
  77346. }
  77347. #endif
  77348. /* Drop all SQLITE_MASTER table and index entries that refer to the
  77349. ** table. The program name loops through the master table and deletes
  77350. ** every row that refers to a table of the same name as the one being
  77351. ** dropped. Triggers are handled seperately because a trigger can be
  77352. ** created in the temp database that refers to a table in another
  77353. ** database.
  77354. */
  77355. sqlite3NestedParse(pParse,
  77356. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  77357. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  77358. if( !isView && !IsVirtual(pTab) ){
  77359. destroyTable(pParse, pTab);
  77360. }
  77361. /* Remove the table entry from SQLite's internal schema and modify
  77362. ** the schema cookie.
  77363. */
  77364. if( IsVirtual(pTab) ){
  77365. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  77366. }
  77367. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  77368. sqlite3ChangeCookie(pParse, iDb);
  77369. sqliteViewResetAll(db, iDb);
  77370. }
  77371. /*
  77372. ** This routine is called to do the work of a DROP TABLE statement.
  77373. ** pName is the name of the table to be dropped.
  77374. */
  77375. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  77376. Table *pTab;
  77377. Vdbe *v;
  77378. sqlite3 *db = pParse->db;
  77379. int iDb;
  77380. if( db->mallocFailed ){
  77381. goto exit_drop_table;
  77382. }
  77383. assert( pParse->nErr==0 );
  77384. assert( pName->nSrc==1 );
  77385. if( noErr ) db->suppressErr++;
  77386. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  77387. if( noErr ) db->suppressErr--;
  77388. if( pTab==0 ){
  77389. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  77390. goto exit_drop_table;
  77391. }
  77392. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  77393. assert( iDb>=0 && iDb<db->nDb );
  77394. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  77395. ** it is initialized.
  77396. */
  77397. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  77398. goto exit_drop_table;
  77399. }
  77400. #ifndef SQLITE_OMIT_AUTHORIZATION
  77401. {
  77402. int code;
  77403. const char *zTab = SCHEMA_TABLE(iDb);
  77404. const char *zDb = db->aDb[iDb].zName;
  77405. const char *zArg2 = 0;
  77406. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  77407. goto exit_drop_table;
  77408. }
  77409. if( isView ){
  77410. if( !OMIT_TEMPDB && iDb==1 ){
  77411. code = SQLITE_DROP_TEMP_VIEW;
  77412. }else{
  77413. code = SQLITE_DROP_VIEW;
  77414. }
  77415. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77416. }else if( IsVirtual(pTab) ){
  77417. code = SQLITE_DROP_VTABLE;
  77418. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  77419. #endif
  77420. }else{
  77421. if( !OMIT_TEMPDB && iDb==1 ){
  77422. code = SQLITE_DROP_TEMP_TABLE;
  77423. }else{
  77424. code = SQLITE_DROP_TABLE;
  77425. }
  77426. }
  77427. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  77428. goto exit_drop_table;
  77429. }
  77430. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  77431. goto exit_drop_table;
  77432. }
  77433. }
  77434. #endif
  77435. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  77436. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  77437. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  77438. goto exit_drop_table;
  77439. }
  77440. #ifndef SQLITE_OMIT_VIEW
  77441. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  77442. ** on a table.
  77443. */
  77444. if( isView && pTab->pSelect==0 ){
  77445. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  77446. goto exit_drop_table;
  77447. }
  77448. if( !isView && pTab->pSelect ){
  77449. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  77450. goto exit_drop_table;
  77451. }
  77452. #endif
  77453. /* Generate code to remove the table from the master table
  77454. ** on disk.
  77455. */
  77456. v = sqlite3GetVdbe(pParse);
  77457. if( v ){
  77458. sqlite3BeginWriteOperation(pParse, 1, iDb);
  77459. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  77460. sqlite3FkDropTable(pParse, pName, pTab);
  77461. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  77462. }
  77463. exit_drop_table:
  77464. sqlite3SrcListDelete(db, pName);
  77465. }
  77466. /*
  77467. ** This routine is called to create a new foreign key on the table
  77468. ** currently under construction. pFromCol determines which columns
  77469. ** in the current table point to the foreign key. If pFromCol==0 then
  77470. ** connect the key to the last column inserted. pTo is the name of
  77471. ** the table referred to. pToCol is a list of tables in the other
  77472. ** pTo table that the foreign key points to. flags contains all
  77473. ** information about the conflict resolution algorithms specified
  77474. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  77475. **
  77476. ** An FKey structure is created and added to the table currently
  77477. ** under construction in the pParse->pNewTable field.
  77478. **
  77479. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  77480. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  77481. */
  77482. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  77483. Parse *pParse, /* Parsing context */
  77484. ExprList *pFromCol, /* Columns in this table that point to other table */
  77485. Token *pTo, /* Name of the other table */
  77486. ExprList *pToCol, /* Columns in the other table */
  77487. int flags /* Conflict resolution algorithms. */
  77488. ){
  77489. sqlite3 *db = pParse->db;
  77490. #ifndef SQLITE_OMIT_FOREIGN_KEY
  77491. FKey *pFKey = 0;
  77492. FKey *pNextTo;
  77493. Table *p = pParse->pNewTable;
  77494. int nByte;
  77495. int i;
  77496. int nCol;
  77497. char *z;
  77498. assert( pTo!=0 );
  77499. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  77500. if( pFromCol==0 ){
  77501. int iCol = p->nCol-1;
  77502. if( NEVER(iCol<0) ) goto fk_end;
  77503. if( pToCol && pToCol->nExpr!=1 ){
  77504. sqlite3ErrorMsg(pParse, "foreign key on %s"
  77505. " should reference only one column of table %T",
  77506. p->aCol[iCol].zName, pTo);
  77507. goto fk_end;
  77508. }
  77509. nCol = 1;
  77510. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  77511. sqlite3ErrorMsg(pParse,
  77512. "number of columns in foreign key does not match the number of "
  77513. "columns in the referenced table");
  77514. goto fk_end;
  77515. }else{
  77516. nCol = pFromCol->nExpr;
  77517. }
  77518. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  77519. if( pToCol ){
  77520. for(i=0; i<pToCol->nExpr; i++){
  77521. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  77522. }
  77523. }
  77524. pFKey = sqlite3DbMallocZero(db, nByte );
  77525. if( pFKey==0 ){
  77526. goto fk_end;
  77527. }
  77528. pFKey->pFrom = p;
  77529. pFKey->pNextFrom = p->pFKey;
  77530. z = (char*)&pFKey->aCol[nCol];
  77531. pFKey->zTo = z;
  77532. memcpy(z, pTo->z, pTo->n);
  77533. z[pTo->n] = 0;
  77534. sqlite3Dequote(z);
  77535. z += pTo->n+1;
  77536. pFKey->nCol = nCol;
  77537. if( pFromCol==0 ){
  77538. pFKey->aCol[0].iFrom = p->nCol-1;
  77539. }else{
  77540. for(i=0; i<nCol; i++){
  77541. int j;
  77542. for(j=0; j<p->nCol; j++){
  77543. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  77544. pFKey->aCol[i].iFrom = j;
  77545. break;
  77546. }
  77547. }
  77548. if( j>=p->nCol ){
  77549. sqlite3ErrorMsg(pParse,
  77550. "unknown column \"%s\" in foreign key definition",
  77551. pFromCol->a[i].zName);
  77552. goto fk_end;
  77553. }
  77554. }
  77555. }
  77556. if( pToCol ){
  77557. for(i=0; i<nCol; i++){
  77558. int n = sqlite3Strlen30(pToCol->a[i].zName);
  77559. pFKey->aCol[i].zCol = z;
  77560. memcpy(z, pToCol->a[i].zName, n);
  77561. z[n] = 0;
  77562. z += n+1;
  77563. }
  77564. }
  77565. pFKey->isDeferred = 0;
  77566. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  77567. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  77568. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  77569. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  77570. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  77571. );
  77572. if( pNextTo==pFKey ){
  77573. db->mallocFailed = 1;
  77574. goto fk_end;
  77575. }
  77576. if( pNextTo ){
  77577. assert( pNextTo->pPrevTo==0 );
  77578. pFKey->pNextTo = pNextTo;
  77579. pNextTo->pPrevTo = pFKey;
  77580. }
  77581. /* Link the foreign key to the table as the last step.
  77582. */
  77583. p->pFKey = pFKey;
  77584. pFKey = 0;
  77585. fk_end:
  77586. sqlite3DbFree(db, pFKey);
  77587. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  77588. sqlite3ExprListDelete(db, pFromCol);
  77589. sqlite3ExprListDelete(db, pToCol);
  77590. }
  77591. /*
  77592. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  77593. ** clause is seen as part of a foreign key definition. The isDeferred
  77594. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  77595. ** The behavior of the most recently created foreign key is adjusted
  77596. ** accordingly.
  77597. */
  77598. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  77599. #ifndef SQLITE_OMIT_FOREIGN_KEY
  77600. Table *pTab;
  77601. FKey *pFKey;
  77602. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  77603. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  77604. pFKey->isDeferred = (u8)isDeferred;
  77605. #endif
  77606. }
  77607. /*
  77608. ** Generate code that will erase and refill index *pIdx. This is
  77609. ** used to initialize a newly created index or to recompute the
  77610. ** content of an index in response to a REINDEX command.
  77611. **
  77612. ** if memRootPage is not negative, it means that the index is newly
  77613. ** created. The register specified by memRootPage contains the
  77614. ** root page number of the index. If memRootPage is negative, then
  77615. ** the index already exists and must be cleared before being refilled and
  77616. ** the root page number of the index is taken from pIndex->tnum.
  77617. */
  77618. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  77619. Table *pTab = pIndex->pTable; /* The table that is indexed */
  77620. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  77621. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  77622. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  77623. int addr1; /* Address of top of loop */
  77624. int addr2; /* Address to jump to for next iteration */
  77625. int tnum; /* Root page of index */
  77626. Vdbe *v; /* Generate code into this virtual machine */
  77627. KeyInfo *pKey; /* KeyInfo for index */
  77628. #ifdef SQLITE_OMIT_MERGE_SORT
  77629. int regIdxKey; /* Registers containing the index key */
  77630. #endif
  77631. int regRecord; /* Register holding assemblied index record */
  77632. sqlite3 *db = pParse->db; /* The database connection */
  77633. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  77634. #ifndef SQLITE_OMIT_AUTHORIZATION
  77635. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  77636. db->aDb[iDb].zName ) ){
  77637. return;
  77638. }
  77639. #endif
  77640. /* Require a write-lock on the table to perform this operation */
  77641. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  77642. v = sqlite3GetVdbe(pParse);
  77643. if( v==0 ) return;
  77644. if( memRootPage>=0 ){
  77645. tnum = memRootPage;
  77646. }else{
  77647. tnum = pIndex->tnum;
  77648. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  77649. }
  77650. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  77651. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  77652. (char *)pKey, P4_KEYINFO_HANDOFF);
  77653. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  77654. #ifndef SQLITE_OMIT_MERGE_SORT
  77655. /* Open the sorter cursor if we are to use one. */
  77656. iSorter = pParse->nTab++;
  77657. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  77658. #else
  77659. iSorter = iTab;
  77660. #endif
  77661. /* Open the table. Loop through all rows of the table, inserting index
  77662. ** records into the sorter. */
  77663. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  77664. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  77665. regRecord = sqlite3GetTempReg(pParse);
  77666. #ifndef SQLITE_OMIT_MERGE_SORT
  77667. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  77668. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  77669. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  77670. sqlite3VdbeJumpHere(v, addr1);
  77671. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  77672. if( pIndex->onError!=OE_None ){
  77673. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  77674. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  77675. addr2 = sqlite3VdbeCurrentAddr(v);
  77676. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  77677. sqlite3HaltConstraint(
  77678. pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
  77679. );
  77680. }else{
  77681. addr2 = sqlite3VdbeCurrentAddr(v);
  77682. }
  77683. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  77684. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  77685. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  77686. #else
  77687. regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  77688. addr2 = addr1 + 1;
  77689. if( pIndex->onError!=OE_None ){
  77690. const int regRowid = regIdxKey + pIndex->nColumn;
  77691. const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
  77692. void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
  77693. /* The registers accessed by the OP_IsUnique opcode were allocated
  77694. ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
  77695. ** call above. Just before that function was freed they were released
  77696. ** (made available to the compiler for reuse) using
  77697. ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
  77698. ** opcode use the values stored within seems dangerous. However, since
  77699. ** we can be sure that no other temp registers have been allocated
  77700. ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
  77701. */
  77702. sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
  77703. sqlite3HaltConstraint(
  77704. pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
  77705. }
  77706. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  77707. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  77708. #endif
  77709. sqlite3ReleaseTempReg(pParse, regRecord);
  77710. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  77711. sqlite3VdbeJumpHere(v, addr1);
  77712. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  77713. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  77714. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  77715. }
  77716. /*
  77717. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  77718. ** and pTblList is the name of the table that is to be indexed. Both will
  77719. ** be NULL for a primary key or an index that is created to satisfy a
  77720. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  77721. ** as the table to be indexed. pParse->pNewTable is a table that is
  77722. ** currently being constructed by a CREATE TABLE statement.
  77723. **
  77724. ** pList is a list of columns to be indexed. pList will be NULL if this
  77725. ** is a primary key or unique-constraint on the most recent column added
  77726. ** to the table currently under construction.
  77727. **
  77728. ** If the index is created successfully, return a pointer to the new Index
  77729. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  77730. ** as the tables primary key (Index.autoIndex==2).
  77731. */
  77732. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  77733. Parse *pParse, /* All information about this parse */
  77734. Token *pName1, /* First part of index name. May be NULL */
  77735. Token *pName2, /* Second part of index name. May be NULL */
  77736. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  77737. ExprList *pList, /* A list of columns to be indexed */
  77738. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  77739. Token *pStart, /* The CREATE token that begins this statement */
  77740. Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
  77741. int sortOrder, /* Sort order of primary key when pList==NULL */
  77742. int ifNotExist /* Omit error if index already exists */
  77743. ){
  77744. Index *pRet = 0; /* Pointer to return */
  77745. Table *pTab = 0; /* Table to be indexed */
  77746. Index *pIndex = 0; /* The index to be created */
  77747. char *zName = 0; /* Name of the index */
  77748. int nName; /* Number of characters in zName */
  77749. int i, j;
  77750. Token nullId; /* Fake token for an empty ID list */
  77751. DbFixer sFix; /* For assigning database names to pTable */
  77752. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  77753. sqlite3 *db = pParse->db;
  77754. Db *pDb; /* The specific table containing the indexed database */
  77755. int iDb; /* Index of the database that is being written */
  77756. Token *pName = 0; /* Unqualified name of the index to create */
  77757. struct ExprList_item *pListItem; /* For looping over pList */
  77758. int nCol;
  77759. int nExtra = 0;
  77760. char *zExtra;
  77761. assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
  77762. assert( pParse->nErr==0 ); /* Never called with prior errors */
  77763. if( db->mallocFailed || IN_DECLARE_VTAB ){
  77764. goto exit_create_index;
  77765. }
  77766. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  77767. goto exit_create_index;
  77768. }
  77769. /*
  77770. ** Find the table that is to be indexed. Return early if not found.
  77771. */
  77772. if( pTblName!=0 ){
  77773. /* Use the two-part index name to determine the database
  77774. ** to search for the table. 'Fix' the table name to this db
  77775. ** before looking up the table.
  77776. */
  77777. assert( pName1 && pName2 );
  77778. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  77779. if( iDb<0 ) goto exit_create_index;
  77780. assert( pName && pName->z );
  77781. #ifndef SQLITE_OMIT_TEMPDB
  77782. /* If the index name was unqualified, check if the table
  77783. ** is a temp table. If so, set the database to 1. Do not do this
  77784. ** if initialising a database schema.
  77785. */
  77786. if( !db->init.busy ){
  77787. pTab = sqlite3SrcListLookup(pParse, pTblName);
  77788. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  77789. iDb = 1;
  77790. }
  77791. }
  77792. #endif
  77793. if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  77794. sqlite3FixSrcList(&sFix, pTblName)
  77795. ){
  77796. /* Because the parser constructs pTblName from a single identifier,
  77797. ** sqlite3FixSrcList can never fail. */
  77798. assert(0);
  77799. }
  77800. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  77801. assert( db->mallocFailed==0 || pTab==0 );
  77802. if( pTab==0 ) goto exit_create_index;
  77803. assert( db->aDb[iDb].pSchema==pTab->pSchema );
  77804. }else{
  77805. assert( pName==0 );
  77806. assert( pStart==0 );
  77807. pTab = pParse->pNewTable;
  77808. if( !pTab ) goto exit_create_index;
  77809. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  77810. }
  77811. pDb = &db->aDb[iDb];
  77812. assert( pTab!=0 );
  77813. assert( pParse->nErr==0 );
  77814. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  77815. && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
  77816. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  77817. goto exit_create_index;
  77818. }
  77819. #ifndef SQLITE_OMIT_VIEW
  77820. if( pTab->pSelect ){
  77821. sqlite3ErrorMsg(pParse, "views may not be indexed");
  77822. goto exit_create_index;
  77823. }
  77824. #endif
  77825. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77826. if( IsVirtual(pTab) ){
  77827. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  77828. goto exit_create_index;
  77829. }
  77830. #endif
  77831. /*
  77832. ** Find the name of the index. Make sure there is not already another
  77833. ** index or table with the same name.
  77834. **
  77835. ** Exception: If we are reading the names of permanent indices from the
  77836. ** sqlite_master table (because some other process changed the schema) and
  77837. ** one of the index names collides with the name of a temporary table or
  77838. ** index, then we will continue to process this index.
  77839. **
  77840. ** If pName==0 it means that we are
  77841. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  77842. ** own name.
  77843. */
  77844. if( pName ){
  77845. zName = sqlite3NameFromToken(db, pName);
  77846. if( zName==0 ) goto exit_create_index;
  77847. assert( pName->z!=0 );
  77848. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  77849. goto exit_create_index;
  77850. }
  77851. if( !db->init.busy ){
  77852. if( sqlite3FindTable(db, zName, 0)!=0 ){
  77853. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  77854. goto exit_create_index;
  77855. }
  77856. }
  77857. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  77858. if( !ifNotExist ){
  77859. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  77860. }else{
  77861. assert( !db->init.busy );
  77862. sqlite3CodeVerifySchema(pParse, iDb);
  77863. }
  77864. goto exit_create_index;
  77865. }
  77866. }else{
  77867. int n;
  77868. Index *pLoop;
  77869. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  77870. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  77871. if( zName==0 ){
  77872. goto exit_create_index;
  77873. }
  77874. }
  77875. /* Check for authorization to create an index.
  77876. */
  77877. #ifndef SQLITE_OMIT_AUTHORIZATION
  77878. {
  77879. const char *zDb = pDb->zName;
  77880. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  77881. goto exit_create_index;
  77882. }
  77883. i = SQLITE_CREATE_INDEX;
  77884. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  77885. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  77886. goto exit_create_index;
  77887. }
  77888. }
  77889. #endif
  77890. /* If pList==0, it means this routine was called to make a primary
  77891. ** key out of the last column added to the table under construction.
  77892. ** So create a fake list to simulate this.
  77893. */
  77894. if( pList==0 ){
  77895. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  77896. nullId.n = sqlite3Strlen30((char*)nullId.z);
  77897. pList = sqlite3ExprListAppend(pParse, 0, 0);
  77898. if( pList==0 ) goto exit_create_index;
  77899. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  77900. pList->a[0].sortOrder = (u8)sortOrder;
  77901. }
  77902. /* Figure out how many bytes of space are required to store explicitly
  77903. ** specified collation sequence names.
  77904. */
  77905. for(i=0; i<pList->nExpr; i++){
  77906. Expr *pExpr = pList->a[i].pExpr;
  77907. if( pExpr ){
  77908. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
  77909. if( pColl ){
  77910. nExtra += (1 + sqlite3Strlen30(pColl->zName));
  77911. }
  77912. }
  77913. }
  77914. /*
  77915. ** Allocate the index structure.
  77916. */
  77917. nName = sqlite3Strlen30(zName);
  77918. nCol = pList->nExpr;
  77919. pIndex = sqlite3DbMallocZero(db,
  77920. ROUND8(sizeof(Index)) + /* Index structure */
  77921. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  77922. sizeof(char *)*nCol + /* Index.azColl */
  77923. sizeof(int)*nCol + /* Index.aiColumn */
  77924. sizeof(u8)*nCol + /* Index.aSortOrder */
  77925. nName + 1 + /* Index.zName */
  77926. nExtra /* Collation sequence names */
  77927. );
  77928. if( db->mallocFailed ){
  77929. goto exit_create_index;
  77930. }
  77931. zExtra = (char*)pIndex;
  77932. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  77933. pIndex->azColl = (char**)
  77934. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  77935. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  77936. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  77937. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  77938. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  77939. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  77940. zExtra = (char *)(&pIndex->zName[nName+1]);
  77941. memcpy(pIndex->zName, zName, nName+1);
  77942. pIndex->pTable = pTab;
  77943. pIndex->nColumn = pList->nExpr;
  77944. pIndex->onError = (u8)onError;
  77945. pIndex->autoIndex = (u8)(pName==0);
  77946. pIndex->pSchema = db->aDb[iDb].pSchema;
  77947. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  77948. /* Check to see if we should honor DESC requests on index columns
  77949. */
  77950. if( pDb->pSchema->file_format>=4 ){
  77951. sortOrderMask = -1; /* Honor DESC */
  77952. }else{
  77953. sortOrderMask = 0; /* Ignore DESC */
  77954. }
  77955. /* Scan the names of the columns of the table to be indexed and
  77956. ** load the column indices into the Index structure. Report an error
  77957. ** if any column is not found.
  77958. **
  77959. ** TODO: Add a test to make sure that the same column is not named
  77960. ** more than once within the same index. Only the first instance of
  77961. ** the column will ever be used by the optimizer. Note that using the
  77962. ** same column more than once cannot be an error because that would
  77963. ** break backwards compatibility - it needs to be a warning.
  77964. */
  77965. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  77966. const char *zColName = pListItem->zName;
  77967. Column *pTabCol;
  77968. int requestedSortOrder;
  77969. CollSeq *pColl; /* Collating sequence */
  77970. char *zColl; /* Collation sequence name */
  77971. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  77972. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  77973. }
  77974. if( j>=pTab->nCol ){
  77975. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  77976. pTab->zName, zColName);
  77977. pParse->checkSchema = 1;
  77978. goto exit_create_index;
  77979. }
  77980. pIndex->aiColumn[i] = j;
  77981. if( pListItem->pExpr
  77982. && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
  77983. ){
  77984. int nColl;
  77985. zColl = pColl->zName;
  77986. nColl = sqlite3Strlen30(zColl) + 1;
  77987. assert( nExtra>=nColl );
  77988. memcpy(zExtra, zColl, nColl);
  77989. zColl = zExtra;
  77990. zExtra += nColl;
  77991. nExtra -= nColl;
  77992. }else{
  77993. zColl = pTab->aCol[j].zColl;
  77994. if( !zColl ){
  77995. zColl = "BINARY";
  77996. }
  77997. }
  77998. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  77999. goto exit_create_index;
  78000. }
  78001. pIndex->azColl[i] = zColl;
  78002. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  78003. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  78004. }
  78005. sqlite3DefaultRowEst(pIndex);
  78006. if( pTab==pParse->pNewTable ){
  78007. /* This routine has been called to create an automatic index as a
  78008. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  78009. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  78010. ** i.e. one of:
  78011. **
  78012. ** CREATE TABLE t(x PRIMARY KEY, y);
  78013. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  78014. **
  78015. ** Either way, check to see if the table already has such an index. If
  78016. ** so, don't bother creating this one. This only applies to
  78017. ** automatically created indices. Users can do as they wish with
  78018. ** explicit indices.
  78019. **
  78020. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  78021. ** (and thus suppressing the second one) even if they have different
  78022. ** sort orders.
  78023. **
  78024. ** If there are different collating sequences or if the columns of
  78025. ** the constraint occur in different orders, then the constraints are
  78026. ** considered distinct and both result in separate indices.
  78027. */
  78028. Index *pIdx;
  78029. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  78030. int k;
  78031. assert( pIdx->onError!=OE_None );
  78032. assert( pIdx->autoIndex );
  78033. assert( pIndex->onError!=OE_None );
  78034. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  78035. for(k=0; k<pIdx->nColumn; k++){
  78036. const char *z1;
  78037. const char *z2;
  78038. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  78039. z1 = pIdx->azColl[k];
  78040. z2 = pIndex->azColl[k];
  78041. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  78042. }
  78043. if( k==pIdx->nColumn ){
  78044. if( pIdx->onError!=pIndex->onError ){
  78045. /* This constraint creates the same index as a previous
  78046. ** constraint specified somewhere in the CREATE TABLE statement.
  78047. ** However the ON CONFLICT clauses are different. If both this
  78048. ** constraint and the previous equivalent constraint have explicit
  78049. ** ON CONFLICT clauses this is an error. Otherwise, use the
  78050. ** explicitly specified behaviour for the index.
  78051. */
  78052. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  78053. sqlite3ErrorMsg(pParse,
  78054. "conflicting ON CONFLICT clauses specified", 0);
  78055. }
  78056. if( pIdx->onError==OE_Default ){
  78057. pIdx->onError = pIndex->onError;
  78058. }
  78059. }
  78060. goto exit_create_index;
  78061. }
  78062. }
  78063. }
  78064. /* Link the new Index structure to its table and to the other
  78065. ** in-memory database structures.
  78066. */
  78067. if( db->init.busy ){
  78068. Index *p;
  78069. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  78070. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  78071. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  78072. pIndex);
  78073. if( p ){
  78074. assert( p==pIndex ); /* Malloc must have failed */
  78075. db->mallocFailed = 1;
  78076. goto exit_create_index;
  78077. }
  78078. db->flags |= SQLITE_InternChanges;
  78079. if( pTblName!=0 ){
  78080. pIndex->tnum = db->init.newTnum;
  78081. }
  78082. }
  78083. /* If the db->init.busy is 0 then create the index on disk. This
  78084. ** involves writing the index into the master table and filling in the
  78085. ** index with the current table contents.
  78086. **
  78087. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  78088. ** command. db->init.busy is 1 when a database is opened and
  78089. ** CREATE INDEX statements are read out of the master table. In
  78090. ** the latter case the index already exists on disk, which is why
  78091. ** we don't want to recreate it.
  78092. **
  78093. ** If pTblName==0 it means this index is generated as a primary key
  78094. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  78095. ** has just been created, it contains no data and the index initialization
  78096. ** step can be skipped.
  78097. */
  78098. else{ /* if( db->init.busy==0 ) */
  78099. Vdbe *v;
  78100. char *zStmt;
  78101. int iMem = ++pParse->nMem;
  78102. v = sqlite3GetVdbe(pParse);
  78103. if( v==0 ) goto exit_create_index;
  78104. /* Create the rootpage for the index
  78105. */
  78106. sqlite3BeginWriteOperation(pParse, 1, iDb);
  78107. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  78108. /* Gather the complete text of the CREATE INDEX statement into
  78109. ** the zStmt variable
  78110. */
  78111. if( pStart ){
  78112. assert( pEnd!=0 );
  78113. /* A named index with an explicit CREATE INDEX statement */
  78114. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  78115. onError==OE_None ? "" : " UNIQUE",
  78116. (int)(pEnd->z - pName->z) + 1,
  78117. pName->z);
  78118. }else{
  78119. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  78120. /* zStmt = sqlite3MPrintf(""); */
  78121. zStmt = 0;
  78122. }
  78123. /* Add an entry in sqlite_master for this index
  78124. */
  78125. sqlite3NestedParse(pParse,
  78126. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  78127. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  78128. pIndex->zName,
  78129. pTab->zName,
  78130. iMem,
  78131. zStmt
  78132. );
  78133. sqlite3DbFree(db, zStmt);
  78134. /* Fill the index with data and reparse the schema. Code an OP_Expire
  78135. ** to invalidate all pre-compiled statements.
  78136. */
  78137. if( pTblName ){
  78138. sqlite3RefillIndex(pParse, pIndex, iMem);
  78139. sqlite3ChangeCookie(pParse, iDb);
  78140. sqlite3VdbeAddParseSchemaOp(v, iDb,
  78141. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  78142. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  78143. }
  78144. }
  78145. /* When adding an index to the list of indices for a table, make
  78146. ** sure all indices labeled OE_Replace come after all those labeled
  78147. ** OE_Ignore. This is necessary for the correct constraint check
  78148. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  78149. ** UPDATE and INSERT statements.
  78150. */
  78151. if( db->init.busy || pTblName==0 ){
  78152. if( onError!=OE_Replace || pTab->pIndex==0
  78153. || pTab->pIndex->onError==OE_Replace){
  78154. pIndex->pNext = pTab->pIndex;
  78155. pTab->pIndex = pIndex;
  78156. }else{
  78157. Index *pOther = pTab->pIndex;
  78158. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  78159. pOther = pOther->pNext;
  78160. }
  78161. pIndex->pNext = pOther->pNext;
  78162. pOther->pNext = pIndex;
  78163. }
  78164. pRet = pIndex;
  78165. pIndex = 0;
  78166. }
  78167. /* Clean up before exiting */
  78168. exit_create_index:
  78169. if( pIndex ){
  78170. sqlite3DbFree(db, pIndex->zColAff);
  78171. sqlite3DbFree(db, pIndex);
  78172. }
  78173. sqlite3ExprListDelete(db, pList);
  78174. sqlite3SrcListDelete(db, pTblName);
  78175. sqlite3DbFree(db, zName);
  78176. return pRet;
  78177. }
  78178. /*
  78179. ** Fill the Index.aiRowEst[] array with default information - information
  78180. ** to be used when we have not run the ANALYZE command.
  78181. **
  78182. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  78183. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  78184. ** number of rows in the table that match any particular value of the
  78185. ** first column of the index. aiRowEst[2] is an estimate of the number
  78186. ** of rows that match any particular combiniation of the first 2 columns
  78187. ** of the index. And so forth. It must always be the case that
  78188. *
  78189. ** aiRowEst[N]<=aiRowEst[N-1]
  78190. ** aiRowEst[N]>=1
  78191. **
  78192. ** Apart from that, we have little to go on besides intuition as to
  78193. ** how aiRowEst[] should be initialized. The numbers generated here
  78194. ** are based on typical values found in actual indices.
  78195. */
  78196. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  78197. tRowcnt *a = pIdx->aiRowEst;
  78198. int i;
  78199. tRowcnt n;
  78200. assert( a!=0 );
  78201. a[0] = pIdx->pTable->nRowEst;
  78202. if( a[0]<10 ) a[0] = 10;
  78203. n = 10;
  78204. for(i=1; i<=pIdx->nColumn; i++){
  78205. a[i] = n;
  78206. if( n>5 ) n--;
  78207. }
  78208. if( pIdx->onError!=OE_None ){
  78209. a[pIdx->nColumn] = 1;
  78210. }
  78211. }
  78212. /*
  78213. ** This routine will drop an existing named index. This routine
  78214. ** implements the DROP INDEX statement.
  78215. */
  78216. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  78217. Index *pIndex;
  78218. Vdbe *v;
  78219. sqlite3 *db = pParse->db;
  78220. int iDb;
  78221. assert( pParse->nErr==0 ); /* Never called with prior errors */
  78222. if( db->mallocFailed ){
  78223. goto exit_drop_index;
  78224. }
  78225. assert( pName->nSrc==1 );
  78226. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  78227. goto exit_drop_index;
  78228. }
  78229. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  78230. if( pIndex==0 ){
  78231. if( !ifExists ){
  78232. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  78233. }else{
  78234. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  78235. }
  78236. pParse->checkSchema = 1;
  78237. goto exit_drop_index;
  78238. }
  78239. if( pIndex->autoIndex ){
  78240. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  78241. "or PRIMARY KEY constraint cannot be dropped", 0);
  78242. goto exit_drop_index;
  78243. }
  78244. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  78245. #ifndef SQLITE_OMIT_AUTHORIZATION
  78246. {
  78247. int code = SQLITE_DROP_INDEX;
  78248. Table *pTab = pIndex->pTable;
  78249. const char *zDb = db->aDb[iDb].zName;
  78250. const char *zTab = SCHEMA_TABLE(iDb);
  78251. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  78252. goto exit_drop_index;
  78253. }
  78254. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  78255. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  78256. goto exit_drop_index;
  78257. }
  78258. }
  78259. #endif
  78260. /* Generate code to remove the index and from the master table */
  78261. v = sqlite3GetVdbe(pParse);
  78262. if( v ){
  78263. sqlite3BeginWriteOperation(pParse, 1, iDb);
  78264. sqlite3NestedParse(pParse,
  78265. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  78266. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  78267. );
  78268. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  78269. sqlite3ChangeCookie(pParse, iDb);
  78270. destroyRootPage(pParse, pIndex->tnum, iDb);
  78271. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  78272. }
  78273. exit_drop_index:
  78274. sqlite3SrcListDelete(db, pName);
  78275. }
  78276. /*
  78277. ** pArray is a pointer to an array of objects. Each object in the
  78278. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  78279. ** to extend the array so that there is space for a new object at the end.
  78280. **
  78281. ** When this function is called, *pnEntry contains the current size of
  78282. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  78283. ** in total).
  78284. **
  78285. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  78286. ** space allocated for the new object is zeroed, *pnEntry updated to
  78287. ** reflect the new size of the array and a pointer to the new allocation
  78288. ** returned. *pIdx is set to the index of the new array entry in this case.
  78289. **
  78290. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  78291. ** unchanged and a copy of pArray returned.
  78292. */
  78293. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  78294. sqlite3 *db, /* Connection to notify of malloc failures */
  78295. void *pArray, /* Array of objects. Might be reallocated */
  78296. int szEntry, /* Size of each object in the array */
  78297. int *pnEntry, /* Number of objects currently in use */
  78298. int *pIdx /* Write the index of a new slot here */
  78299. ){
  78300. char *z;
  78301. int n = *pnEntry;
  78302. if( (n & (n-1))==0 ){
  78303. int sz = (n==0) ? 1 : 2*n;
  78304. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  78305. if( pNew==0 ){
  78306. *pIdx = -1;
  78307. return pArray;
  78308. }
  78309. pArray = pNew;
  78310. }
  78311. z = (char*)pArray;
  78312. memset(&z[n * szEntry], 0, szEntry);
  78313. *pIdx = n;
  78314. ++*pnEntry;
  78315. return pArray;
  78316. }
  78317. /*
  78318. ** Append a new element to the given IdList. Create a new IdList if
  78319. ** need be.
  78320. **
  78321. ** A new IdList is returned, or NULL if malloc() fails.
  78322. */
  78323. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  78324. int i;
  78325. if( pList==0 ){
  78326. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  78327. if( pList==0 ) return 0;
  78328. }
  78329. pList->a = sqlite3ArrayAllocate(
  78330. db,
  78331. pList->a,
  78332. sizeof(pList->a[0]),
  78333. &pList->nId,
  78334. &i
  78335. );
  78336. if( i<0 ){
  78337. sqlite3IdListDelete(db, pList);
  78338. return 0;
  78339. }
  78340. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  78341. return pList;
  78342. }
  78343. /*
  78344. ** Delete an IdList.
  78345. */
  78346. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  78347. int i;
  78348. if( pList==0 ) return;
  78349. for(i=0; i<pList->nId; i++){
  78350. sqlite3DbFree(db, pList->a[i].zName);
  78351. }
  78352. sqlite3DbFree(db, pList->a);
  78353. sqlite3DbFree(db, pList);
  78354. }
  78355. /*
  78356. ** Return the index in pList of the identifier named zId. Return -1
  78357. ** if not found.
  78358. */
  78359. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  78360. int i;
  78361. if( pList==0 ) return -1;
  78362. for(i=0; i<pList->nId; i++){
  78363. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  78364. }
  78365. return -1;
  78366. }
  78367. /*
  78368. ** Expand the space allocated for the given SrcList object by
  78369. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  78370. ** New slots are zeroed.
  78371. **
  78372. ** For example, suppose a SrcList initially contains two entries: A,B.
  78373. ** To append 3 new entries onto the end, do this:
  78374. **
  78375. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  78376. **
  78377. ** After the call above it would contain: A, B, nil, nil, nil.
  78378. ** If the iStart argument had been 1 instead of 2, then the result
  78379. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  78380. ** the iStart value would be 0. The result then would
  78381. ** be: nil, nil, nil, A, B.
  78382. **
  78383. ** If a memory allocation fails the SrcList is unchanged. The
  78384. ** db->mallocFailed flag will be set to true.
  78385. */
  78386. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  78387. sqlite3 *db, /* Database connection to notify of OOM errors */
  78388. SrcList *pSrc, /* The SrcList to be enlarged */
  78389. int nExtra, /* Number of new slots to add to pSrc->a[] */
  78390. int iStart /* Index in pSrc->a[] of first new slot */
  78391. ){
  78392. int i;
  78393. /* Sanity checking on calling parameters */
  78394. assert( iStart>=0 );
  78395. assert( nExtra>=1 );
  78396. assert( pSrc!=0 );
  78397. assert( iStart<=pSrc->nSrc );
  78398. /* Allocate additional space if needed */
  78399. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  78400. SrcList *pNew;
  78401. int nAlloc = pSrc->nSrc+nExtra;
  78402. int nGot;
  78403. pNew = sqlite3DbRealloc(db, pSrc,
  78404. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  78405. if( pNew==0 ){
  78406. assert( db->mallocFailed );
  78407. return pSrc;
  78408. }
  78409. pSrc = pNew;
  78410. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  78411. pSrc->nAlloc = (u16)nGot;
  78412. }
  78413. /* Move existing slots that come after the newly inserted slots
  78414. ** out of the way */
  78415. for(i=pSrc->nSrc-1; i>=iStart; i--){
  78416. pSrc->a[i+nExtra] = pSrc->a[i];
  78417. }
  78418. pSrc->nSrc += (i16)nExtra;
  78419. /* Zero the newly allocated slots */
  78420. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  78421. for(i=iStart; i<iStart+nExtra; i++){
  78422. pSrc->a[i].iCursor = -1;
  78423. }
  78424. /* Return a pointer to the enlarged SrcList */
  78425. return pSrc;
  78426. }
  78427. /*
  78428. ** Append a new table name to the given SrcList. Create a new SrcList if
  78429. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  78430. **
  78431. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  78432. ** SrcList might be the same as the SrcList that was input or it might be
  78433. ** a new one. If an OOM error does occurs, then the prior value of pList
  78434. ** that is input to this routine is automatically freed.
  78435. **
  78436. ** If pDatabase is not null, it means that the table has an optional
  78437. ** database name prefix. Like this: "database.table". The pDatabase
  78438. ** points to the table name and the pTable points to the database name.
  78439. ** The SrcList.a[].zName field is filled with the table name which might
  78440. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  78441. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  78442. ** or with NULL if no database is specified.
  78443. **
  78444. ** In other words, if call like this:
  78445. **
  78446. ** sqlite3SrcListAppend(D,A,B,0);
  78447. **
  78448. ** Then B is a table name and the database name is unspecified. If called
  78449. ** like this:
  78450. **
  78451. ** sqlite3SrcListAppend(D,A,B,C);
  78452. **
  78453. ** Then C is the table name and B is the database name. If C is defined
  78454. ** then so is B. In other words, we never have a case where:
  78455. **
  78456. ** sqlite3SrcListAppend(D,A,0,C);
  78457. **
  78458. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  78459. ** before being added to the SrcList.
  78460. */
  78461. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  78462. sqlite3 *db, /* Connection to notify of malloc failures */
  78463. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  78464. Token *pTable, /* Table to append */
  78465. Token *pDatabase /* Database of the table */
  78466. ){
  78467. struct SrcList_item *pItem;
  78468. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  78469. if( pList==0 ){
  78470. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  78471. if( pList==0 ) return 0;
  78472. pList->nAlloc = 1;
  78473. }
  78474. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  78475. if( db->mallocFailed ){
  78476. sqlite3SrcListDelete(db, pList);
  78477. return 0;
  78478. }
  78479. pItem = &pList->a[pList->nSrc-1];
  78480. if( pDatabase && pDatabase->z==0 ){
  78481. pDatabase = 0;
  78482. }
  78483. if( pDatabase ){
  78484. Token *pTemp = pDatabase;
  78485. pDatabase = pTable;
  78486. pTable = pTemp;
  78487. }
  78488. pItem->zName = sqlite3NameFromToken(db, pTable);
  78489. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  78490. return pList;
  78491. }
  78492. /*
  78493. ** Assign VdbeCursor index numbers to all tables in a SrcList
  78494. */
  78495. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  78496. int i;
  78497. struct SrcList_item *pItem;
  78498. assert(pList || pParse->db->mallocFailed );
  78499. if( pList ){
  78500. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  78501. if( pItem->iCursor>=0 ) break;
  78502. pItem->iCursor = pParse->nTab++;
  78503. if( pItem->pSelect ){
  78504. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  78505. }
  78506. }
  78507. }
  78508. }
  78509. /*
  78510. ** Delete an entire SrcList including all its substructure.
  78511. */
  78512. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  78513. int i;
  78514. struct SrcList_item *pItem;
  78515. if( pList==0 ) return;
  78516. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  78517. sqlite3DbFree(db, pItem->zDatabase);
  78518. sqlite3DbFree(db, pItem->zName);
  78519. sqlite3DbFree(db, pItem->zAlias);
  78520. sqlite3DbFree(db, pItem->zIndex);
  78521. sqlite3DeleteTable(db, pItem->pTab);
  78522. sqlite3SelectDelete(db, pItem->pSelect);
  78523. sqlite3ExprDelete(db, pItem->pOn);
  78524. sqlite3IdListDelete(db, pItem->pUsing);
  78525. }
  78526. sqlite3DbFree(db, pList);
  78527. }
  78528. /*
  78529. ** This routine is called by the parser to add a new term to the
  78530. ** end of a growing FROM clause. The "p" parameter is the part of
  78531. ** the FROM clause that has already been constructed. "p" is NULL
  78532. ** if this is the first term of the FROM clause. pTable and pDatabase
  78533. ** are the name of the table and database named in the FROM clause term.
  78534. ** pDatabase is NULL if the database name qualifier is missing - the
  78535. ** usual case. If the term has a alias, then pAlias points to the
  78536. ** alias token. If the term is a subquery, then pSubquery is the
  78537. ** SELECT statement that the subquery encodes. The pTable and
  78538. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  78539. ** parameters are the content of the ON and USING clauses.
  78540. **
  78541. ** Return a new SrcList which encodes is the FROM with the new
  78542. ** term added.
  78543. */
  78544. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  78545. Parse *pParse, /* Parsing context */
  78546. SrcList *p, /* The left part of the FROM clause already seen */
  78547. Token *pTable, /* Name of the table to add to the FROM clause */
  78548. Token *pDatabase, /* Name of the database containing pTable */
  78549. Token *pAlias, /* The right-hand side of the AS subexpression */
  78550. Select *pSubquery, /* A subquery used in place of a table name */
  78551. Expr *pOn, /* The ON clause of a join */
  78552. IdList *pUsing /* The USING clause of a join */
  78553. ){
  78554. struct SrcList_item *pItem;
  78555. sqlite3 *db = pParse->db;
  78556. if( !p && (pOn || pUsing) ){
  78557. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  78558. (pOn ? "ON" : "USING")
  78559. );
  78560. goto append_from_error;
  78561. }
  78562. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  78563. if( p==0 || NEVER(p->nSrc==0) ){
  78564. goto append_from_error;
  78565. }
  78566. pItem = &p->a[p->nSrc-1];
  78567. assert( pAlias!=0 );
  78568. if( pAlias->n ){
  78569. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  78570. }
  78571. pItem->pSelect = pSubquery;
  78572. pItem->pOn = pOn;
  78573. pItem->pUsing = pUsing;
  78574. return p;
  78575. append_from_error:
  78576. assert( p==0 );
  78577. sqlite3ExprDelete(db, pOn);
  78578. sqlite3IdListDelete(db, pUsing);
  78579. sqlite3SelectDelete(db, pSubquery);
  78580. return 0;
  78581. }
  78582. /*
  78583. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  78584. ** element of the source-list passed as the second argument.
  78585. */
  78586. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  78587. assert( pIndexedBy!=0 );
  78588. if( p && ALWAYS(p->nSrc>0) ){
  78589. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  78590. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  78591. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  78592. /* A "NOT INDEXED" clause was supplied. See parse.y
  78593. ** construct "indexed_opt" for details. */
  78594. pItem->notIndexed = 1;
  78595. }else{
  78596. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  78597. }
  78598. }
  78599. }
  78600. /*
  78601. ** When building up a FROM clause in the parser, the join operator
  78602. ** is initially attached to the left operand. But the code generator
  78603. ** expects the join operator to be on the right operand. This routine
  78604. ** Shifts all join operators from left to right for an entire FROM
  78605. ** clause.
  78606. **
  78607. ** Example: Suppose the join is like this:
  78608. **
  78609. ** A natural cross join B
  78610. **
  78611. ** The operator is "natural cross join". The A and B operands are stored
  78612. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  78613. ** operator with A. This routine shifts that operator over to B.
  78614. */
  78615. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  78616. if( p ){
  78617. int i;
  78618. assert( p->a || p->nSrc==0 );
  78619. for(i=p->nSrc-1; i>0; i--){
  78620. p->a[i].jointype = p->a[i-1].jointype;
  78621. }
  78622. p->a[0].jointype = 0;
  78623. }
  78624. }
  78625. /*
  78626. ** Begin a transaction
  78627. */
  78628. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  78629. sqlite3 *db;
  78630. Vdbe *v;
  78631. int i;
  78632. assert( pParse!=0 );
  78633. db = pParse->db;
  78634. assert( db!=0 );
  78635. /* if( db->aDb[0].pBt==0 ) return; */
  78636. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  78637. return;
  78638. }
  78639. v = sqlite3GetVdbe(pParse);
  78640. if( !v ) return;
  78641. if( type!=TK_DEFERRED ){
  78642. for(i=0; i<db->nDb; i++){
  78643. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  78644. sqlite3VdbeUsesBtree(v, i);
  78645. }
  78646. }
  78647. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  78648. }
  78649. /*
  78650. ** Commit a transaction
  78651. */
  78652. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  78653. Vdbe *v;
  78654. assert( pParse!=0 );
  78655. assert( pParse->db!=0 );
  78656. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  78657. return;
  78658. }
  78659. v = sqlite3GetVdbe(pParse);
  78660. if( v ){
  78661. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  78662. }
  78663. }
  78664. /*
  78665. ** Rollback a transaction
  78666. */
  78667. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  78668. Vdbe *v;
  78669. assert( pParse!=0 );
  78670. assert( pParse->db!=0 );
  78671. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  78672. return;
  78673. }
  78674. v = sqlite3GetVdbe(pParse);
  78675. if( v ){
  78676. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  78677. }
  78678. }
  78679. /*
  78680. ** This function is called by the parser when it parses a command to create,
  78681. ** release or rollback an SQL savepoint.
  78682. */
  78683. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  78684. char *zName = sqlite3NameFromToken(pParse->db, pName);
  78685. if( zName ){
  78686. Vdbe *v = sqlite3GetVdbe(pParse);
  78687. #ifndef SQLITE_OMIT_AUTHORIZATION
  78688. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  78689. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  78690. #endif
  78691. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  78692. sqlite3DbFree(pParse->db, zName);
  78693. return;
  78694. }
  78695. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  78696. }
  78697. }
  78698. /*
  78699. ** Make sure the TEMP database is open and available for use. Return
  78700. ** the number of errors. Leave any error messages in the pParse structure.
  78701. */
  78702. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  78703. sqlite3 *db = pParse->db;
  78704. if( db->aDb[1].pBt==0 && !pParse->explain ){
  78705. int rc;
  78706. Btree *pBt;
  78707. static const int flags =
  78708. SQLITE_OPEN_READWRITE |
  78709. SQLITE_OPEN_CREATE |
  78710. SQLITE_OPEN_EXCLUSIVE |
  78711. SQLITE_OPEN_DELETEONCLOSE |
  78712. SQLITE_OPEN_TEMP_DB;
  78713. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  78714. if( rc!=SQLITE_OK ){
  78715. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  78716. "file for storing temporary tables");
  78717. pParse->rc = rc;
  78718. return 1;
  78719. }
  78720. db->aDb[1].pBt = pBt;
  78721. assert( db->aDb[1].pSchema );
  78722. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  78723. db->mallocFailed = 1;
  78724. return 1;
  78725. }
  78726. }
  78727. return 0;
  78728. }
  78729. /*
  78730. ** Generate VDBE code that will verify the schema cookie and start
  78731. ** a read-transaction for all named database files.
  78732. **
  78733. ** It is important that all schema cookies be verified and all
  78734. ** read transactions be started before anything else happens in
  78735. ** the VDBE program. But this routine can be called after much other
  78736. ** code has been generated. So here is what we do:
  78737. **
  78738. ** The first time this routine is called, we code an OP_Goto that
  78739. ** will jump to a subroutine at the end of the program. Then we
  78740. ** record every database that needs its schema verified in the
  78741. ** pParse->cookieMask field. Later, after all other code has been
  78742. ** generated, the subroutine that does the cookie verifications and
  78743. ** starts the transactions will be coded and the OP_Goto P2 value
  78744. ** will be made to point to that subroutine. The generation of the
  78745. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  78746. **
  78747. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  78748. ** schema on any databases. This can be used to position the OP_Goto
  78749. ** early in the code, before we know if any database tables will be used.
  78750. */
  78751. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  78752. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78753. #ifndef SQLITE_OMIT_TRIGGER
  78754. if( pToplevel!=pParse ){
  78755. /* This branch is taken if a trigger is currently being coded. In this
  78756. ** case, set cookieGoto to a non-zero value to show that this function
  78757. ** has been called. This is used by the sqlite3ExprCodeConstants()
  78758. ** function. */
  78759. pParse->cookieGoto = -1;
  78760. }
  78761. #endif
  78762. if( pToplevel->cookieGoto==0 ){
  78763. Vdbe *v = sqlite3GetVdbe(pToplevel);
  78764. if( v==0 ) return; /* This only happens if there was a prior error */
  78765. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  78766. }
  78767. if( iDb>=0 ){
  78768. sqlite3 *db = pToplevel->db;
  78769. yDbMask mask;
  78770. assert( iDb<db->nDb );
  78771. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  78772. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  78773. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  78774. mask = ((yDbMask)1)<<iDb;
  78775. if( (pToplevel->cookieMask & mask)==0 ){
  78776. pToplevel->cookieMask |= mask;
  78777. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  78778. if( !OMIT_TEMPDB && iDb==1 ){
  78779. sqlite3OpenTempDatabase(pToplevel);
  78780. }
  78781. }
  78782. }
  78783. }
  78784. /*
  78785. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  78786. ** attached database. Otherwise, invoke it for the database named zDb only.
  78787. */
  78788. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  78789. sqlite3 *db = pParse->db;
  78790. int i;
  78791. for(i=0; i<db->nDb; i++){
  78792. Db *pDb = &db->aDb[i];
  78793. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  78794. sqlite3CodeVerifySchema(pParse, i);
  78795. }
  78796. }
  78797. }
  78798. /*
  78799. ** Generate VDBE code that prepares for doing an operation that
  78800. ** might change the database.
  78801. **
  78802. ** This routine starts a new transaction if we are not already within
  78803. ** a transaction. If we are already within a transaction, then a checkpoint
  78804. ** is set if the setStatement parameter is true. A checkpoint should
  78805. ** be set for operations that might fail (due to a constraint) part of
  78806. ** the way through and which will need to undo some writes without having to
  78807. ** rollback the whole transaction. For operations where all constraints
  78808. ** can be checked before any changes are made to the database, it is never
  78809. ** necessary to undo a write and the checkpoint should not be set.
  78810. */
  78811. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  78812. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78813. sqlite3CodeVerifySchema(pParse, iDb);
  78814. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  78815. pToplevel->isMultiWrite |= setStatement;
  78816. }
  78817. /*
  78818. ** Indicate that the statement currently under construction might write
  78819. ** more than one entry (example: deleting one row then inserting another,
  78820. ** inserting multiple rows in a table, or inserting a row and index entries.)
  78821. ** If an abort occurs after some of these writes have completed, then it will
  78822. ** be necessary to undo the completed writes.
  78823. */
  78824. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  78825. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78826. pToplevel->isMultiWrite = 1;
  78827. }
  78828. /*
  78829. ** The code generator calls this routine if is discovers that it is
  78830. ** possible to abort a statement prior to completion. In order to
  78831. ** perform this abort without corrupting the database, we need to make
  78832. ** sure that the statement is protected by a statement transaction.
  78833. **
  78834. ** Technically, we only need to set the mayAbort flag if the
  78835. ** isMultiWrite flag was previously set. There is a time dependency
  78836. ** such that the abort must occur after the multiwrite. This makes
  78837. ** some statements involving the REPLACE conflict resolution algorithm
  78838. ** go a little faster. But taking advantage of this time dependency
  78839. ** makes it more difficult to prove that the code is correct (in
  78840. ** particular, it prevents us from writing an effective
  78841. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  78842. ** to take the safe route and skip the optimization.
  78843. */
  78844. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  78845. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78846. pToplevel->mayAbort = 1;
  78847. }
  78848. /*
  78849. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  78850. ** error. The onError parameter determines which (if any) of the statement
  78851. ** and/or current transaction is rolled back.
  78852. */
  78853. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
  78854. Vdbe *v = sqlite3GetVdbe(pParse);
  78855. if( onError==OE_Abort ){
  78856. sqlite3MayAbort(pParse);
  78857. }
  78858. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
  78859. }
  78860. /*
  78861. ** Check to see if pIndex uses the collating sequence pColl. Return
  78862. ** true if it does and false if it does not.
  78863. */
  78864. #ifndef SQLITE_OMIT_REINDEX
  78865. static int collationMatch(const char *zColl, Index *pIndex){
  78866. int i;
  78867. assert( zColl!=0 );
  78868. for(i=0; i<pIndex->nColumn; i++){
  78869. const char *z = pIndex->azColl[i];
  78870. assert( z!=0 );
  78871. if( 0==sqlite3StrICmp(z, zColl) ){
  78872. return 1;
  78873. }
  78874. }
  78875. return 0;
  78876. }
  78877. #endif
  78878. /*
  78879. ** Recompute all indices of pTab that use the collating sequence pColl.
  78880. ** If pColl==0 then recompute all indices of pTab.
  78881. */
  78882. #ifndef SQLITE_OMIT_REINDEX
  78883. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  78884. Index *pIndex; /* An index associated with pTab */
  78885. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  78886. if( zColl==0 || collationMatch(zColl, pIndex) ){
  78887. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78888. sqlite3BeginWriteOperation(pParse, 0, iDb);
  78889. sqlite3RefillIndex(pParse, pIndex, -1);
  78890. }
  78891. }
  78892. }
  78893. #endif
  78894. /*
  78895. ** Recompute all indices of all tables in all databases where the
  78896. ** indices use the collating sequence pColl. If pColl==0 then recompute
  78897. ** all indices everywhere.
  78898. */
  78899. #ifndef SQLITE_OMIT_REINDEX
  78900. static void reindexDatabases(Parse *pParse, char const *zColl){
  78901. Db *pDb; /* A single database */
  78902. int iDb; /* The database index number */
  78903. sqlite3 *db = pParse->db; /* The database connection */
  78904. HashElem *k; /* For looping over tables in pDb */
  78905. Table *pTab; /* A table in the database */
  78906. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  78907. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  78908. assert( pDb!=0 );
  78909. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  78910. pTab = (Table*)sqliteHashData(k);
  78911. reindexTable(pParse, pTab, zColl);
  78912. }
  78913. }
  78914. }
  78915. #endif
  78916. /*
  78917. ** Generate code for the REINDEX command.
  78918. **
  78919. ** REINDEX -- 1
  78920. ** REINDEX <collation> -- 2
  78921. ** REINDEX ?<database>.?<tablename> -- 3
  78922. ** REINDEX ?<database>.?<indexname> -- 4
  78923. **
  78924. ** Form 1 causes all indices in all attached databases to be rebuilt.
  78925. ** Form 2 rebuilds all indices in all databases that use the named
  78926. ** collating function. Forms 3 and 4 rebuild the named index or all
  78927. ** indices associated with the named table.
  78928. */
  78929. #ifndef SQLITE_OMIT_REINDEX
  78930. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  78931. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  78932. char *z; /* Name of a table or index */
  78933. const char *zDb; /* Name of the database */
  78934. Table *pTab; /* A table in the database */
  78935. Index *pIndex; /* An index associated with pTab */
  78936. int iDb; /* The database index number */
  78937. sqlite3 *db = pParse->db; /* The database connection */
  78938. Token *pObjName; /* Name of the table or index to be reindexed */
  78939. /* Read the database schema. If an error occurs, leave an error message
  78940. ** and code in pParse and return NULL. */
  78941. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  78942. return;
  78943. }
  78944. if( pName1==0 ){
  78945. reindexDatabases(pParse, 0);
  78946. return;
  78947. }else if( NEVER(pName2==0) || pName2->z==0 ){
  78948. char *zColl;
  78949. assert( pName1->z );
  78950. zColl = sqlite3NameFromToken(pParse->db, pName1);
  78951. if( !zColl ) return;
  78952. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  78953. if( pColl ){
  78954. reindexDatabases(pParse, zColl);
  78955. sqlite3DbFree(db, zColl);
  78956. return;
  78957. }
  78958. sqlite3DbFree(db, zColl);
  78959. }
  78960. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  78961. if( iDb<0 ) return;
  78962. z = sqlite3NameFromToken(db, pObjName);
  78963. if( z==0 ) return;
  78964. zDb = db->aDb[iDb].zName;
  78965. pTab = sqlite3FindTable(db, z, zDb);
  78966. if( pTab ){
  78967. reindexTable(pParse, pTab, 0);
  78968. sqlite3DbFree(db, z);
  78969. return;
  78970. }
  78971. pIndex = sqlite3FindIndex(db, z, zDb);
  78972. sqlite3DbFree(db, z);
  78973. if( pIndex ){
  78974. sqlite3BeginWriteOperation(pParse, 0, iDb);
  78975. sqlite3RefillIndex(pParse, pIndex, -1);
  78976. return;
  78977. }
  78978. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  78979. }
  78980. #endif
  78981. /*
  78982. ** Return a dynamicly allocated KeyInfo structure that can be used
  78983. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  78984. **
  78985. ** If successful, a pointer to the new structure is returned. In this case
  78986. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  78987. ** pointer. If an error occurs (out of memory or missing collation
  78988. ** sequence), NULL is returned and the state of pParse updated to reflect
  78989. ** the error.
  78990. */
  78991. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  78992. int i;
  78993. int nCol = pIdx->nColumn;
  78994. int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  78995. sqlite3 *db = pParse->db;
  78996. KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  78997. if( pKey ){
  78998. pKey->db = pParse->db;
  78999. pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  79000. assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  79001. for(i=0; i<nCol; i++){
  79002. char *zColl = pIdx->azColl[i];
  79003. assert( zColl );
  79004. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  79005. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  79006. }
  79007. pKey->nField = (u16)nCol;
  79008. }
  79009. if( pParse->nErr ){
  79010. sqlite3DbFree(db, pKey);
  79011. pKey = 0;
  79012. }
  79013. return pKey;
  79014. }
  79015. /************** End of build.c ***********************************************/
  79016. /************** Begin file callback.c ****************************************/
  79017. /*
  79018. ** 2005 May 23
  79019. **
  79020. ** The author disclaims copyright to this source code. In place of
  79021. ** a legal notice, here is a blessing:
  79022. **
  79023. ** May you do good and not evil.
  79024. ** May you find forgiveness for yourself and forgive others.
  79025. ** May you share freely, never taking more than you give.
  79026. **
  79027. *************************************************************************
  79028. **
  79029. ** This file contains functions used to access the internal hash tables
  79030. ** of user defined functions and collation sequences.
  79031. */
  79032. /*
  79033. ** Invoke the 'collation needed' callback to request a collation sequence
  79034. ** in the encoding enc of name zName, length nName.
  79035. */
  79036. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  79037. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  79038. if( db->xCollNeeded ){
  79039. char *zExternal = sqlite3DbStrDup(db, zName);
  79040. if( !zExternal ) return;
  79041. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  79042. sqlite3DbFree(db, zExternal);
  79043. }
  79044. #ifndef SQLITE_OMIT_UTF16
  79045. if( db->xCollNeeded16 ){
  79046. char const *zExternal;
  79047. sqlite3_value *pTmp = sqlite3ValueNew(db);
  79048. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  79049. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  79050. if( zExternal ){
  79051. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  79052. }
  79053. sqlite3ValueFree(pTmp);
  79054. }
  79055. #endif
  79056. }
  79057. /*
  79058. ** This routine is called if the collation factory fails to deliver a
  79059. ** collation function in the best encoding but there may be other versions
  79060. ** of this collation function (for other text encodings) available. Use one
  79061. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  79062. ** possible.
  79063. */
  79064. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  79065. CollSeq *pColl2;
  79066. char *z = pColl->zName;
  79067. int i;
  79068. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  79069. for(i=0; i<3; i++){
  79070. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  79071. if( pColl2->xCmp!=0 ){
  79072. memcpy(pColl, pColl2, sizeof(CollSeq));
  79073. pColl->xDel = 0; /* Do not copy the destructor */
  79074. return SQLITE_OK;
  79075. }
  79076. }
  79077. return SQLITE_ERROR;
  79078. }
  79079. /*
  79080. ** This function is responsible for invoking the collation factory callback
  79081. ** or substituting a collation sequence of a different encoding when the
  79082. ** requested collation sequence is not available in the desired encoding.
  79083. **
  79084. ** If it is not NULL, then pColl must point to the database native encoding
  79085. ** collation sequence with name zName, length nName.
  79086. **
  79087. ** The return value is either the collation sequence to be used in database
  79088. ** db for collation type name zName, length nName, or NULL, if no collation
  79089. ** sequence can be found. If no collation is found, leave an error message.
  79090. **
  79091. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  79092. */
  79093. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  79094. Parse *pParse, /* Parsing context */
  79095. u8 enc, /* The desired encoding for the collating sequence */
  79096. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  79097. const char *zName /* Collating sequence name */
  79098. ){
  79099. CollSeq *p;
  79100. sqlite3 *db = pParse->db;
  79101. p = pColl;
  79102. if( !p ){
  79103. p = sqlite3FindCollSeq(db, enc, zName, 0);
  79104. }
  79105. if( !p || !p->xCmp ){
  79106. /* No collation sequence of this type for this encoding is registered.
  79107. ** Call the collation factory to see if it can supply us with one.
  79108. */
  79109. callCollNeeded(db, enc, zName);
  79110. p = sqlite3FindCollSeq(db, enc, zName, 0);
  79111. }
  79112. if( p && !p->xCmp && synthCollSeq(db, p) ){
  79113. p = 0;
  79114. }
  79115. assert( !p || p->xCmp );
  79116. if( p==0 ){
  79117. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  79118. }
  79119. return p;
  79120. }
  79121. /*
  79122. ** This routine is called on a collation sequence before it is used to
  79123. ** check that it is defined. An undefined collation sequence exists when
  79124. ** a database is loaded that contains references to collation sequences
  79125. ** that have not been defined by sqlite3_create_collation() etc.
  79126. **
  79127. ** If required, this routine calls the 'collation needed' callback to
  79128. ** request a definition of the collating sequence. If this doesn't work,
  79129. ** an equivalent collating sequence that uses a text encoding different
  79130. ** from the main database is substituted, if one is available.
  79131. */
  79132. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  79133. if( pColl ){
  79134. const char *zName = pColl->zName;
  79135. sqlite3 *db = pParse->db;
  79136. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  79137. if( !p ){
  79138. return SQLITE_ERROR;
  79139. }
  79140. assert( p==pColl );
  79141. }
  79142. return SQLITE_OK;
  79143. }
  79144. /*
  79145. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  79146. ** specified by zName and nName is not found and parameter 'create' is
  79147. ** true, then create a new entry. Otherwise return NULL.
  79148. **
  79149. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  79150. ** array of three CollSeq structures. The first is the collation sequence
  79151. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  79152. **
  79153. ** Stored immediately after the three collation sequences is a copy of
  79154. ** the collation sequence name. A pointer to this string is stored in
  79155. ** each collation sequence structure.
  79156. */
  79157. static CollSeq *findCollSeqEntry(
  79158. sqlite3 *db, /* Database connection */
  79159. const char *zName, /* Name of the collating sequence */
  79160. int create /* Create a new entry if true */
  79161. ){
  79162. CollSeq *pColl;
  79163. int nName = sqlite3Strlen30(zName);
  79164. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  79165. if( 0==pColl && create ){
  79166. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  79167. if( pColl ){
  79168. CollSeq *pDel = 0;
  79169. pColl[0].zName = (char*)&pColl[3];
  79170. pColl[0].enc = SQLITE_UTF8;
  79171. pColl[1].zName = (char*)&pColl[3];
  79172. pColl[1].enc = SQLITE_UTF16LE;
  79173. pColl[2].zName = (char*)&pColl[3];
  79174. pColl[2].enc = SQLITE_UTF16BE;
  79175. memcpy(pColl[0].zName, zName, nName);
  79176. pColl[0].zName[nName] = 0;
  79177. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  79178. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  79179. ** return the pColl pointer to be deleted (because it wasn't added
  79180. ** to the hash table).
  79181. */
  79182. assert( pDel==0 || pDel==pColl );
  79183. if( pDel!=0 ){
  79184. db->mallocFailed = 1;
  79185. sqlite3DbFree(db, pDel);
  79186. pColl = 0;
  79187. }
  79188. }
  79189. }
  79190. return pColl;
  79191. }
  79192. /*
  79193. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  79194. ** Return the CollSeq* pointer for the collation sequence named zName
  79195. ** for the encoding 'enc' from the database 'db'.
  79196. **
  79197. ** If the entry specified is not found and 'create' is true, then create a
  79198. ** new entry. Otherwise return NULL.
  79199. **
  79200. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  79201. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  79202. ** if necessary and generates an error message if the collating sequence
  79203. ** cannot be found.
  79204. **
  79205. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  79206. */
  79207. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  79208. sqlite3 *db,
  79209. u8 enc,
  79210. const char *zName,
  79211. int create
  79212. ){
  79213. CollSeq *pColl;
  79214. if( zName ){
  79215. pColl = findCollSeqEntry(db, zName, create);
  79216. }else{
  79217. pColl = db->pDfltColl;
  79218. }
  79219. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  79220. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  79221. if( pColl ) pColl += enc-1;
  79222. return pColl;
  79223. }
  79224. /* During the search for the best function definition, this procedure
  79225. ** is called to test how well the function passed as the first argument
  79226. ** matches the request for a function with nArg arguments in a system
  79227. ** that uses encoding enc. The value returned indicates how well the
  79228. ** request is matched. A higher value indicates a better match.
  79229. **
  79230. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  79231. ** is also -1. In other words, we are searching for a function that
  79232. ** takes a variable number of arguments.
  79233. **
  79234. ** If nArg is -2 that means that we are searching for any function
  79235. ** regardless of the number of arguments it uses, so return a positive
  79236. ** match score for any
  79237. **
  79238. ** The returned value is always between 0 and 6, as follows:
  79239. **
  79240. ** 0: Not a match.
  79241. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  79242. ** 2: UTF16 byte order change required and function takes any number of args.
  79243. ** 3: encoding matches and function takes any number of arguments
  79244. ** 4: UTF8/16 conversion required - argument count matches exactly
  79245. ** 5: UTF16 byte order conversion required - argument count matches exactly
  79246. ** 6: Perfect match: encoding and argument count match exactly.
  79247. **
  79248. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  79249. ** a perfect match and any function with both xStep and xFunc NULL is
  79250. ** a non-match.
  79251. */
  79252. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  79253. static int matchQuality(
  79254. FuncDef *p, /* The function we are evaluating for match quality */
  79255. int nArg, /* Desired number of arguments. (-1)==any */
  79256. u8 enc /* Desired text encoding */
  79257. ){
  79258. int match;
  79259. /* nArg of -2 is a special case */
  79260. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  79261. /* Wrong number of arguments means "no match" */
  79262. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  79263. /* Give a better score to a function with a specific number of arguments
  79264. ** than to function that accepts any number of arguments. */
  79265. if( p->nArg==nArg ){
  79266. match = 4;
  79267. }else{
  79268. match = 1;
  79269. }
  79270. /* Bonus points if the text encoding matches */
  79271. if( enc==p->iPrefEnc ){
  79272. match += 2; /* Exact encoding match */
  79273. }else if( (enc & p->iPrefEnc & 2)!=0 ){
  79274. match += 1; /* Both are UTF16, but with different byte orders */
  79275. }
  79276. return match;
  79277. }
  79278. /*
  79279. ** Search a FuncDefHash for a function with the given name. Return
  79280. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  79281. */
  79282. static FuncDef *functionSearch(
  79283. FuncDefHash *pHash, /* Hash table to search */
  79284. int h, /* Hash of the name */
  79285. const char *zFunc, /* Name of function */
  79286. int nFunc /* Number of bytes in zFunc */
  79287. ){
  79288. FuncDef *p;
  79289. for(p=pHash->a[h]; p; p=p->pHash){
  79290. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  79291. return p;
  79292. }
  79293. }
  79294. return 0;
  79295. }
  79296. /*
  79297. ** Insert a new FuncDef into a FuncDefHash hash table.
  79298. */
  79299. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  79300. FuncDefHash *pHash, /* The hash table into which to insert */
  79301. FuncDef *pDef /* The function definition to insert */
  79302. ){
  79303. FuncDef *pOther;
  79304. int nName = sqlite3Strlen30(pDef->zName);
  79305. u8 c1 = (u8)pDef->zName[0];
  79306. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  79307. pOther = functionSearch(pHash, h, pDef->zName, nName);
  79308. if( pOther ){
  79309. assert( pOther!=pDef && pOther->pNext!=pDef );
  79310. pDef->pNext = pOther->pNext;
  79311. pOther->pNext = pDef;
  79312. }else{
  79313. pDef->pNext = 0;
  79314. pDef->pHash = pHash->a[h];
  79315. pHash->a[h] = pDef;
  79316. }
  79317. }
  79318. /*
  79319. ** Locate a user function given a name, a number of arguments and a flag
  79320. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  79321. ** pointer to the FuncDef structure that defines that function, or return
  79322. ** NULL if the function does not exist.
  79323. **
  79324. ** If the createFlag argument is true, then a new (blank) FuncDef
  79325. ** structure is created and liked into the "db" structure if a
  79326. ** no matching function previously existed.
  79327. **
  79328. ** If nArg is -2, then the first valid function found is returned. A
  79329. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  79330. ** case is used to see if zName is a valid function name for some number
  79331. ** of arguments. If nArg is -2, then createFlag must be 0.
  79332. **
  79333. ** If createFlag is false, then a function with the required name and
  79334. ** number of arguments may be returned even if the eTextRep flag does not
  79335. ** match that requested.
  79336. */
  79337. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  79338. sqlite3 *db, /* An open database */
  79339. const char *zName, /* Name of the function. Not null-terminated */
  79340. int nName, /* Number of characters in the name */
  79341. int nArg, /* Number of arguments. -1 means any number */
  79342. u8 enc, /* Preferred text encoding */
  79343. u8 createFlag /* Create new entry if true and does not otherwise exist */
  79344. ){
  79345. FuncDef *p; /* Iterator variable */
  79346. FuncDef *pBest = 0; /* Best match found so far */
  79347. int bestScore = 0; /* Score of best match */
  79348. int h; /* Hash value */
  79349. assert( nArg>=(-2) );
  79350. assert( nArg>=(-1) || createFlag==0 );
  79351. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  79352. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  79353. /* First search for a match amongst the application-defined functions.
  79354. */
  79355. p = functionSearch(&db->aFunc, h, zName, nName);
  79356. while( p ){
  79357. int score = matchQuality(p, nArg, enc);
  79358. if( score>bestScore ){
  79359. pBest = p;
  79360. bestScore = score;
  79361. }
  79362. p = p->pNext;
  79363. }
  79364. /* If no match is found, search the built-in functions.
  79365. **
  79366. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  79367. ** functions even if a prior app-defined function was found. And give
  79368. ** priority to built-in functions.
  79369. **
  79370. ** Except, if createFlag is true, that means that we are trying to
  79371. ** install a new function. Whatever FuncDef structure is returned it will
  79372. ** have fields overwritten with new information appropriate for the
  79373. ** new function. But the FuncDefs for built-in functions are read-only.
  79374. ** So we must not search for built-ins when creating a new function.
  79375. */
  79376. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  79377. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  79378. bestScore = 0;
  79379. p = functionSearch(pHash, h, zName, nName);
  79380. while( p ){
  79381. int score = matchQuality(p, nArg, enc);
  79382. if( score>bestScore ){
  79383. pBest = p;
  79384. bestScore = score;
  79385. }
  79386. p = p->pNext;
  79387. }
  79388. }
  79389. /* If the createFlag parameter is true and the search did not reveal an
  79390. ** exact match for the name, number of arguments and encoding, then add a
  79391. ** new entry to the hash table and return it.
  79392. */
  79393. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  79394. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  79395. pBest->zName = (char *)&pBest[1];
  79396. pBest->nArg = (u16)nArg;
  79397. pBest->iPrefEnc = enc;
  79398. memcpy(pBest->zName, zName, nName);
  79399. pBest->zName[nName] = 0;
  79400. sqlite3FuncDefInsert(&db->aFunc, pBest);
  79401. }
  79402. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  79403. return pBest;
  79404. }
  79405. return 0;
  79406. }
  79407. /*
  79408. ** Free all resources held by the schema structure. The void* argument points
  79409. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  79410. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  79411. ** of the schema hash tables).
  79412. **
  79413. ** The Schema.cache_size variable is not cleared.
  79414. */
  79415. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  79416. Hash temp1;
  79417. Hash temp2;
  79418. HashElem *pElem;
  79419. Schema *pSchema = (Schema *)p;
  79420. temp1 = pSchema->tblHash;
  79421. temp2 = pSchema->trigHash;
  79422. sqlite3HashInit(&pSchema->trigHash);
  79423. sqlite3HashClear(&pSchema->idxHash);
  79424. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  79425. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  79426. }
  79427. sqlite3HashClear(&temp2);
  79428. sqlite3HashInit(&pSchema->tblHash);
  79429. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  79430. Table *pTab = sqliteHashData(pElem);
  79431. sqlite3DeleteTable(0, pTab);
  79432. }
  79433. sqlite3HashClear(&temp1);
  79434. sqlite3HashClear(&pSchema->fkeyHash);
  79435. pSchema->pSeqTab = 0;
  79436. if( pSchema->flags & DB_SchemaLoaded ){
  79437. pSchema->iGeneration++;
  79438. pSchema->flags &= ~DB_SchemaLoaded;
  79439. }
  79440. }
  79441. /*
  79442. ** Find and return the schema associated with a BTree. Create
  79443. ** a new one if necessary.
  79444. */
  79445. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  79446. Schema * p;
  79447. if( pBt ){
  79448. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  79449. }else{
  79450. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  79451. }
  79452. if( !p ){
  79453. db->mallocFailed = 1;
  79454. }else if ( 0==p->file_format ){
  79455. sqlite3HashInit(&p->tblHash);
  79456. sqlite3HashInit(&p->idxHash);
  79457. sqlite3HashInit(&p->trigHash);
  79458. sqlite3HashInit(&p->fkeyHash);
  79459. p->enc = SQLITE_UTF8;
  79460. }
  79461. return p;
  79462. }
  79463. /************** End of callback.c ********************************************/
  79464. /************** Begin file delete.c ******************************************/
  79465. /*
  79466. ** 2001 September 15
  79467. **
  79468. ** The author disclaims copyright to this source code. In place of
  79469. ** a legal notice, here is a blessing:
  79470. **
  79471. ** May you do good and not evil.
  79472. ** May you find forgiveness for yourself and forgive others.
  79473. ** May you share freely, never taking more than you give.
  79474. **
  79475. *************************************************************************
  79476. ** This file contains C code routines that are called by the parser
  79477. ** in order to generate code for DELETE FROM statements.
  79478. */
  79479. /*
  79480. ** While a SrcList can in general represent multiple tables and subqueries
  79481. ** (as in the FROM clause of a SELECT statement) in this case it contains
  79482. ** the name of a single table, as one might find in an INSERT, DELETE,
  79483. ** or UPDATE statement. Look up that table in the symbol table and
  79484. ** return a pointer. Set an error message and return NULL if the table
  79485. ** name is not found or if any other error occurs.
  79486. **
  79487. ** The following fields are initialized appropriate in pSrc:
  79488. **
  79489. ** pSrc->a[0].pTab Pointer to the Table object
  79490. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  79491. **
  79492. */
  79493. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  79494. struct SrcList_item *pItem = pSrc->a;
  79495. Table *pTab;
  79496. assert( pItem && pSrc->nSrc==1 );
  79497. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  79498. sqlite3DeleteTable(pParse->db, pItem->pTab);
  79499. pItem->pTab = pTab;
  79500. if( pTab ){
  79501. pTab->nRef++;
  79502. }
  79503. if( sqlite3IndexedByLookup(pParse, pItem) ){
  79504. pTab = 0;
  79505. }
  79506. return pTab;
  79507. }
  79508. /*
  79509. ** Check to make sure the given table is writable. If it is not
  79510. ** writable, generate an error message and return 1. If it is
  79511. ** writable return 0;
  79512. */
  79513. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  79514. /* A table is not writable under the following circumstances:
  79515. **
  79516. ** 1) It is a virtual table and no implementation of the xUpdate method
  79517. ** has been provided, or
  79518. ** 2) It is a system table (i.e. sqlite_master), this call is not
  79519. ** part of a nested parse and writable_schema pragma has not
  79520. ** been specified.
  79521. **
  79522. ** In either case leave an error message in pParse and return non-zero.
  79523. */
  79524. if( ( IsVirtual(pTab)
  79525. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  79526. || ( (pTab->tabFlags & TF_Readonly)!=0
  79527. && (pParse->db->flags & SQLITE_WriteSchema)==0
  79528. && pParse->nested==0 )
  79529. ){
  79530. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  79531. return 1;
  79532. }
  79533. #ifndef SQLITE_OMIT_VIEW
  79534. if( !viewOk && pTab->pSelect ){
  79535. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  79536. return 1;
  79537. }
  79538. #endif
  79539. return 0;
  79540. }
  79541. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  79542. /*
  79543. ** Evaluate a view and store its result in an ephemeral table. The
  79544. ** pWhere argument is an optional WHERE clause that restricts the
  79545. ** set of rows in the view that are to be added to the ephemeral table.
  79546. */
  79547. SQLITE_PRIVATE void sqlite3MaterializeView(
  79548. Parse *pParse, /* Parsing context */
  79549. Table *pView, /* View definition */
  79550. Expr *pWhere, /* Optional WHERE clause to be added */
  79551. int iCur /* Cursor number for ephemerial table */
  79552. ){
  79553. SelectDest dest;
  79554. Select *pDup;
  79555. sqlite3 *db = pParse->db;
  79556. pDup = sqlite3SelectDup(db, pView->pSelect, 0);
  79557. if( pWhere ){
  79558. SrcList *pFrom;
  79559. pWhere = sqlite3ExprDup(db, pWhere, 0);
  79560. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  79561. if( pFrom ){
  79562. assert( pFrom->nSrc==1 );
  79563. pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
  79564. pFrom->a[0].pSelect = pDup;
  79565. assert( pFrom->a[0].pOn==0 );
  79566. assert( pFrom->a[0].pUsing==0 );
  79567. }else{
  79568. sqlite3SelectDelete(db, pDup);
  79569. }
  79570. pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  79571. if( pDup ) pDup->selFlags |= SF_Materialize;
  79572. }
  79573. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  79574. sqlite3Select(pParse, pDup, &dest);
  79575. sqlite3SelectDelete(db, pDup);
  79576. }
  79577. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  79578. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  79579. /*
  79580. ** Generate an expression tree to implement the WHERE, ORDER BY,
  79581. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  79582. **
  79583. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  79584. ** \__________________________/
  79585. ** pLimitWhere (pInClause)
  79586. */
  79587. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  79588. Parse *pParse, /* The parser context */
  79589. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  79590. Expr *pWhere, /* The WHERE clause. May be null */
  79591. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  79592. Expr *pLimit, /* The LIMIT clause. May be null */
  79593. Expr *pOffset, /* The OFFSET clause. May be null */
  79594. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  79595. ){
  79596. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  79597. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  79598. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  79599. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  79600. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  79601. Select *pSelect = NULL; /* Complete SELECT tree */
  79602. /* Check that there isn't an ORDER BY without a LIMIT clause.
  79603. */
  79604. if( pOrderBy && (pLimit == 0) ) {
  79605. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  79606. goto limit_where_cleanup_2;
  79607. }
  79608. /* We only need to generate a select expression if there
  79609. ** is a limit/offset term to enforce.
  79610. */
  79611. if( pLimit == 0 ) {
  79612. /* if pLimit is null, pOffset will always be null as well. */
  79613. assert( pOffset == 0 );
  79614. return pWhere;
  79615. }
  79616. /* Generate a select expression tree to enforce the limit/offset
  79617. ** term for the DELETE or UPDATE statement. For example:
  79618. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  79619. ** becomes:
  79620. ** DELETE FROM table_a WHERE rowid IN (
  79621. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  79622. ** );
  79623. */
  79624. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  79625. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  79626. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  79627. if( pEList == 0 ) goto limit_where_cleanup_2;
  79628. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  79629. ** and the SELECT subtree. */
  79630. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  79631. if( pSelectSrc == 0 ) {
  79632. sqlite3ExprListDelete(pParse->db, pEList);
  79633. goto limit_where_cleanup_2;
  79634. }
  79635. /* generate the SELECT expression tree. */
  79636. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  79637. pOrderBy,0,pLimit,pOffset);
  79638. if( pSelect == 0 ) return 0;
  79639. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  79640. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  79641. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  79642. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  79643. if( pInClause == 0 ) goto limit_where_cleanup_1;
  79644. pInClause->x.pSelect = pSelect;
  79645. pInClause->flags |= EP_xIsSelect;
  79646. sqlite3ExprSetHeight(pParse, pInClause);
  79647. return pInClause;
  79648. /* something went wrong. clean up anything allocated. */
  79649. limit_where_cleanup_1:
  79650. sqlite3SelectDelete(pParse->db, pSelect);
  79651. return 0;
  79652. limit_where_cleanup_2:
  79653. sqlite3ExprDelete(pParse->db, pWhere);
  79654. sqlite3ExprListDelete(pParse->db, pOrderBy);
  79655. sqlite3ExprDelete(pParse->db, pLimit);
  79656. sqlite3ExprDelete(pParse->db, pOffset);
  79657. return 0;
  79658. }
  79659. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  79660. /*
  79661. ** Generate code for a DELETE FROM statement.
  79662. **
  79663. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  79664. ** \________/ \________________/
  79665. ** pTabList pWhere
  79666. */
  79667. SQLITE_PRIVATE void sqlite3DeleteFrom(
  79668. Parse *pParse, /* The parser context */
  79669. SrcList *pTabList, /* The table from which we should delete things */
  79670. Expr *pWhere /* The WHERE clause. May be null */
  79671. ){
  79672. Vdbe *v; /* The virtual database engine */
  79673. Table *pTab; /* The table from which records will be deleted */
  79674. const char *zDb; /* Name of database holding pTab */
  79675. int end, addr = 0; /* A couple addresses of generated code */
  79676. int i; /* Loop counter */
  79677. WhereInfo *pWInfo; /* Information about the WHERE clause */
  79678. Index *pIdx; /* For looping over indices of the table */
  79679. int iCur; /* VDBE Cursor number for pTab */
  79680. sqlite3 *db; /* Main database structure */
  79681. AuthContext sContext; /* Authorization context */
  79682. NameContext sNC; /* Name context to resolve expressions in */
  79683. int iDb; /* Database number */
  79684. int memCnt = -1; /* Memory cell used for change counting */
  79685. int rcauth; /* Value returned by authorization callback */
  79686. #ifndef SQLITE_OMIT_TRIGGER
  79687. int isView; /* True if attempting to delete from a view */
  79688. Trigger *pTrigger; /* List of table triggers, if required */
  79689. #endif
  79690. memset(&sContext, 0, sizeof(sContext));
  79691. db = pParse->db;
  79692. if( pParse->nErr || db->mallocFailed ){
  79693. goto delete_from_cleanup;
  79694. }
  79695. assert( pTabList->nSrc==1 );
  79696. /* Locate the table which we want to delete. This table has to be
  79697. ** put in an SrcList structure because some of the subroutines we
  79698. ** will be calling are designed to work with multiple tables and expect
  79699. ** an SrcList* parameter instead of just a Table* parameter.
  79700. */
  79701. pTab = sqlite3SrcListLookup(pParse, pTabList);
  79702. if( pTab==0 ) goto delete_from_cleanup;
  79703. /* Figure out if we have any triggers and if the table being
  79704. ** deleted from is a view
  79705. */
  79706. #ifndef SQLITE_OMIT_TRIGGER
  79707. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  79708. isView = pTab->pSelect!=0;
  79709. #else
  79710. # define pTrigger 0
  79711. # define isView 0
  79712. #endif
  79713. #ifdef SQLITE_OMIT_VIEW
  79714. # undef isView
  79715. # define isView 0
  79716. #endif
  79717. /* If pTab is really a view, make sure it has been initialized.
  79718. */
  79719. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  79720. goto delete_from_cleanup;
  79721. }
  79722. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  79723. goto delete_from_cleanup;
  79724. }
  79725. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  79726. assert( iDb<db->nDb );
  79727. zDb = db->aDb[iDb].zName;
  79728. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  79729. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  79730. if( rcauth==SQLITE_DENY ){
  79731. goto delete_from_cleanup;
  79732. }
  79733. assert(!isView || pTrigger);
  79734. /* Assign cursor number to the table and all its indices.
  79735. */
  79736. assert( pTabList->nSrc==1 );
  79737. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  79738. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  79739. pParse->nTab++;
  79740. }
  79741. /* Start the view context
  79742. */
  79743. if( isView ){
  79744. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  79745. }
  79746. /* Begin generating code.
  79747. */
  79748. v = sqlite3GetVdbe(pParse);
  79749. if( v==0 ){
  79750. goto delete_from_cleanup;
  79751. }
  79752. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  79753. sqlite3BeginWriteOperation(pParse, 1, iDb);
  79754. /* If we are trying to delete from a view, realize that view into
  79755. ** a ephemeral table.
  79756. */
  79757. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  79758. if( isView ){
  79759. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  79760. }
  79761. #endif
  79762. /* Resolve the column names in the WHERE clause.
  79763. */
  79764. memset(&sNC, 0, sizeof(sNC));
  79765. sNC.pParse = pParse;
  79766. sNC.pSrcList = pTabList;
  79767. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  79768. goto delete_from_cleanup;
  79769. }
  79770. /* Initialize the counter of the number of rows deleted, if
  79771. ** we are counting rows.
  79772. */
  79773. if( db->flags & SQLITE_CountRows ){
  79774. memCnt = ++pParse->nMem;
  79775. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  79776. }
  79777. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  79778. /* Special case: A DELETE without a WHERE clause deletes everything.
  79779. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  79780. ** this optimization caused the row change count (the value returned by
  79781. ** API function sqlite3_count_changes) to be set incorrectly. */
  79782. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  79783. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  79784. ){
  79785. assert( !isView );
  79786. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  79787. pTab->zName, P4_STATIC);
  79788. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  79789. assert( pIdx->pSchema==pTab->pSchema );
  79790. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  79791. }
  79792. }else
  79793. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  79794. /* The usual case: There is a WHERE clause so we have to scan through
  79795. ** the table and pick which records to delete.
  79796. */
  79797. {
  79798. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  79799. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  79800. int regRowid; /* Actual register containing rowids */
  79801. /* Collect rowids of every row to be deleted.
  79802. */
  79803. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  79804. pWInfo = sqlite3WhereBegin(
  79805. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  79806. );
  79807. if( pWInfo==0 ) goto delete_from_cleanup;
  79808. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  79809. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  79810. if( db->flags & SQLITE_CountRows ){
  79811. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  79812. }
  79813. sqlite3WhereEnd(pWInfo);
  79814. /* Delete every item whose key was written to the list during the
  79815. ** database scan. We have to delete items after the scan is complete
  79816. ** because deleting an item can change the scan order. */
  79817. end = sqlite3VdbeMakeLabel(v);
  79818. /* Unless this is a view, open cursors for the table we are
  79819. ** deleting from and all its indices. If this is a view, then the
  79820. ** only effect this statement has is to fire the INSTEAD OF
  79821. ** triggers. */
  79822. if( !isView ){
  79823. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  79824. }
  79825. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  79826. /* Delete the row */
  79827. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79828. if( IsVirtual(pTab) ){
  79829. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  79830. sqlite3VtabMakeWritable(pParse, pTab);
  79831. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  79832. sqlite3VdbeChangeP5(v, OE_Abort);
  79833. sqlite3MayAbort(pParse);
  79834. }else
  79835. #endif
  79836. {
  79837. int count = (pParse->nested==0); /* True to count changes */
  79838. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  79839. }
  79840. /* End of the delete loop */
  79841. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  79842. sqlite3VdbeResolveLabel(v, end);
  79843. /* Close the cursors open on the table and its indexes. */
  79844. if( !isView && !IsVirtual(pTab) ){
  79845. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  79846. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  79847. }
  79848. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  79849. }
  79850. }
  79851. /* Update the sqlite_sequence table by storing the content of the
  79852. ** maximum rowid counter values recorded while inserting into
  79853. ** autoincrement tables.
  79854. */
  79855. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  79856. sqlite3AutoincrementEnd(pParse);
  79857. }
  79858. /* Return the number of rows that were deleted. If this routine is
  79859. ** generating code because of a call to sqlite3NestedParse(), do not
  79860. ** invoke the callback function.
  79861. */
  79862. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  79863. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  79864. sqlite3VdbeSetNumCols(v, 1);
  79865. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  79866. }
  79867. delete_from_cleanup:
  79868. sqlite3AuthContextPop(&sContext);
  79869. sqlite3SrcListDelete(db, pTabList);
  79870. sqlite3ExprDelete(db, pWhere);
  79871. return;
  79872. }
  79873. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  79874. ** thely may interfere with compilation of other functions in this file
  79875. ** (or in another file, if this file becomes part of the amalgamation). */
  79876. #ifdef isView
  79877. #undef isView
  79878. #endif
  79879. #ifdef pTrigger
  79880. #undef pTrigger
  79881. #endif
  79882. /*
  79883. ** This routine generates VDBE code that causes a single row of a
  79884. ** single table to be deleted.
  79885. **
  79886. ** The VDBE must be in a particular state when this routine is called.
  79887. ** These are the requirements:
  79888. **
  79889. ** 1. A read/write cursor pointing to pTab, the table containing the row
  79890. ** to be deleted, must be opened as cursor number $iCur.
  79891. **
  79892. ** 2. Read/write cursors for all indices of pTab must be open as
  79893. ** cursor number base+i for the i-th index.
  79894. **
  79895. ** 3. The record number of the row to be deleted must be stored in
  79896. ** memory cell iRowid.
  79897. **
  79898. ** This routine generates code to remove both the table record and all
  79899. ** index entries that point to that record.
  79900. */
  79901. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  79902. Parse *pParse, /* Parsing context */
  79903. Table *pTab, /* Table containing the row to be deleted */
  79904. int iCur, /* Cursor number for the table */
  79905. int iRowid, /* Memory cell that contains the rowid to delete */
  79906. int count, /* If non-zero, increment the row change counter */
  79907. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  79908. int onconf /* Default ON CONFLICT policy for triggers */
  79909. ){
  79910. Vdbe *v = pParse->pVdbe; /* Vdbe */
  79911. int iOld = 0; /* First register in OLD.* array */
  79912. int iLabel; /* Label resolved to end of generated code */
  79913. /* Vdbe is guaranteed to have been allocated by this stage. */
  79914. assert( v );
  79915. /* Seek cursor iCur to the row to delete. If this row no longer exists
  79916. ** (this can happen if a trigger program has already deleted it), do
  79917. ** not attempt to delete it or fire any DELETE triggers. */
  79918. iLabel = sqlite3VdbeMakeLabel(v);
  79919. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  79920. /* If there are any triggers to fire, allocate a range of registers to
  79921. ** use for the old.* references in the triggers. */
  79922. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  79923. u32 mask; /* Mask of OLD.* columns in use */
  79924. int iCol; /* Iterator used while populating OLD.* */
  79925. /* TODO: Could use temporary registers here. Also could attempt to
  79926. ** avoid copying the contents of the rowid register. */
  79927. mask = sqlite3TriggerColmask(
  79928. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  79929. );
  79930. mask |= sqlite3FkOldmask(pParse, pTab);
  79931. iOld = pParse->nMem+1;
  79932. pParse->nMem += (1 + pTab->nCol);
  79933. /* Populate the OLD.* pseudo-table register array. These values will be
  79934. ** used by any BEFORE and AFTER triggers that exist. */
  79935. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  79936. for(iCol=0; iCol<pTab->nCol; iCol++){
  79937. if( mask==0xffffffff || mask&(1<<iCol) ){
  79938. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  79939. }
  79940. }
  79941. /* Invoke BEFORE DELETE trigger programs. */
  79942. sqlite3CodeRowTrigger(pParse, pTrigger,
  79943. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  79944. );
  79945. /* Seek the cursor to the row to be deleted again. It may be that
  79946. ** the BEFORE triggers coded above have already removed the row
  79947. ** being deleted. Do not attempt to delete the row a second time, and
  79948. ** do not fire AFTER triggers. */
  79949. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  79950. /* Do FK processing. This call checks that any FK constraints that
  79951. ** refer to this table (i.e. constraints attached to other tables)
  79952. ** are not violated by deleting this row. */
  79953. sqlite3FkCheck(pParse, pTab, iOld, 0);
  79954. }
  79955. /* Delete the index and table entries. Skip this step if pTab is really
  79956. ** a view (in which case the only effect of the DELETE statement is to
  79957. ** fire the INSTEAD OF triggers). */
  79958. if( pTab->pSelect==0 ){
  79959. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  79960. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  79961. if( count ){
  79962. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  79963. }
  79964. }
  79965. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  79966. ** handle rows (possibly in other tables) that refer via a foreign key
  79967. ** to the row just deleted. */
  79968. sqlite3FkActions(pParse, pTab, 0, iOld);
  79969. /* Invoke AFTER DELETE trigger programs. */
  79970. sqlite3CodeRowTrigger(pParse, pTrigger,
  79971. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  79972. );
  79973. /* Jump here if the row had already been deleted before any BEFORE
  79974. ** trigger programs were invoked. Or if a trigger program throws a
  79975. ** RAISE(IGNORE) exception. */
  79976. sqlite3VdbeResolveLabel(v, iLabel);
  79977. }
  79978. /*
  79979. ** This routine generates VDBE code that causes the deletion of all
  79980. ** index entries associated with a single row of a single table.
  79981. **
  79982. ** The VDBE must be in a particular state when this routine is called.
  79983. ** These are the requirements:
  79984. **
  79985. ** 1. A read/write cursor pointing to pTab, the table containing the row
  79986. ** to be deleted, must be opened as cursor number "iCur".
  79987. **
  79988. ** 2. Read/write cursors for all indices of pTab must be open as
  79989. ** cursor number iCur+i for the i-th index.
  79990. **
  79991. ** 3. The "iCur" cursor must be pointing to the row that is to be
  79992. ** deleted.
  79993. */
  79994. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  79995. Parse *pParse, /* Parsing and code generating context */
  79996. Table *pTab, /* Table containing the row to be deleted */
  79997. int iCur, /* Cursor number for the table */
  79998. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  79999. ){
  80000. int i;
  80001. Index *pIdx;
  80002. int r1;
  80003. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  80004. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  80005. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
  80006. sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  80007. }
  80008. }
  80009. /*
  80010. ** Generate code that will assemble an index key and put it in register
  80011. ** regOut. The key with be for index pIdx which is an index on pTab.
  80012. ** iCur is the index of a cursor open on the pTab table and pointing to
  80013. ** the entry that needs indexing.
  80014. **
  80015. ** Return a register number which is the first in a block of
  80016. ** registers that holds the elements of the index key. The
  80017. ** block of registers has already been deallocated by the time
  80018. ** this routine returns.
  80019. */
  80020. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  80021. Parse *pParse, /* Parsing context */
  80022. Index *pIdx, /* The index for which to generate a key */
  80023. int iCur, /* Cursor number for the pIdx->pTable table */
  80024. int regOut, /* Write the new index key to this register */
  80025. int doMakeRec /* Run the OP_MakeRecord instruction if true */
  80026. ){
  80027. Vdbe *v = pParse->pVdbe;
  80028. int j;
  80029. Table *pTab = pIdx->pTable;
  80030. int regBase;
  80031. int nCol;
  80032. nCol = pIdx->nColumn;
  80033. regBase = sqlite3GetTempRange(pParse, nCol+1);
  80034. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  80035. for(j=0; j<nCol; j++){
  80036. int idx = pIdx->aiColumn[j];
  80037. if( idx==pTab->iPKey ){
  80038. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  80039. }else{
  80040. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  80041. sqlite3ColumnDefault(v, pTab, idx, -1);
  80042. }
  80043. }
  80044. if( doMakeRec ){
  80045. const char *zAff;
  80046. if( pTab->pSelect
  80047. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  80048. ){
  80049. zAff = 0;
  80050. }else{
  80051. zAff = sqlite3IndexAffinityStr(v, pIdx);
  80052. }
  80053. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  80054. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  80055. }
  80056. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  80057. return regBase;
  80058. }
  80059. /************** End of delete.c **********************************************/
  80060. /************** Begin file func.c ********************************************/
  80061. /*
  80062. ** 2002 February 23
  80063. **
  80064. ** The author disclaims copyright to this source code. In place of
  80065. ** a legal notice, here is a blessing:
  80066. **
  80067. ** May you do good and not evil.
  80068. ** May you find forgiveness for yourself and forgive others.
  80069. ** May you share freely, never taking more than you give.
  80070. **
  80071. *************************************************************************
  80072. ** This file contains the C functions that implement various SQL
  80073. ** functions of SQLite.
  80074. **
  80075. ** There is only one exported symbol in this file - the function
  80076. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  80077. ** All other code has file scope.
  80078. */
  80079. /* #include <stdlib.h> */
  80080. /* #include <assert.h> */
  80081. /*
  80082. ** Return the collating function associated with a function.
  80083. */
  80084. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  80085. return context->pColl;
  80086. }
  80087. /*
  80088. ** Indicate that the accumulator load should be skipped on this
  80089. ** iteration of the aggregate loop.
  80090. */
  80091. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  80092. context->skipFlag = 1;
  80093. }
  80094. /*
  80095. ** Implementation of the non-aggregate min() and max() functions
  80096. */
  80097. static void minmaxFunc(
  80098. sqlite3_context *context,
  80099. int argc,
  80100. sqlite3_value **argv
  80101. ){
  80102. int i;
  80103. int mask; /* 0 for min() or 0xffffffff for max() */
  80104. int iBest;
  80105. CollSeq *pColl;
  80106. assert( argc>1 );
  80107. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  80108. pColl = sqlite3GetFuncCollSeq(context);
  80109. assert( pColl );
  80110. assert( mask==-1 || mask==0 );
  80111. iBest = 0;
  80112. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  80113. for(i=1; i<argc; i++){
  80114. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  80115. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  80116. testcase( mask==0 );
  80117. iBest = i;
  80118. }
  80119. }
  80120. sqlite3_result_value(context, argv[iBest]);
  80121. }
  80122. /*
  80123. ** Return the type of the argument.
  80124. */
  80125. static void typeofFunc(
  80126. sqlite3_context *context,
  80127. int NotUsed,
  80128. sqlite3_value **argv
  80129. ){
  80130. const char *z = 0;
  80131. UNUSED_PARAMETER(NotUsed);
  80132. switch( sqlite3_value_type(argv[0]) ){
  80133. case SQLITE_INTEGER: z = "integer"; break;
  80134. case SQLITE_TEXT: z = "text"; break;
  80135. case SQLITE_FLOAT: z = "real"; break;
  80136. case SQLITE_BLOB: z = "blob"; break;
  80137. default: z = "null"; break;
  80138. }
  80139. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  80140. }
  80141. /*
  80142. ** Implementation of the length() function
  80143. */
  80144. static void lengthFunc(
  80145. sqlite3_context *context,
  80146. int argc,
  80147. sqlite3_value **argv
  80148. ){
  80149. int len;
  80150. assert( argc==1 );
  80151. UNUSED_PARAMETER(argc);
  80152. switch( sqlite3_value_type(argv[0]) ){
  80153. case SQLITE_BLOB:
  80154. case SQLITE_INTEGER:
  80155. case SQLITE_FLOAT: {
  80156. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  80157. break;
  80158. }
  80159. case SQLITE_TEXT: {
  80160. const unsigned char *z = sqlite3_value_text(argv[0]);
  80161. if( z==0 ) return;
  80162. len = 0;
  80163. while( *z ){
  80164. len++;
  80165. SQLITE_SKIP_UTF8(z);
  80166. }
  80167. sqlite3_result_int(context, len);
  80168. break;
  80169. }
  80170. default: {
  80171. sqlite3_result_null(context);
  80172. break;
  80173. }
  80174. }
  80175. }
  80176. /*
  80177. ** Implementation of the abs() function.
  80178. **
  80179. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  80180. ** the numeric argument X.
  80181. */
  80182. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  80183. assert( argc==1 );
  80184. UNUSED_PARAMETER(argc);
  80185. switch( sqlite3_value_type(argv[0]) ){
  80186. case SQLITE_INTEGER: {
  80187. i64 iVal = sqlite3_value_int64(argv[0]);
  80188. if( iVal<0 ){
  80189. if( (iVal<<1)==0 ){
  80190. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  80191. ** abs(X) throws an integer overflow error since there is no
  80192. ** equivalent positive 64-bit two complement value. */
  80193. sqlite3_result_error(context, "integer overflow", -1);
  80194. return;
  80195. }
  80196. iVal = -iVal;
  80197. }
  80198. sqlite3_result_int64(context, iVal);
  80199. break;
  80200. }
  80201. case SQLITE_NULL: {
  80202. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  80203. sqlite3_result_null(context);
  80204. break;
  80205. }
  80206. default: {
  80207. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  80208. ** something that can be converted into a number, we have:
  80209. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  80210. ** cannot be converted to a numeric value.
  80211. */
  80212. double rVal = sqlite3_value_double(argv[0]);
  80213. if( rVal<0 ) rVal = -rVal;
  80214. sqlite3_result_double(context, rVal);
  80215. break;
  80216. }
  80217. }
  80218. }
  80219. /*
  80220. ** Implementation of the instr() function.
  80221. **
  80222. ** instr(haystack,needle) finds the first occurrence of needle
  80223. ** in haystack and returns the number of previous characters plus 1,
  80224. ** or 0 if needle does not occur within haystack.
  80225. **
  80226. ** If both haystack and needle are BLOBs, then the result is one more than
  80227. ** the number of bytes in haystack prior to the first occurrence of needle,
  80228. ** or 0 if needle never occurs in haystack.
  80229. */
  80230. static void instrFunc(
  80231. sqlite3_context *context,
  80232. int argc,
  80233. sqlite3_value **argv
  80234. ){
  80235. const unsigned char *zHaystack;
  80236. const unsigned char *zNeedle;
  80237. int nHaystack;
  80238. int nNeedle;
  80239. int typeHaystack, typeNeedle;
  80240. int N = 1;
  80241. int isText;
  80242. UNUSED_PARAMETER(argc);
  80243. typeHaystack = sqlite3_value_type(argv[0]);
  80244. typeNeedle = sqlite3_value_type(argv[1]);
  80245. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  80246. nHaystack = sqlite3_value_bytes(argv[0]);
  80247. nNeedle = sqlite3_value_bytes(argv[1]);
  80248. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  80249. zHaystack = sqlite3_value_blob(argv[0]);
  80250. zNeedle = sqlite3_value_blob(argv[1]);
  80251. isText = 0;
  80252. }else{
  80253. zHaystack = sqlite3_value_text(argv[0]);
  80254. zNeedle = sqlite3_value_text(argv[1]);
  80255. isText = 1;
  80256. }
  80257. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  80258. N++;
  80259. do{
  80260. nHaystack--;
  80261. zHaystack++;
  80262. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  80263. }
  80264. if( nNeedle>nHaystack ) N = 0;
  80265. sqlite3_result_int(context, N);
  80266. }
  80267. /*
  80268. ** Implementation of the substr() function.
  80269. **
  80270. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  80271. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  80272. ** of x. If x is text, then we actually count UTF-8 characters.
  80273. ** If x is a blob, then we count bytes.
  80274. **
  80275. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  80276. **
  80277. ** If p2 is negative, return the p2 characters preceeding p1.
  80278. */
  80279. static void substrFunc(
  80280. sqlite3_context *context,
  80281. int argc,
  80282. sqlite3_value **argv
  80283. ){
  80284. const unsigned char *z;
  80285. const unsigned char *z2;
  80286. int len;
  80287. int p0type;
  80288. i64 p1, p2;
  80289. int negP2 = 0;
  80290. assert( argc==3 || argc==2 );
  80291. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  80292. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  80293. ){
  80294. return;
  80295. }
  80296. p0type = sqlite3_value_type(argv[0]);
  80297. p1 = sqlite3_value_int(argv[1]);
  80298. if( p0type==SQLITE_BLOB ){
  80299. len = sqlite3_value_bytes(argv[0]);
  80300. z = sqlite3_value_blob(argv[0]);
  80301. if( z==0 ) return;
  80302. assert( len==sqlite3_value_bytes(argv[0]) );
  80303. }else{
  80304. z = sqlite3_value_text(argv[0]);
  80305. if( z==0 ) return;
  80306. len = 0;
  80307. if( p1<0 ){
  80308. for(z2=z; *z2; len++){
  80309. SQLITE_SKIP_UTF8(z2);
  80310. }
  80311. }
  80312. }
  80313. if( argc==3 ){
  80314. p2 = sqlite3_value_int(argv[2]);
  80315. if( p2<0 ){
  80316. p2 = -p2;
  80317. negP2 = 1;
  80318. }
  80319. }else{
  80320. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  80321. }
  80322. if( p1<0 ){
  80323. p1 += len;
  80324. if( p1<0 ){
  80325. p2 += p1;
  80326. if( p2<0 ) p2 = 0;
  80327. p1 = 0;
  80328. }
  80329. }else if( p1>0 ){
  80330. p1--;
  80331. }else if( p2>0 ){
  80332. p2--;
  80333. }
  80334. if( negP2 ){
  80335. p1 -= p2;
  80336. if( p1<0 ){
  80337. p2 += p1;
  80338. p1 = 0;
  80339. }
  80340. }
  80341. assert( p1>=0 && p2>=0 );
  80342. if( p0type!=SQLITE_BLOB ){
  80343. while( *z && p1 ){
  80344. SQLITE_SKIP_UTF8(z);
  80345. p1--;
  80346. }
  80347. for(z2=z; *z2 && p2; p2--){
  80348. SQLITE_SKIP_UTF8(z2);
  80349. }
  80350. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  80351. }else{
  80352. if( p1+p2>len ){
  80353. p2 = len-p1;
  80354. if( p2<0 ) p2 = 0;
  80355. }
  80356. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  80357. }
  80358. }
  80359. /*
  80360. ** Implementation of the round() function
  80361. */
  80362. #ifndef SQLITE_OMIT_FLOATING_POINT
  80363. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  80364. int n = 0;
  80365. double r;
  80366. char *zBuf;
  80367. assert( argc==1 || argc==2 );
  80368. if( argc==2 ){
  80369. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  80370. n = sqlite3_value_int(argv[1]);
  80371. if( n>30 ) n = 30;
  80372. if( n<0 ) n = 0;
  80373. }
  80374. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  80375. r = sqlite3_value_double(argv[0]);
  80376. /* If Y==0 and X will fit in a 64-bit int,
  80377. ** handle the rounding directly,
  80378. ** otherwise use printf.
  80379. */
  80380. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  80381. r = (double)((sqlite_int64)(r+0.5));
  80382. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  80383. r = -(double)((sqlite_int64)((-r)+0.5));
  80384. }else{
  80385. zBuf = sqlite3_mprintf("%.*f",n,r);
  80386. if( zBuf==0 ){
  80387. sqlite3_result_error_nomem(context);
  80388. return;
  80389. }
  80390. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  80391. sqlite3_free(zBuf);
  80392. }
  80393. sqlite3_result_double(context, r);
  80394. }
  80395. #endif
  80396. /*
  80397. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  80398. ** allocation fails, call sqlite3_result_error_nomem() to notify
  80399. ** the database handle that malloc() has failed and return NULL.
  80400. ** If nByte is larger than the maximum string or blob length, then
  80401. ** raise an SQLITE_TOOBIG exception and return NULL.
  80402. */
  80403. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  80404. char *z;
  80405. sqlite3 *db = sqlite3_context_db_handle(context);
  80406. assert( nByte>0 );
  80407. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  80408. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  80409. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80410. sqlite3_result_error_toobig(context);
  80411. z = 0;
  80412. }else{
  80413. z = sqlite3Malloc((int)nByte);
  80414. if( !z ){
  80415. sqlite3_result_error_nomem(context);
  80416. }
  80417. }
  80418. return z;
  80419. }
  80420. /*
  80421. ** Implementation of the upper() and lower() SQL functions.
  80422. */
  80423. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  80424. char *z1;
  80425. const char *z2;
  80426. int i, n;
  80427. UNUSED_PARAMETER(argc);
  80428. z2 = (char*)sqlite3_value_text(argv[0]);
  80429. n = sqlite3_value_bytes(argv[0]);
  80430. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  80431. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  80432. if( z2 ){
  80433. z1 = contextMalloc(context, ((i64)n)+1);
  80434. if( z1 ){
  80435. for(i=0; i<n; i++){
  80436. z1[i] = (char)sqlite3Toupper(z2[i]);
  80437. }
  80438. sqlite3_result_text(context, z1, n, sqlite3_free);
  80439. }
  80440. }
  80441. }
  80442. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  80443. char *z1;
  80444. const char *z2;
  80445. int i, n;
  80446. UNUSED_PARAMETER(argc);
  80447. z2 = (char*)sqlite3_value_text(argv[0]);
  80448. n = sqlite3_value_bytes(argv[0]);
  80449. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  80450. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  80451. if( z2 ){
  80452. z1 = contextMalloc(context, ((i64)n)+1);
  80453. if( z1 ){
  80454. for(i=0; i<n; i++){
  80455. z1[i] = sqlite3Tolower(z2[i]);
  80456. }
  80457. sqlite3_result_text(context, z1, n, sqlite3_free);
  80458. }
  80459. }
  80460. }
  80461. /*
  80462. ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
  80463. ** that unused argument values do not have to be computed. However, we
  80464. ** still need some kind of function implementation for this routines in
  80465. ** the function table. That function implementation will never be called
  80466. ** so it doesn't matter what the implementation is. We might as well use
  80467. ** the "version()" function as a substitute.
  80468. */
  80469. #define ifnullFunc versionFunc /* Substitute function - never called */
  80470. /*
  80471. ** Implementation of random(). Return a random integer.
  80472. */
  80473. static void randomFunc(
  80474. sqlite3_context *context,
  80475. int NotUsed,
  80476. sqlite3_value **NotUsed2
  80477. ){
  80478. sqlite_int64 r;
  80479. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80480. sqlite3_randomness(sizeof(r), &r);
  80481. if( r<0 ){
  80482. /* We need to prevent a random number of 0x8000000000000000
  80483. ** (or -9223372036854775808) since when you do abs() of that
  80484. ** number of you get the same value back again. To do this
  80485. ** in a way that is testable, mask the sign bit off of negative
  80486. ** values, resulting in a positive value. Then take the
  80487. ** 2s complement of that positive value. The end result can
  80488. ** therefore be no less than -9223372036854775807.
  80489. */
  80490. r = -(r & LARGEST_INT64);
  80491. }
  80492. sqlite3_result_int64(context, r);
  80493. }
  80494. /*
  80495. ** Implementation of randomblob(N). Return a random blob
  80496. ** that is N bytes long.
  80497. */
  80498. static void randomBlob(
  80499. sqlite3_context *context,
  80500. int argc,
  80501. sqlite3_value **argv
  80502. ){
  80503. int n;
  80504. unsigned char *p;
  80505. assert( argc==1 );
  80506. UNUSED_PARAMETER(argc);
  80507. n = sqlite3_value_int(argv[0]);
  80508. if( n<1 ){
  80509. n = 1;
  80510. }
  80511. p = contextMalloc(context, n);
  80512. if( p ){
  80513. sqlite3_randomness(n, p);
  80514. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  80515. }
  80516. }
  80517. /*
  80518. ** Implementation of the last_insert_rowid() SQL function. The return
  80519. ** value is the same as the sqlite3_last_insert_rowid() API function.
  80520. */
  80521. static void last_insert_rowid(
  80522. sqlite3_context *context,
  80523. int NotUsed,
  80524. sqlite3_value **NotUsed2
  80525. ){
  80526. sqlite3 *db = sqlite3_context_db_handle(context);
  80527. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80528. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  80529. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  80530. ** function. */
  80531. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  80532. }
  80533. /*
  80534. ** Implementation of the changes() SQL function.
  80535. **
  80536. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  80537. ** around the sqlite3_changes() C/C++ function and hence follows the same
  80538. ** rules for counting changes.
  80539. */
  80540. static void changes(
  80541. sqlite3_context *context,
  80542. int NotUsed,
  80543. sqlite3_value **NotUsed2
  80544. ){
  80545. sqlite3 *db = sqlite3_context_db_handle(context);
  80546. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80547. sqlite3_result_int(context, sqlite3_changes(db));
  80548. }
  80549. /*
  80550. ** Implementation of the total_changes() SQL function. The return value is
  80551. ** the same as the sqlite3_total_changes() API function.
  80552. */
  80553. static void total_changes(
  80554. sqlite3_context *context,
  80555. int NotUsed,
  80556. sqlite3_value **NotUsed2
  80557. ){
  80558. sqlite3 *db = sqlite3_context_db_handle(context);
  80559. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80560. /* IMP: R-52756-41993 This function is a wrapper around the
  80561. ** sqlite3_total_changes() C/C++ interface. */
  80562. sqlite3_result_int(context, sqlite3_total_changes(db));
  80563. }
  80564. /*
  80565. ** A structure defining how to do GLOB-style comparisons.
  80566. */
  80567. struct compareInfo {
  80568. u8 matchAll;
  80569. u8 matchOne;
  80570. u8 matchSet;
  80571. u8 noCase;
  80572. };
  80573. /*
  80574. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  80575. ** character is exactly one byte in size. Also, all characters are
  80576. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  80577. ** whereas only characters less than 0x80 do in ASCII.
  80578. */
  80579. #if defined(SQLITE_EBCDIC)
  80580. # define sqlite3Utf8Read(A) (*((*A)++))
  80581. # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
  80582. #else
  80583. # define GlogUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  80584. #endif
  80585. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  80586. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  80587. ** case. Thus 'a' LIKE 'A' would be true. */
  80588. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  80589. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  80590. ** is case sensitive causing 'a' LIKE 'A' to be false */
  80591. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  80592. /*
  80593. ** Compare two UTF-8 strings for equality where the first string can
  80594. ** potentially be a "glob" expression. Return true (1) if they
  80595. ** are the same and false (0) if they are different.
  80596. **
  80597. ** Globbing rules:
  80598. **
  80599. ** '*' Matches any sequence of zero or more characters.
  80600. **
  80601. ** '?' Matches exactly one character.
  80602. **
  80603. ** [...] Matches one character from the enclosed list of
  80604. ** characters.
  80605. **
  80606. ** [^...] Matches one character not in the enclosed list.
  80607. **
  80608. ** With the [...] and [^...] matching, a ']' character can be included
  80609. ** in the list by making it the first character after '[' or '^'. A
  80610. ** range of characters can be specified using '-'. Example:
  80611. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  80612. ** it the last character in the list.
  80613. **
  80614. ** This routine is usually quick, but can be N**2 in the worst case.
  80615. **
  80616. ** Hints: to match '*' or '?', put them in "[]". Like this:
  80617. **
  80618. ** abc[*]xyz Matches "abc*xyz" only
  80619. */
  80620. static int patternCompare(
  80621. const u8 *zPattern, /* The glob pattern */
  80622. const u8 *zString, /* The string to compare against the glob */
  80623. const struct compareInfo *pInfo, /* Information about how to do the compare */
  80624. u32 esc /* The escape character */
  80625. ){
  80626. u32 c, c2;
  80627. int invert;
  80628. int seen;
  80629. u8 matchOne = pInfo->matchOne;
  80630. u8 matchAll = pInfo->matchAll;
  80631. u8 matchSet = pInfo->matchSet;
  80632. u8 noCase = pInfo->noCase;
  80633. int prevEscape = 0; /* True if the previous character was 'escape' */
  80634. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  80635. if( c==matchAll && !prevEscape ){
  80636. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  80637. || c == matchOne ){
  80638. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  80639. return 0;
  80640. }
  80641. }
  80642. if( c==0 ){
  80643. return 1;
  80644. }else if( c==esc ){
  80645. c = sqlite3Utf8Read(&zPattern);
  80646. if( c==0 ){
  80647. return 0;
  80648. }
  80649. }else if( c==matchSet ){
  80650. assert( esc==0 ); /* This is GLOB, not LIKE */
  80651. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  80652. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  80653. SQLITE_SKIP_UTF8(zString);
  80654. }
  80655. return *zString!=0;
  80656. }
  80657. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  80658. if( noCase ){
  80659. GlogUpperToLower(c2);
  80660. GlogUpperToLower(c);
  80661. while( c2 != 0 && c2 != c ){
  80662. c2 = sqlite3Utf8Read(&zString);
  80663. GlogUpperToLower(c2);
  80664. }
  80665. }else{
  80666. while( c2 != 0 && c2 != c ){
  80667. c2 = sqlite3Utf8Read(&zString);
  80668. }
  80669. }
  80670. if( c2==0 ) return 0;
  80671. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  80672. }
  80673. return 0;
  80674. }else if( c==matchOne && !prevEscape ){
  80675. if( sqlite3Utf8Read(&zString)==0 ){
  80676. return 0;
  80677. }
  80678. }else if( c==matchSet ){
  80679. u32 prior_c = 0;
  80680. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  80681. seen = 0;
  80682. invert = 0;
  80683. c = sqlite3Utf8Read(&zString);
  80684. if( c==0 ) return 0;
  80685. c2 = sqlite3Utf8Read(&zPattern);
  80686. if( c2=='^' ){
  80687. invert = 1;
  80688. c2 = sqlite3Utf8Read(&zPattern);
  80689. }
  80690. if( c2==']' ){
  80691. if( c==']' ) seen = 1;
  80692. c2 = sqlite3Utf8Read(&zPattern);
  80693. }
  80694. while( c2 && c2!=']' ){
  80695. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  80696. c2 = sqlite3Utf8Read(&zPattern);
  80697. if( c>=prior_c && c<=c2 ) seen = 1;
  80698. prior_c = 0;
  80699. }else{
  80700. if( c==c2 ){
  80701. seen = 1;
  80702. }
  80703. prior_c = c2;
  80704. }
  80705. c2 = sqlite3Utf8Read(&zPattern);
  80706. }
  80707. if( c2==0 || (seen ^ invert)==0 ){
  80708. return 0;
  80709. }
  80710. }else if( esc==c && !prevEscape ){
  80711. prevEscape = 1;
  80712. }else{
  80713. c2 = sqlite3Utf8Read(&zString);
  80714. if( noCase ){
  80715. GlogUpperToLower(c);
  80716. GlogUpperToLower(c2);
  80717. }
  80718. if( c!=c2 ){
  80719. return 0;
  80720. }
  80721. prevEscape = 0;
  80722. }
  80723. }
  80724. return *zString==0;
  80725. }
  80726. /*
  80727. ** Count the number of times that the LIKE operator (or GLOB which is
  80728. ** just a variation of LIKE) gets called. This is used for testing
  80729. ** only.
  80730. */
  80731. #ifdef SQLITE_TEST
  80732. SQLITE_API int sqlite3_like_count = 0;
  80733. #endif
  80734. /*
  80735. ** Implementation of the like() SQL function. This function implements
  80736. ** the build-in LIKE operator. The first argument to the function is the
  80737. ** pattern and the second argument is the string. So, the SQL statements:
  80738. **
  80739. ** A LIKE B
  80740. **
  80741. ** is implemented as like(B,A).
  80742. **
  80743. ** This same function (with a different compareInfo structure) computes
  80744. ** the GLOB operator.
  80745. */
  80746. static void likeFunc(
  80747. sqlite3_context *context,
  80748. int argc,
  80749. sqlite3_value **argv
  80750. ){
  80751. const unsigned char *zA, *zB;
  80752. u32 escape = 0;
  80753. int nPat;
  80754. sqlite3 *db = sqlite3_context_db_handle(context);
  80755. zB = sqlite3_value_text(argv[0]);
  80756. zA = sqlite3_value_text(argv[1]);
  80757. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  80758. ** of deep recursion and N*N behavior in patternCompare().
  80759. */
  80760. nPat = sqlite3_value_bytes(argv[0]);
  80761. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  80762. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  80763. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  80764. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  80765. return;
  80766. }
  80767. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  80768. if( argc==3 ){
  80769. /* The escape character string must consist of a single UTF-8 character.
  80770. ** Otherwise, return an error.
  80771. */
  80772. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  80773. if( zEsc==0 ) return;
  80774. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  80775. sqlite3_result_error(context,
  80776. "ESCAPE expression must be a single character", -1);
  80777. return;
  80778. }
  80779. escape = sqlite3Utf8Read(&zEsc);
  80780. }
  80781. if( zA && zB ){
  80782. struct compareInfo *pInfo = sqlite3_user_data(context);
  80783. #ifdef SQLITE_TEST
  80784. sqlite3_like_count++;
  80785. #endif
  80786. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  80787. }
  80788. }
  80789. /*
  80790. ** Implementation of the NULLIF(x,y) function. The result is the first
  80791. ** argument if the arguments are different. The result is NULL if the
  80792. ** arguments are equal to each other.
  80793. */
  80794. static void nullifFunc(
  80795. sqlite3_context *context,
  80796. int NotUsed,
  80797. sqlite3_value **argv
  80798. ){
  80799. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  80800. UNUSED_PARAMETER(NotUsed);
  80801. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  80802. sqlite3_result_value(context, argv[0]);
  80803. }
  80804. }
  80805. /*
  80806. ** Implementation of the sqlite_version() function. The result is the version
  80807. ** of the SQLite library that is running.
  80808. */
  80809. static void versionFunc(
  80810. sqlite3_context *context,
  80811. int NotUsed,
  80812. sqlite3_value **NotUsed2
  80813. ){
  80814. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80815. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  80816. ** sqlite3_libversion() C-interface. */
  80817. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  80818. }
  80819. /*
  80820. ** Implementation of the sqlite_source_id() function. The result is a string
  80821. ** that identifies the particular version of the source code used to build
  80822. ** SQLite.
  80823. */
  80824. static void sourceidFunc(
  80825. sqlite3_context *context,
  80826. int NotUsed,
  80827. sqlite3_value **NotUsed2
  80828. ){
  80829. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  80830. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  80831. ** sqlite3_sourceid() C interface. */
  80832. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  80833. }
  80834. /*
  80835. ** Implementation of the sqlite_log() function. This is a wrapper around
  80836. ** sqlite3_log(). The return value is NULL. The function exists purely for
  80837. ** its side-effects.
  80838. */
  80839. static void errlogFunc(
  80840. sqlite3_context *context,
  80841. int argc,
  80842. sqlite3_value **argv
  80843. ){
  80844. UNUSED_PARAMETER(argc);
  80845. UNUSED_PARAMETER(context);
  80846. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  80847. }
  80848. /*
  80849. ** Implementation of the sqlite_compileoption_used() function.
  80850. ** The result is an integer that identifies if the compiler option
  80851. ** was used to build SQLite.
  80852. */
  80853. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  80854. static void compileoptionusedFunc(
  80855. sqlite3_context *context,
  80856. int argc,
  80857. sqlite3_value **argv
  80858. ){
  80859. const char *zOptName;
  80860. assert( argc==1 );
  80861. UNUSED_PARAMETER(argc);
  80862. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  80863. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  80864. ** function.
  80865. */
  80866. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  80867. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  80868. }
  80869. }
  80870. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  80871. /*
  80872. ** Implementation of the sqlite_compileoption_get() function.
  80873. ** The result is a string that identifies the compiler options
  80874. ** used to build SQLite.
  80875. */
  80876. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  80877. static void compileoptiongetFunc(
  80878. sqlite3_context *context,
  80879. int argc,
  80880. sqlite3_value **argv
  80881. ){
  80882. int n;
  80883. assert( argc==1 );
  80884. UNUSED_PARAMETER(argc);
  80885. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  80886. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  80887. */
  80888. n = sqlite3_value_int(argv[0]);
  80889. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  80890. }
  80891. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  80892. /* Array for converting from half-bytes (nybbles) into ASCII hex
  80893. ** digits. */
  80894. static const char hexdigits[] = {
  80895. '0', '1', '2', '3', '4', '5', '6', '7',
  80896. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  80897. };
  80898. /*
  80899. ** EXPERIMENTAL - This is not an official function. The interface may
  80900. ** change. This function may disappear. Do not write code that depends
  80901. ** on this function.
  80902. **
  80903. ** Implementation of the QUOTE() function. This function takes a single
  80904. ** argument. If the argument is numeric, the return value is the same as
  80905. ** the argument. If the argument is NULL, the return value is the string
  80906. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  80907. ** single-quote escapes.
  80908. */
  80909. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  80910. assert( argc==1 );
  80911. UNUSED_PARAMETER(argc);
  80912. switch( sqlite3_value_type(argv[0]) ){
  80913. case SQLITE_FLOAT: {
  80914. double r1, r2;
  80915. char zBuf[50];
  80916. r1 = sqlite3_value_double(argv[0]);
  80917. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  80918. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  80919. if( r1!=r2 ){
  80920. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  80921. }
  80922. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  80923. break;
  80924. }
  80925. case SQLITE_INTEGER: {
  80926. sqlite3_result_value(context, argv[0]);
  80927. break;
  80928. }
  80929. case SQLITE_BLOB: {
  80930. char *zText = 0;
  80931. char const *zBlob = sqlite3_value_blob(argv[0]);
  80932. int nBlob = sqlite3_value_bytes(argv[0]);
  80933. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  80934. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  80935. if( zText ){
  80936. int i;
  80937. for(i=0; i<nBlob; i++){
  80938. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  80939. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  80940. }
  80941. zText[(nBlob*2)+2] = '\'';
  80942. zText[(nBlob*2)+3] = '\0';
  80943. zText[0] = 'X';
  80944. zText[1] = '\'';
  80945. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  80946. sqlite3_free(zText);
  80947. }
  80948. break;
  80949. }
  80950. case SQLITE_TEXT: {
  80951. int i,j;
  80952. u64 n;
  80953. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  80954. char *z;
  80955. if( zArg==0 ) return;
  80956. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  80957. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  80958. if( z ){
  80959. z[0] = '\'';
  80960. for(i=0, j=1; zArg[i]; i++){
  80961. z[j++] = zArg[i];
  80962. if( zArg[i]=='\'' ){
  80963. z[j++] = '\'';
  80964. }
  80965. }
  80966. z[j++] = '\'';
  80967. z[j] = 0;
  80968. sqlite3_result_text(context, z, j, sqlite3_free);
  80969. }
  80970. break;
  80971. }
  80972. default: {
  80973. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  80974. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  80975. break;
  80976. }
  80977. }
  80978. }
  80979. /*
  80980. ** The hex() function. Interpret the argument as a blob. Return
  80981. ** a hexadecimal rendering as text.
  80982. */
  80983. static void hexFunc(
  80984. sqlite3_context *context,
  80985. int argc,
  80986. sqlite3_value **argv
  80987. ){
  80988. int i, n;
  80989. const unsigned char *pBlob;
  80990. char *zHex, *z;
  80991. assert( argc==1 );
  80992. UNUSED_PARAMETER(argc);
  80993. pBlob = sqlite3_value_blob(argv[0]);
  80994. n = sqlite3_value_bytes(argv[0]);
  80995. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  80996. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  80997. if( zHex ){
  80998. for(i=0; i<n; i++, pBlob++){
  80999. unsigned char c = *pBlob;
  81000. *(z++) = hexdigits[(c>>4)&0xf];
  81001. *(z++) = hexdigits[c&0xf];
  81002. }
  81003. *z = 0;
  81004. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  81005. }
  81006. }
  81007. /*
  81008. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  81009. */
  81010. static void zeroblobFunc(
  81011. sqlite3_context *context,
  81012. int argc,
  81013. sqlite3_value **argv
  81014. ){
  81015. i64 n;
  81016. sqlite3 *db = sqlite3_context_db_handle(context);
  81017. assert( argc==1 );
  81018. UNUSED_PARAMETER(argc);
  81019. n = sqlite3_value_int64(argv[0]);
  81020. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  81021. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  81022. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81023. sqlite3_result_error_toobig(context);
  81024. }else{
  81025. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  81026. }
  81027. }
  81028. /*
  81029. ** The replace() function. Three arguments are all strings: call
  81030. ** them A, B, and C. The result is also a string which is derived
  81031. ** from A by replacing every occurance of B with C. The match
  81032. ** must be exact. Collating sequences are not used.
  81033. */
  81034. static void replaceFunc(
  81035. sqlite3_context *context,
  81036. int argc,
  81037. sqlite3_value **argv
  81038. ){
  81039. const unsigned char *zStr; /* The input string A */
  81040. const unsigned char *zPattern; /* The pattern string B */
  81041. const unsigned char *zRep; /* The replacement string C */
  81042. unsigned char *zOut; /* The output */
  81043. int nStr; /* Size of zStr */
  81044. int nPattern; /* Size of zPattern */
  81045. int nRep; /* Size of zRep */
  81046. i64 nOut; /* Maximum size of zOut */
  81047. int loopLimit; /* Last zStr[] that might match zPattern[] */
  81048. int i, j; /* Loop counters */
  81049. assert( argc==3 );
  81050. UNUSED_PARAMETER(argc);
  81051. zStr = sqlite3_value_text(argv[0]);
  81052. if( zStr==0 ) return;
  81053. nStr = sqlite3_value_bytes(argv[0]);
  81054. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  81055. zPattern = sqlite3_value_text(argv[1]);
  81056. if( zPattern==0 ){
  81057. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  81058. || sqlite3_context_db_handle(context)->mallocFailed );
  81059. return;
  81060. }
  81061. if( zPattern[0]==0 ){
  81062. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  81063. sqlite3_result_value(context, argv[0]);
  81064. return;
  81065. }
  81066. nPattern = sqlite3_value_bytes(argv[1]);
  81067. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  81068. zRep = sqlite3_value_text(argv[2]);
  81069. if( zRep==0 ) return;
  81070. nRep = sqlite3_value_bytes(argv[2]);
  81071. assert( zRep==sqlite3_value_text(argv[2]) );
  81072. nOut = nStr + 1;
  81073. assert( nOut<SQLITE_MAX_LENGTH );
  81074. zOut = contextMalloc(context, (i64)nOut);
  81075. if( zOut==0 ){
  81076. return;
  81077. }
  81078. loopLimit = nStr - nPattern;
  81079. for(i=j=0; i<=loopLimit; i++){
  81080. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  81081. zOut[j++] = zStr[i];
  81082. }else{
  81083. u8 *zOld;
  81084. sqlite3 *db = sqlite3_context_db_handle(context);
  81085. nOut += nRep - nPattern;
  81086. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  81087. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  81088. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81089. sqlite3_result_error_toobig(context);
  81090. sqlite3_free(zOut);
  81091. return;
  81092. }
  81093. zOld = zOut;
  81094. zOut = sqlite3_realloc(zOut, (int)nOut);
  81095. if( zOut==0 ){
  81096. sqlite3_result_error_nomem(context);
  81097. sqlite3_free(zOld);
  81098. return;
  81099. }
  81100. memcpy(&zOut[j], zRep, nRep);
  81101. j += nRep;
  81102. i += nPattern-1;
  81103. }
  81104. }
  81105. assert( j+nStr-i+1==nOut );
  81106. memcpy(&zOut[j], &zStr[i], nStr-i);
  81107. j += nStr - i;
  81108. assert( j<=nOut );
  81109. zOut[j] = 0;
  81110. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  81111. }
  81112. /*
  81113. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  81114. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  81115. */
  81116. static void trimFunc(
  81117. sqlite3_context *context,
  81118. int argc,
  81119. sqlite3_value **argv
  81120. ){
  81121. const unsigned char *zIn; /* Input string */
  81122. const unsigned char *zCharSet; /* Set of characters to trim */
  81123. int nIn; /* Number of bytes in input */
  81124. int flags; /* 1: trimleft 2: trimright 3: trim */
  81125. int i; /* Loop counter */
  81126. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  81127. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  81128. int nChar; /* Number of characters in zCharSet */
  81129. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  81130. return;
  81131. }
  81132. zIn = sqlite3_value_text(argv[0]);
  81133. if( zIn==0 ) return;
  81134. nIn = sqlite3_value_bytes(argv[0]);
  81135. assert( zIn==sqlite3_value_text(argv[0]) );
  81136. if( argc==1 ){
  81137. static const unsigned char lenOne[] = { 1 };
  81138. static unsigned char * const azOne[] = { (u8*)" " };
  81139. nChar = 1;
  81140. aLen = (u8*)lenOne;
  81141. azChar = (unsigned char **)azOne;
  81142. zCharSet = 0;
  81143. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  81144. return;
  81145. }else{
  81146. const unsigned char *z;
  81147. for(z=zCharSet, nChar=0; *z; nChar++){
  81148. SQLITE_SKIP_UTF8(z);
  81149. }
  81150. if( nChar>0 ){
  81151. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  81152. if( azChar==0 ){
  81153. return;
  81154. }
  81155. aLen = (unsigned char*)&azChar[nChar];
  81156. for(z=zCharSet, nChar=0; *z; nChar++){
  81157. azChar[nChar] = (unsigned char *)z;
  81158. SQLITE_SKIP_UTF8(z);
  81159. aLen[nChar] = (u8)(z - azChar[nChar]);
  81160. }
  81161. }
  81162. }
  81163. if( nChar>0 ){
  81164. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  81165. if( flags & 1 ){
  81166. while( nIn>0 ){
  81167. int len = 0;
  81168. for(i=0; i<nChar; i++){
  81169. len = aLen[i];
  81170. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  81171. }
  81172. if( i>=nChar ) break;
  81173. zIn += len;
  81174. nIn -= len;
  81175. }
  81176. }
  81177. if( flags & 2 ){
  81178. while( nIn>0 ){
  81179. int len = 0;
  81180. for(i=0; i<nChar; i++){
  81181. len = aLen[i];
  81182. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  81183. }
  81184. if( i>=nChar ) break;
  81185. nIn -= len;
  81186. }
  81187. }
  81188. if( zCharSet ){
  81189. sqlite3_free(azChar);
  81190. }
  81191. }
  81192. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  81193. }
  81194. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  81195. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  81196. ** when SQLite is built.
  81197. */
  81198. #ifdef SQLITE_SOUNDEX
  81199. /*
  81200. ** Compute the soundex encoding of a word.
  81201. **
  81202. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  81203. ** soundex encoding of the string X.
  81204. */
  81205. static void soundexFunc(
  81206. sqlite3_context *context,
  81207. int argc,
  81208. sqlite3_value **argv
  81209. ){
  81210. char zResult[8];
  81211. const u8 *zIn;
  81212. int i, j;
  81213. static const unsigned char iCode[] = {
  81214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  81215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  81216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  81217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  81218. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  81219. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  81220. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  81221. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  81222. };
  81223. assert( argc==1 );
  81224. zIn = (u8*)sqlite3_value_text(argv[0]);
  81225. if( zIn==0 ) zIn = (u8*)"";
  81226. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  81227. if( zIn[i] ){
  81228. u8 prevcode = iCode[zIn[i]&0x7f];
  81229. zResult[0] = sqlite3Toupper(zIn[i]);
  81230. for(j=1; j<4 && zIn[i]; i++){
  81231. int code = iCode[zIn[i]&0x7f];
  81232. if( code>0 ){
  81233. if( code!=prevcode ){
  81234. prevcode = code;
  81235. zResult[j++] = code + '0';
  81236. }
  81237. }else{
  81238. prevcode = 0;
  81239. }
  81240. }
  81241. while( j<4 ){
  81242. zResult[j++] = '0';
  81243. }
  81244. zResult[j] = 0;
  81245. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  81246. }else{
  81247. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  81248. ** is NULL or contains no ASCII alphabetic characters. */
  81249. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  81250. }
  81251. }
  81252. #endif /* SQLITE_SOUNDEX */
  81253. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  81254. /*
  81255. ** A function that loads a shared-library extension then returns NULL.
  81256. */
  81257. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  81258. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  81259. const char *zProc;
  81260. sqlite3 *db = sqlite3_context_db_handle(context);
  81261. char *zErrMsg = 0;
  81262. if( argc==2 ){
  81263. zProc = (const char *)sqlite3_value_text(argv[1]);
  81264. }else{
  81265. zProc = 0;
  81266. }
  81267. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  81268. sqlite3_result_error(context, zErrMsg, -1);
  81269. sqlite3_free(zErrMsg);
  81270. }
  81271. }
  81272. #endif
  81273. /*
  81274. ** An instance of the following structure holds the context of a
  81275. ** sum() or avg() aggregate computation.
  81276. */
  81277. typedef struct SumCtx SumCtx;
  81278. struct SumCtx {
  81279. double rSum; /* Floating point sum */
  81280. i64 iSum; /* Integer sum */
  81281. i64 cnt; /* Number of elements summed */
  81282. u8 overflow; /* True if integer overflow seen */
  81283. u8 approx; /* True if non-integer value was input to the sum */
  81284. };
  81285. /*
  81286. ** Routines used to compute the sum, average, and total.
  81287. **
  81288. ** The SUM() function follows the (broken) SQL standard which means
  81289. ** that it returns NULL if it sums over no inputs. TOTAL returns
  81290. ** 0.0 in that case. In addition, TOTAL always returns a float where
  81291. ** SUM might return an integer if it never encounters a floating point
  81292. ** value. TOTAL never fails, but SUM might through an exception if
  81293. ** it overflows an integer.
  81294. */
  81295. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  81296. SumCtx *p;
  81297. int type;
  81298. assert( argc==1 );
  81299. UNUSED_PARAMETER(argc);
  81300. p = sqlite3_aggregate_context(context, sizeof(*p));
  81301. type = sqlite3_value_numeric_type(argv[0]);
  81302. if( p && type!=SQLITE_NULL ){
  81303. p->cnt++;
  81304. if( type==SQLITE_INTEGER ){
  81305. i64 v = sqlite3_value_int64(argv[0]);
  81306. p->rSum += v;
  81307. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  81308. p->overflow = 1;
  81309. }
  81310. }else{
  81311. p->rSum += sqlite3_value_double(argv[0]);
  81312. p->approx = 1;
  81313. }
  81314. }
  81315. }
  81316. static void sumFinalize(sqlite3_context *context){
  81317. SumCtx *p;
  81318. p = sqlite3_aggregate_context(context, 0);
  81319. if( p && p->cnt>0 ){
  81320. if( p->overflow ){
  81321. sqlite3_result_error(context,"integer overflow",-1);
  81322. }else if( p->approx ){
  81323. sqlite3_result_double(context, p->rSum);
  81324. }else{
  81325. sqlite3_result_int64(context, p->iSum);
  81326. }
  81327. }
  81328. }
  81329. static void avgFinalize(sqlite3_context *context){
  81330. SumCtx *p;
  81331. p = sqlite3_aggregate_context(context, 0);
  81332. if( p && p->cnt>0 ){
  81333. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  81334. }
  81335. }
  81336. static void totalFinalize(sqlite3_context *context){
  81337. SumCtx *p;
  81338. p = sqlite3_aggregate_context(context, 0);
  81339. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  81340. sqlite3_result_double(context, p ? p->rSum : (double)0);
  81341. }
  81342. /*
  81343. ** The following structure keeps track of state information for the
  81344. ** count() aggregate function.
  81345. */
  81346. typedef struct CountCtx CountCtx;
  81347. struct CountCtx {
  81348. i64 n;
  81349. };
  81350. /*
  81351. ** Routines to implement the count() aggregate function.
  81352. */
  81353. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  81354. CountCtx *p;
  81355. p = sqlite3_aggregate_context(context, sizeof(*p));
  81356. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  81357. p->n++;
  81358. }
  81359. #ifndef SQLITE_OMIT_DEPRECATED
  81360. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  81361. ** sure it still operates correctly, verify that its count agrees with our
  81362. ** internal count when using count(*) and when the total count can be
  81363. ** expressed as a 32-bit integer. */
  81364. assert( argc==1 || p==0 || p->n>0x7fffffff
  81365. || p->n==sqlite3_aggregate_count(context) );
  81366. #endif
  81367. }
  81368. static void countFinalize(sqlite3_context *context){
  81369. CountCtx *p;
  81370. p = sqlite3_aggregate_context(context, 0);
  81371. sqlite3_result_int64(context, p ? p->n : 0);
  81372. }
  81373. /*
  81374. ** Routines to implement min() and max() aggregate functions.
  81375. */
  81376. static void minmaxStep(
  81377. sqlite3_context *context,
  81378. int NotUsed,
  81379. sqlite3_value **argv
  81380. ){
  81381. Mem *pArg = (Mem *)argv[0];
  81382. Mem *pBest;
  81383. UNUSED_PARAMETER(NotUsed);
  81384. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  81385. if( !pBest ) return;
  81386. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  81387. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  81388. }else if( pBest->flags ){
  81389. int max;
  81390. int cmp;
  81391. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  81392. /* This step function is used for both the min() and max() aggregates,
  81393. ** the only difference between the two being that the sense of the
  81394. ** comparison is inverted. For the max() aggregate, the
  81395. ** sqlite3_user_data() function returns (void *)-1. For min() it
  81396. ** returns (void *)db, where db is the sqlite3* database pointer.
  81397. ** Therefore the next statement sets variable 'max' to 1 for the max()
  81398. ** aggregate, or 0 for min().
  81399. */
  81400. max = sqlite3_user_data(context)!=0;
  81401. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  81402. if( (max && cmp<0) || (!max && cmp>0) ){
  81403. sqlite3VdbeMemCopy(pBest, pArg);
  81404. }else{
  81405. sqlite3SkipAccumulatorLoad(context);
  81406. }
  81407. }else{
  81408. sqlite3VdbeMemCopy(pBest, pArg);
  81409. }
  81410. }
  81411. static void minMaxFinalize(sqlite3_context *context){
  81412. sqlite3_value *pRes;
  81413. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  81414. if( pRes ){
  81415. if( pRes->flags ){
  81416. sqlite3_result_value(context, pRes);
  81417. }
  81418. sqlite3VdbeMemRelease(pRes);
  81419. }
  81420. }
  81421. /*
  81422. ** group_concat(EXPR, ?SEPARATOR?)
  81423. */
  81424. static void groupConcatStep(
  81425. sqlite3_context *context,
  81426. int argc,
  81427. sqlite3_value **argv
  81428. ){
  81429. const char *zVal;
  81430. StrAccum *pAccum;
  81431. const char *zSep;
  81432. int nVal, nSep;
  81433. assert( argc==1 || argc==2 );
  81434. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  81435. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  81436. if( pAccum ){
  81437. sqlite3 *db = sqlite3_context_db_handle(context);
  81438. int firstTerm = pAccum->useMalloc==0;
  81439. pAccum->useMalloc = 2;
  81440. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  81441. if( !firstTerm ){
  81442. if( argc==2 ){
  81443. zSep = (char*)sqlite3_value_text(argv[1]);
  81444. nSep = sqlite3_value_bytes(argv[1]);
  81445. }else{
  81446. zSep = ",";
  81447. nSep = 1;
  81448. }
  81449. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  81450. }
  81451. zVal = (char*)sqlite3_value_text(argv[0]);
  81452. nVal = sqlite3_value_bytes(argv[0]);
  81453. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  81454. }
  81455. }
  81456. static void groupConcatFinalize(sqlite3_context *context){
  81457. StrAccum *pAccum;
  81458. pAccum = sqlite3_aggregate_context(context, 0);
  81459. if( pAccum ){
  81460. if( pAccum->tooBig ){
  81461. sqlite3_result_error_toobig(context);
  81462. }else if( pAccum->mallocFailed ){
  81463. sqlite3_result_error_nomem(context);
  81464. }else{
  81465. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  81466. sqlite3_free);
  81467. }
  81468. }
  81469. }
  81470. /*
  81471. ** This routine does per-connection function registration. Most
  81472. ** of the built-in functions above are part of the global function set.
  81473. ** This routine only deals with those that are not global.
  81474. */
  81475. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  81476. int rc = sqlite3_overload_function(db, "MATCH", 2);
  81477. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  81478. if( rc==SQLITE_NOMEM ){
  81479. db->mallocFailed = 1;
  81480. }
  81481. }
  81482. /*
  81483. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  81484. */
  81485. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  81486. FuncDef *pDef;
  81487. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  81488. 2, SQLITE_UTF8, 0);
  81489. if( ALWAYS(pDef) ){
  81490. pDef->flags = flagVal;
  81491. }
  81492. }
  81493. /*
  81494. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  81495. ** parameter determines whether or not the LIKE operator is case
  81496. ** sensitive. GLOB is always case sensitive.
  81497. */
  81498. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  81499. struct compareInfo *pInfo;
  81500. if( caseSensitive ){
  81501. pInfo = (struct compareInfo*)&likeInfoAlt;
  81502. }else{
  81503. pInfo = (struct compareInfo*)&likeInfoNorm;
  81504. }
  81505. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  81506. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  81507. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  81508. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  81509. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  81510. setLikeOptFlag(db, "like",
  81511. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  81512. }
  81513. /*
  81514. ** pExpr points to an expression which implements a function. If
  81515. ** it is appropriate to apply the LIKE optimization to that function
  81516. ** then set aWc[0] through aWc[2] to the wildcard characters and
  81517. ** return TRUE. If the function is not a LIKE-style function then
  81518. ** return FALSE.
  81519. */
  81520. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  81521. FuncDef *pDef;
  81522. if( pExpr->op!=TK_FUNCTION
  81523. || !pExpr->x.pList
  81524. || pExpr->x.pList->nExpr!=2
  81525. ){
  81526. return 0;
  81527. }
  81528. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81529. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  81530. sqlite3Strlen30(pExpr->u.zToken),
  81531. 2, SQLITE_UTF8, 0);
  81532. if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  81533. return 0;
  81534. }
  81535. /* The memcpy() statement assumes that the wildcard characters are
  81536. ** the first three statements in the compareInfo structure. The
  81537. ** asserts() that follow verify that assumption
  81538. */
  81539. memcpy(aWc, pDef->pUserData, 3);
  81540. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  81541. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  81542. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  81543. *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  81544. return 1;
  81545. }
  81546. /*
  81547. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  81548. ** to the global function hash table. This occurs at start-time (as
  81549. ** a consequence of calling sqlite3_initialize()).
  81550. **
  81551. ** After this routine runs
  81552. */
  81553. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  81554. /*
  81555. ** The following array holds FuncDef structures for all of the functions
  81556. ** defined in this file.
  81557. **
  81558. ** The array cannot be constant since changes are made to the
  81559. ** FuncDef.pHash elements at start-time. The elements of this array
  81560. ** are read-only after initialization is complete.
  81561. */
  81562. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  81563. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  81564. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  81565. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  81566. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  81567. FUNCTION(trim, 1, 3, 0, trimFunc ),
  81568. FUNCTION(trim, 2, 3, 0, trimFunc ),
  81569. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  81570. FUNCTION(min, 0, 0, 1, 0 ),
  81571. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  81572. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  81573. FUNCTION(max, 0, 1, 1, 0 ),
  81574. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  81575. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  81576. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  81577. FUNCTION(instr, 2, 0, 0, instrFunc ),
  81578. FUNCTION(substr, 2, 0, 0, substrFunc ),
  81579. FUNCTION(substr, 3, 0, 0, substrFunc ),
  81580. FUNCTION(abs, 1, 0, 0, absFunc ),
  81581. #ifndef SQLITE_OMIT_FLOATING_POINT
  81582. FUNCTION(round, 1, 0, 0, roundFunc ),
  81583. FUNCTION(round, 2, 0, 0, roundFunc ),
  81584. #endif
  81585. FUNCTION(upper, 1, 0, 0, upperFunc ),
  81586. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  81587. FUNCTION(coalesce, 1, 0, 0, 0 ),
  81588. FUNCTION(coalesce, 0, 0, 0, 0 ),
  81589. FUNCTION2(coalesce, -1, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
  81590. FUNCTION(hex, 1, 0, 0, hexFunc ),
  81591. FUNCTION2(ifnull, 2, 0, 0, ifnullFunc, SQLITE_FUNC_COALESCE),
  81592. FUNCTION(random, 0, 0, 0, randomFunc ),
  81593. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  81594. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  81595. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  81596. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  81597. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  81598. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  81599. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  81600. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  81601. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  81602. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  81603. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  81604. FUNCTION(changes, 0, 0, 0, changes ),
  81605. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  81606. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  81607. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  81608. #ifdef SQLITE_SOUNDEX
  81609. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  81610. #endif
  81611. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  81612. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  81613. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  81614. #endif
  81615. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  81616. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  81617. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  81618. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  81619. {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  81620. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  81621. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  81622. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  81623. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  81624. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  81625. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  81626. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  81627. #else
  81628. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  81629. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  81630. #endif
  81631. };
  81632. int i;
  81633. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  81634. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  81635. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  81636. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  81637. }
  81638. sqlite3RegisterDateTimeFunctions();
  81639. #ifndef SQLITE_OMIT_ALTERTABLE
  81640. sqlite3AlterFunctions();
  81641. #endif
  81642. }
  81643. /************** End of func.c ************************************************/
  81644. /************** Begin file fkey.c ********************************************/
  81645. /*
  81646. **
  81647. ** The author disclaims copyright to this source code. In place of
  81648. ** a legal notice, here is a blessing:
  81649. **
  81650. ** May you do good and not evil.
  81651. ** May you find forgiveness for yourself and forgive others.
  81652. ** May you share freely, never taking more than you give.
  81653. **
  81654. *************************************************************************
  81655. ** This file contains code used by the compiler to add foreign key
  81656. ** support to compiled SQL statements.
  81657. */
  81658. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81659. #ifndef SQLITE_OMIT_TRIGGER
  81660. /*
  81661. ** Deferred and Immediate FKs
  81662. ** --------------------------
  81663. **
  81664. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  81665. ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
  81666. ** is returned and the current statement transaction rolled back. If a
  81667. ** deferred foreign key constraint is violated, no action is taken
  81668. ** immediately. However if the application attempts to commit the
  81669. ** transaction before fixing the constraint violation, the attempt fails.
  81670. **
  81671. ** Deferred constraints are implemented using a simple counter associated
  81672. ** with the database handle. The counter is set to zero each time a
  81673. ** database transaction is opened. Each time a statement is executed
  81674. ** that causes a foreign key violation, the counter is incremented. Each
  81675. ** time a statement is executed that removes an existing violation from
  81676. ** the database, the counter is decremented. When the transaction is
  81677. ** committed, the commit fails if the current value of the counter is
  81678. ** greater than zero. This scheme has two big drawbacks:
  81679. **
  81680. ** * When a commit fails due to a deferred foreign key constraint,
  81681. ** there is no way to tell which foreign constraint is not satisfied,
  81682. ** or which row it is not satisfied for.
  81683. **
  81684. ** * If the database contains foreign key violations when the
  81685. ** transaction is opened, this may cause the mechanism to malfunction.
  81686. **
  81687. ** Despite these problems, this approach is adopted as it seems simpler
  81688. ** than the alternatives.
  81689. **
  81690. ** INSERT operations:
  81691. **
  81692. ** I.1) For each FK for which the table is the child table, search
  81693. ** the parent table for a match. If none is found increment the
  81694. ** constraint counter.
  81695. **
  81696. ** I.2) For each FK for which the table is the parent table,
  81697. ** search the child table for rows that correspond to the new
  81698. ** row in the parent table. Decrement the counter for each row
  81699. ** found (as the constraint is now satisfied).
  81700. **
  81701. ** DELETE operations:
  81702. **
  81703. ** D.1) For each FK for which the table is the child table,
  81704. ** search the parent table for a row that corresponds to the
  81705. ** deleted row in the child table. If such a row is not found,
  81706. ** decrement the counter.
  81707. **
  81708. ** D.2) For each FK for which the table is the parent table, search
  81709. ** the child table for rows that correspond to the deleted row
  81710. ** in the parent table. For each found increment the counter.
  81711. **
  81712. ** UPDATE operations:
  81713. **
  81714. ** An UPDATE command requires that all 4 steps above are taken, but only
  81715. ** for FK constraints for which the affected columns are actually
  81716. ** modified (values must be compared at runtime).
  81717. **
  81718. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  81719. ** This simplifies the implementation a bit.
  81720. **
  81721. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  81722. ** resolution is considered to delete rows before the new row is inserted.
  81723. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  81724. ** is thrown, even if the FK constraint would be satisfied after the new
  81725. ** row is inserted.
  81726. **
  81727. ** Immediate constraints are usually handled similarly. The only difference
  81728. ** is that the counter used is stored as part of each individual statement
  81729. ** object (struct Vdbe). If, after the statement has run, its immediate
  81730. ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
  81731. ** and the statement transaction is rolled back. An exception is an INSERT
  81732. ** statement that inserts a single row only (no triggers). In this case,
  81733. ** instead of using a counter, an exception is thrown immediately if the
  81734. ** INSERT violates a foreign key constraint. This is necessary as such
  81735. ** an INSERT does not open a statement transaction.
  81736. **
  81737. ** TODO: How should dropping a table be handled? How should renaming a
  81738. ** table be handled?
  81739. **
  81740. **
  81741. ** Query API Notes
  81742. ** ---------------
  81743. **
  81744. ** Before coding an UPDATE or DELETE row operation, the code-generator
  81745. ** for those two operations needs to know whether or not the operation
  81746. ** requires any FK processing and, if so, which columns of the original
  81747. ** row are required by the FK processing VDBE code (i.e. if FKs were
  81748. ** implemented using triggers, which of the old.* columns would be
  81749. ** accessed). No information is required by the code-generator before
  81750. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  81751. ** generation code to query for this information are:
  81752. **
  81753. ** sqlite3FkRequired() - Test to see if FK processing is required.
  81754. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  81755. **
  81756. **
  81757. ** Externally accessible module functions
  81758. ** --------------------------------------
  81759. **
  81760. ** sqlite3FkCheck() - Check for foreign key violations.
  81761. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  81762. ** sqlite3FkDelete() - Delete an FKey structure.
  81763. */
  81764. /*
  81765. ** VDBE Calling Convention
  81766. ** -----------------------
  81767. **
  81768. ** Example:
  81769. **
  81770. ** For the following INSERT statement:
  81771. **
  81772. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  81773. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  81774. **
  81775. ** Register (x): 2 (type integer)
  81776. ** Register (x+1): 1 (type integer)
  81777. ** Register (x+2): NULL (type NULL)
  81778. ** Register (x+3): 3.1 (type real)
  81779. */
  81780. /*
  81781. ** A foreign key constraint requires that the key columns in the parent
  81782. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  81783. ** Given that pParent is the parent table for foreign key constraint pFKey,
  81784. ** search the schema a unique index on the parent key columns.
  81785. **
  81786. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  81787. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  81788. ** is set to point to the unique index.
  81789. **
  81790. ** If the parent key consists of a single column (the foreign key constraint
  81791. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  81792. ** Otherwise, it is set to point to an allocated array of size N, where
  81793. ** N is the number of columns in the parent key. The first element of the
  81794. ** array is the index of the child table column that is mapped by the FK
  81795. ** constraint to the parent table column stored in the left-most column
  81796. ** of index *ppIdx. The second element of the array is the index of the
  81797. ** child table column that corresponds to the second left-most column of
  81798. ** *ppIdx, and so on.
  81799. **
  81800. ** If the required index cannot be found, either because:
  81801. **
  81802. ** 1) The named parent key columns do not exist, or
  81803. **
  81804. ** 2) The named parent key columns do exist, but are not subject to a
  81805. ** UNIQUE or PRIMARY KEY constraint, or
  81806. **
  81807. ** 3) No parent key columns were provided explicitly as part of the
  81808. ** foreign key definition, and the parent table does not have a
  81809. ** PRIMARY KEY, or
  81810. **
  81811. ** 4) No parent key columns were provided explicitly as part of the
  81812. ** foreign key definition, and the PRIMARY KEY of the parent table
  81813. ** consists of a a different number of columns to the child key in
  81814. ** the child table.
  81815. **
  81816. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  81817. ** into pParse. If an OOM error occurs, non-zero is returned and the
  81818. ** pParse->db->mallocFailed flag is set.
  81819. */
  81820. static int locateFkeyIndex(
  81821. Parse *pParse, /* Parse context to store any error in */
  81822. Table *pParent, /* Parent table of FK constraint pFKey */
  81823. FKey *pFKey, /* Foreign key to find index for */
  81824. Index **ppIdx, /* OUT: Unique index on parent table */
  81825. int **paiCol /* OUT: Map of index columns in pFKey */
  81826. ){
  81827. Index *pIdx = 0; /* Value to return via *ppIdx */
  81828. int *aiCol = 0; /* Value to return via *paiCol */
  81829. int nCol = pFKey->nCol; /* Number of columns in parent key */
  81830. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  81831. /* The caller is responsible for zeroing output parameters. */
  81832. assert( ppIdx && *ppIdx==0 );
  81833. assert( !paiCol || *paiCol==0 );
  81834. assert( pParse );
  81835. /* If this is a non-composite (single column) foreign key, check if it
  81836. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  81837. ** and *paiCol set to zero and return early.
  81838. **
  81839. ** Otherwise, for a composite foreign key (more than one column), allocate
  81840. ** space for the aiCol array (returned via output parameter *paiCol).
  81841. ** Non-composite foreign keys do not require the aiCol array.
  81842. */
  81843. if( nCol==1 ){
  81844. /* The FK maps to the IPK if any of the following are true:
  81845. **
  81846. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  81847. ** mapped to the primary key of table pParent, or
  81848. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  81849. ** PRIMARY KEY.
  81850. */
  81851. if( pParent->iPKey>=0 ){
  81852. if( !zKey ) return 0;
  81853. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  81854. }
  81855. }else if( paiCol ){
  81856. assert( nCol>1 );
  81857. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  81858. if( !aiCol ) return 1;
  81859. *paiCol = aiCol;
  81860. }
  81861. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  81862. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  81863. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  81864. ** of columns. If each indexed column corresponds to a foreign key
  81865. ** column of pFKey, then this index is a winner. */
  81866. if( zKey==0 ){
  81867. /* If zKey is NULL, then this foreign key is implicitly mapped to
  81868. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  81869. ** identified by the test (Index.autoIndex==2). */
  81870. if( pIdx->autoIndex==2 ){
  81871. if( aiCol ){
  81872. int i;
  81873. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  81874. }
  81875. break;
  81876. }
  81877. }else{
  81878. /* If zKey is non-NULL, then this foreign key was declared to
  81879. ** map to an explicit list of columns in table pParent. Check if this
  81880. ** index matches those columns. Also, check that the index uses
  81881. ** the default collation sequences for each column. */
  81882. int i, j;
  81883. for(i=0; i<nCol; i++){
  81884. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  81885. char *zDfltColl; /* Def. collation for column */
  81886. char *zIdxCol; /* Name of indexed column */
  81887. /* If the index uses a collation sequence that is different from
  81888. ** the default collation sequence for the column, this index is
  81889. ** unusable. Bail out early in this case. */
  81890. zDfltColl = pParent->aCol[iCol].zColl;
  81891. if( !zDfltColl ){
  81892. zDfltColl = "BINARY";
  81893. }
  81894. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  81895. zIdxCol = pParent->aCol[iCol].zName;
  81896. for(j=0; j<nCol; j++){
  81897. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  81898. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  81899. break;
  81900. }
  81901. }
  81902. if( j==nCol ) break;
  81903. }
  81904. if( i==nCol ) break; /* pIdx is usable */
  81905. }
  81906. }
  81907. }
  81908. if( !pIdx ){
  81909. if( !pParse->disableTriggers ){
  81910. sqlite3ErrorMsg(pParse, "foreign key mismatch");
  81911. }
  81912. sqlite3DbFree(pParse->db, aiCol);
  81913. return 1;
  81914. }
  81915. *ppIdx = pIdx;
  81916. return 0;
  81917. }
  81918. /*
  81919. ** This function is called when a row is inserted into or deleted from the
  81920. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  81921. ** on the child table of pFKey, this function is invoked twice for each row
  81922. ** affected - once to "delete" the old row, and then again to "insert" the
  81923. ** new row.
  81924. **
  81925. ** Each time it is called, this function generates VDBE code to locate the
  81926. ** row in the parent table that corresponds to the row being inserted into
  81927. ** or deleted from the child table. If the parent row can be found, no
  81928. ** special action is taken. Otherwise, if the parent row can *not* be
  81929. ** found in the parent table:
  81930. **
  81931. ** Operation | FK type | Action taken
  81932. ** --------------------------------------------------------------------------
  81933. ** INSERT immediate Increment the "immediate constraint counter".
  81934. **
  81935. ** DELETE immediate Decrement the "immediate constraint counter".
  81936. **
  81937. ** INSERT deferred Increment the "deferred constraint counter".
  81938. **
  81939. ** DELETE deferred Decrement the "deferred constraint counter".
  81940. **
  81941. ** These operations are identified in the comment at the top of this file
  81942. ** (fkey.c) as "I.1" and "D.1".
  81943. */
  81944. static void fkLookupParent(
  81945. Parse *pParse, /* Parse context */
  81946. int iDb, /* Index of database housing pTab */
  81947. Table *pTab, /* Parent table of FK pFKey */
  81948. Index *pIdx, /* Unique index on parent key columns in pTab */
  81949. FKey *pFKey, /* Foreign key constraint */
  81950. int *aiCol, /* Map from parent key columns to child table columns */
  81951. int regData, /* Address of array containing child table row */
  81952. int nIncr, /* Increment constraint counter by this */
  81953. int isIgnore /* If true, pretend pTab contains all NULL values */
  81954. ){
  81955. int i; /* Iterator variable */
  81956. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  81957. int iCur = pParse->nTab - 1; /* Cursor number to use */
  81958. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  81959. /* If nIncr is less than zero, then check at runtime if there are any
  81960. ** outstanding constraints to resolve. If there are not, there is no need
  81961. ** to check if deleting this row resolves any outstanding violations.
  81962. **
  81963. ** Check if any of the key columns in the child table row are NULL. If
  81964. ** any are, then the constraint is considered satisfied. No need to
  81965. ** search for a matching row in the parent table. */
  81966. if( nIncr<0 ){
  81967. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  81968. }
  81969. for(i=0; i<pFKey->nCol; i++){
  81970. int iReg = aiCol[i] + regData + 1;
  81971. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  81972. }
  81973. if( isIgnore==0 ){
  81974. if( pIdx==0 ){
  81975. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  81976. ** column of the parent table (table pTab). */
  81977. int iMustBeInt; /* Address of MustBeInt instruction */
  81978. int regTemp = sqlite3GetTempReg(pParse);
  81979. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  81980. ** apply the affinity of the parent key). If this fails, then there
  81981. ** is no matching parent key. Before using MustBeInt, make a copy of
  81982. ** the value. Otherwise, the value inserted into the child key column
  81983. ** will have INTEGER affinity applied to it, which may not be correct. */
  81984. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  81985. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  81986. /* If the parent table is the same as the child table, and we are about
  81987. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  81988. ** then check if the row being inserted matches itself. If so, do not
  81989. ** increment the constraint-counter. */
  81990. if( pTab==pFKey->pFrom && nIncr==1 ){
  81991. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  81992. }
  81993. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  81994. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  81995. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  81996. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  81997. sqlite3VdbeJumpHere(v, iMustBeInt);
  81998. sqlite3ReleaseTempReg(pParse, regTemp);
  81999. }else{
  82000. int nCol = pFKey->nCol;
  82001. int regTemp = sqlite3GetTempRange(pParse, nCol);
  82002. int regRec = sqlite3GetTempReg(pParse);
  82003. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  82004. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  82005. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  82006. for(i=0; i<nCol; i++){
  82007. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  82008. }
  82009. /* If the parent table is the same as the child table, and we are about
  82010. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  82011. ** then check if the row being inserted matches itself. If so, do not
  82012. ** increment the constraint-counter.
  82013. **
  82014. ** If any of the parent-key values are NULL, then the row cannot match
  82015. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  82016. ** of the parent-key values are NULL (at this point it is known that
  82017. ** none of the child key values are).
  82018. */
  82019. if( pTab==pFKey->pFrom && nIncr==1 ){
  82020. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  82021. for(i=0; i<nCol; i++){
  82022. int iChild = aiCol[i]+1+regData;
  82023. int iParent = pIdx->aiColumn[i]+1+regData;
  82024. assert( aiCol[i]!=pTab->iPKey );
  82025. if( pIdx->aiColumn[i]==pTab->iPKey ){
  82026. /* The parent key is a composite key that includes the IPK column */
  82027. iParent = regData;
  82028. }
  82029. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  82030. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  82031. }
  82032. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  82033. }
  82034. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  82035. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  82036. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  82037. sqlite3ReleaseTempReg(pParse, regRec);
  82038. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  82039. }
  82040. }
  82041. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  82042. /* Special case: If this is an INSERT statement that will insert exactly
  82043. ** one row into the table, raise a constraint immediately instead of
  82044. ** incrementing a counter. This is necessary as the VM code is being
  82045. ** generated for will not open a statement transaction. */
  82046. assert( nIncr==1 );
  82047. sqlite3HaltConstraint(
  82048. pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
  82049. );
  82050. }else{
  82051. if( nIncr>0 && pFKey->isDeferred==0 ){
  82052. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  82053. }
  82054. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  82055. }
  82056. sqlite3VdbeResolveLabel(v, iOk);
  82057. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  82058. }
  82059. /*
  82060. ** This function is called to generate code executed when a row is deleted
  82061. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  82062. ** deferred, when a row is inserted into the same table. When generating
  82063. ** code for an SQL UPDATE operation, this function may be called twice -
  82064. ** once to "delete" the old row and once to "insert" the new row.
  82065. **
  82066. ** The code generated by this function scans through the rows in the child
  82067. ** table that correspond to the parent table row being deleted or inserted.
  82068. ** For each child row found, one of the following actions is taken:
  82069. **
  82070. ** Operation | FK type | Action taken
  82071. ** --------------------------------------------------------------------------
  82072. ** DELETE immediate Increment the "immediate constraint counter".
  82073. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  82074. ** throw a "foreign key constraint failed" exception.
  82075. **
  82076. ** INSERT immediate Decrement the "immediate constraint counter".
  82077. **
  82078. ** DELETE deferred Increment the "deferred constraint counter".
  82079. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  82080. ** throw a "foreign key constraint failed" exception.
  82081. **
  82082. ** INSERT deferred Decrement the "deferred constraint counter".
  82083. **
  82084. ** These operations are identified in the comment at the top of this file
  82085. ** (fkey.c) as "I.2" and "D.2".
  82086. */
  82087. static void fkScanChildren(
  82088. Parse *pParse, /* Parse context */
  82089. SrcList *pSrc, /* SrcList containing the table to scan */
  82090. Table *pTab,
  82091. Index *pIdx, /* Foreign key index */
  82092. FKey *pFKey, /* Foreign key relationship */
  82093. int *aiCol, /* Map from pIdx cols to child table cols */
  82094. int regData, /* Referenced table data starts here */
  82095. int nIncr /* Amount to increment deferred counter by */
  82096. ){
  82097. sqlite3 *db = pParse->db; /* Database handle */
  82098. int i; /* Iterator variable */
  82099. Expr *pWhere = 0; /* WHERE clause to scan with */
  82100. NameContext sNameContext; /* Context used to resolve WHERE clause */
  82101. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  82102. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  82103. Vdbe *v = sqlite3GetVdbe(pParse);
  82104. assert( !pIdx || pIdx->pTable==pTab );
  82105. if( nIncr<0 ){
  82106. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  82107. }
  82108. /* Create an Expr object representing an SQL expression like:
  82109. **
  82110. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  82111. **
  82112. ** The collation sequence used for the comparison should be that of
  82113. ** the parent key columns. The affinity of the parent key column should
  82114. ** be applied to each child key value before the comparison takes place.
  82115. */
  82116. for(i=0; i<pFKey->nCol; i++){
  82117. Expr *pLeft; /* Value from parent table row */
  82118. Expr *pRight; /* Column ref to child table */
  82119. Expr *pEq; /* Expression (pLeft = pRight) */
  82120. int iCol; /* Index of column in child table */
  82121. const char *zCol; /* Name of column in child table */
  82122. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  82123. if( pLeft ){
  82124. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  82125. ** expression to the parent key column defaults. */
  82126. if( pIdx ){
  82127. Column *pCol;
  82128. const char *zColl;
  82129. iCol = pIdx->aiColumn[i];
  82130. pCol = &pTab->aCol[iCol];
  82131. if( pTab->iPKey==iCol ) iCol = -1;
  82132. pLeft->iTable = regData+iCol+1;
  82133. pLeft->affinity = pCol->affinity;
  82134. zColl = pCol->zColl;
  82135. if( zColl==0 ) zColl = db->pDfltColl->zName;
  82136. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  82137. }else{
  82138. pLeft->iTable = regData;
  82139. pLeft->affinity = SQLITE_AFF_INTEGER;
  82140. }
  82141. }
  82142. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  82143. assert( iCol>=0 );
  82144. zCol = pFKey->pFrom->aCol[iCol].zName;
  82145. pRight = sqlite3Expr(db, TK_ID, zCol);
  82146. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  82147. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  82148. }
  82149. /* If the child table is the same as the parent table, and this scan
  82150. ** is taking place as part of a DELETE operation (operation D.2), omit the
  82151. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  82152. ** clause, where $rowid is the rowid of the row being deleted. */
  82153. if( pTab==pFKey->pFrom && nIncr>0 ){
  82154. Expr *pEq; /* Expression (pLeft = pRight) */
  82155. Expr *pLeft; /* Value from parent table row */
  82156. Expr *pRight; /* Column ref to child table */
  82157. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  82158. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  82159. if( pLeft && pRight ){
  82160. pLeft->iTable = regData;
  82161. pLeft->affinity = SQLITE_AFF_INTEGER;
  82162. pRight->iTable = pSrc->a[0].iCursor;
  82163. pRight->iColumn = -1;
  82164. }
  82165. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  82166. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  82167. }
  82168. /* Resolve the references in the WHERE clause. */
  82169. memset(&sNameContext, 0, sizeof(NameContext));
  82170. sNameContext.pSrcList = pSrc;
  82171. sNameContext.pParse = pParse;
  82172. sqlite3ResolveExprNames(&sNameContext, pWhere);
  82173. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  82174. ** clause. If the constraint is not deferred, throw an exception for
  82175. ** each row found. Otherwise, for deferred constraints, increment the
  82176. ** deferred constraint counter by nIncr for each row selected. */
  82177. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  82178. if( nIncr>0 && pFKey->isDeferred==0 ){
  82179. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  82180. }
  82181. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  82182. if( pWInfo ){
  82183. sqlite3WhereEnd(pWInfo);
  82184. }
  82185. /* Clean up the WHERE clause constructed above. */
  82186. sqlite3ExprDelete(db, pWhere);
  82187. if( iFkIfZero ){
  82188. sqlite3VdbeJumpHere(v, iFkIfZero);
  82189. }
  82190. }
  82191. /*
  82192. ** This function returns a pointer to the head of a linked list of FK
  82193. ** constraints for which table pTab is the parent table. For example,
  82194. ** given the following schema:
  82195. **
  82196. ** CREATE TABLE t1(a PRIMARY KEY);
  82197. ** CREATE TABLE t2(b REFERENCES t1(a);
  82198. **
  82199. ** Calling this function with table "t1" as an argument returns a pointer
  82200. ** to the FKey structure representing the foreign key constraint on table
  82201. ** "t2". Calling this function with "t2" as the argument would return a
  82202. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  82203. ** table).
  82204. */
  82205. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  82206. int nName = sqlite3Strlen30(pTab->zName);
  82207. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  82208. }
  82209. /*
  82210. ** The second argument is a Trigger structure allocated by the
  82211. ** fkActionTrigger() routine. This function deletes the Trigger structure
  82212. ** and all of its sub-components.
  82213. **
  82214. ** The Trigger structure or any of its sub-components may be allocated from
  82215. ** the lookaside buffer belonging to database handle dbMem.
  82216. */
  82217. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  82218. if( p ){
  82219. TriggerStep *pStep = p->step_list;
  82220. sqlite3ExprDelete(dbMem, pStep->pWhere);
  82221. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  82222. sqlite3SelectDelete(dbMem, pStep->pSelect);
  82223. sqlite3ExprDelete(dbMem, p->pWhen);
  82224. sqlite3DbFree(dbMem, p);
  82225. }
  82226. }
  82227. /*
  82228. ** This function is called to generate code that runs when table pTab is
  82229. ** being dropped from the database. The SrcList passed as the second argument
  82230. ** to this function contains a single entry guaranteed to resolve to
  82231. ** table pTab.
  82232. **
  82233. ** Normally, no code is required. However, if either
  82234. **
  82235. ** (a) The table is the parent table of a FK constraint, or
  82236. ** (b) The table is the child table of a deferred FK constraint and it is
  82237. ** determined at runtime that there are outstanding deferred FK
  82238. ** constraint violations in the database,
  82239. **
  82240. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  82241. ** the table from the database. Triggers are disabled while running this
  82242. ** DELETE, but foreign key actions are not.
  82243. */
  82244. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  82245. sqlite3 *db = pParse->db;
  82246. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  82247. int iSkip = 0;
  82248. Vdbe *v = sqlite3GetVdbe(pParse);
  82249. assert( v ); /* VDBE has already been allocated */
  82250. if( sqlite3FkReferences(pTab)==0 ){
  82251. /* Search for a deferred foreign key constraint for which this table
  82252. ** is the child table. If one cannot be found, return without
  82253. ** generating any VDBE code. If one can be found, then jump over
  82254. ** the entire DELETE if there are no outstanding deferred constraints
  82255. ** when this statement is run. */
  82256. FKey *p;
  82257. for(p=pTab->pFKey; p; p=p->pNextFrom){
  82258. if( p->isDeferred ) break;
  82259. }
  82260. if( !p ) return;
  82261. iSkip = sqlite3VdbeMakeLabel(v);
  82262. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  82263. }
  82264. pParse->disableTriggers = 1;
  82265. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  82266. pParse->disableTriggers = 0;
  82267. /* If the DELETE has generated immediate foreign key constraint
  82268. ** violations, halt the VDBE and return an error at this point, before
  82269. ** any modifications to the schema are made. This is because statement
  82270. ** transactions are not able to rollback schema changes. */
  82271. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  82272. sqlite3HaltConstraint(
  82273. pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
  82274. );
  82275. if( iSkip ){
  82276. sqlite3VdbeResolveLabel(v, iSkip);
  82277. }
  82278. }
  82279. }
  82280. /*
  82281. ** This function is called when inserting, deleting or updating a row of
  82282. ** table pTab to generate VDBE code to perform foreign key constraint
  82283. ** processing for the operation.
  82284. **
  82285. ** For a DELETE operation, parameter regOld is passed the index of the
  82286. ** first register in an array of (pTab->nCol+1) registers containing the
  82287. ** rowid of the row being deleted, followed by each of the column values
  82288. ** of the row being deleted, from left to right. Parameter regNew is passed
  82289. ** zero in this case.
  82290. **
  82291. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  82292. ** first register of an array of (pTab->nCol+1) registers containing the new
  82293. ** row data.
  82294. **
  82295. ** For an UPDATE operation, this function is called twice. Once before
  82296. ** the original record is deleted from the table using the calling convention
  82297. ** described for DELETE. Then again after the original record is deleted
  82298. ** but before the new record is inserted using the INSERT convention.
  82299. */
  82300. SQLITE_PRIVATE void sqlite3FkCheck(
  82301. Parse *pParse, /* Parse context */
  82302. Table *pTab, /* Row is being deleted from this table */
  82303. int regOld, /* Previous row data is stored here */
  82304. int regNew /* New row data is stored here */
  82305. ){
  82306. sqlite3 *db = pParse->db; /* Database handle */
  82307. FKey *pFKey; /* Used to iterate through FKs */
  82308. int iDb; /* Index of database containing pTab */
  82309. const char *zDb; /* Name of database containing pTab */
  82310. int isIgnoreErrors = pParse->disableTriggers;
  82311. /* Exactly one of regOld and regNew should be non-zero. */
  82312. assert( (regOld==0)!=(regNew==0) );
  82313. /* If foreign-keys are disabled, this function is a no-op. */
  82314. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  82315. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  82316. zDb = db->aDb[iDb].zName;
  82317. /* Loop through all the foreign key constraints for which pTab is the
  82318. ** child table (the table that the foreign key definition is part of). */
  82319. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  82320. Table *pTo; /* Parent table of foreign key pFKey */
  82321. Index *pIdx = 0; /* Index on key columns in pTo */
  82322. int *aiFree = 0;
  82323. int *aiCol;
  82324. int iCol;
  82325. int i;
  82326. int isIgnore = 0;
  82327. /* Find the parent table of this foreign key. Also find a unique index
  82328. ** on the parent key columns in the parent table. If either of these
  82329. ** schema items cannot be located, set an error in pParse and return
  82330. ** early. */
  82331. if( pParse->disableTriggers ){
  82332. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  82333. }else{
  82334. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  82335. }
  82336. if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  82337. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  82338. if( !isIgnoreErrors || db->mallocFailed ) return;
  82339. if( pTo==0 ){
  82340. /* If isIgnoreErrors is true, then a table is being dropped. In this
  82341. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  82342. ** before actually dropping it in order to check FK constraints.
  82343. ** If the parent table of an FK constraint on the current table is
  82344. ** missing, behave as if it is empty. i.e. decrement the relevant
  82345. ** FK counter for each row of the current table with non-NULL keys.
  82346. */
  82347. Vdbe *v = sqlite3GetVdbe(pParse);
  82348. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  82349. for(i=0; i<pFKey->nCol; i++){
  82350. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  82351. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  82352. }
  82353. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  82354. }
  82355. continue;
  82356. }
  82357. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  82358. if( aiFree ){
  82359. aiCol = aiFree;
  82360. }else{
  82361. iCol = pFKey->aCol[0].iFrom;
  82362. aiCol = &iCol;
  82363. }
  82364. for(i=0; i<pFKey->nCol; i++){
  82365. if( aiCol[i]==pTab->iPKey ){
  82366. aiCol[i] = -1;
  82367. }
  82368. #ifndef SQLITE_OMIT_AUTHORIZATION
  82369. /* Request permission to read the parent key columns. If the
  82370. ** authorization callback returns SQLITE_IGNORE, behave as if any
  82371. ** values read from the parent table are NULL. */
  82372. if( db->xAuth ){
  82373. int rcauth;
  82374. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  82375. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  82376. isIgnore = (rcauth==SQLITE_IGNORE);
  82377. }
  82378. #endif
  82379. }
  82380. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  82381. ** a cursor to use to search the unique index on the parent key columns
  82382. ** in the parent table. */
  82383. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  82384. pParse->nTab++;
  82385. if( regOld!=0 ){
  82386. /* A row is being removed from the child table. Search for the parent.
  82387. ** If the parent does not exist, removing the child row resolves an
  82388. ** outstanding foreign key constraint violation. */
  82389. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  82390. }
  82391. if( regNew!=0 ){
  82392. /* A row is being added to the child table. If a parent row cannot
  82393. ** be found, adding the child row has violated the FK constraint. */
  82394. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  82395. }
  82396. sqlite3DbFree(db, aiFree);
  82397. }
  82398. /* Loop through all the foreign key constraints that refer to this table */
  82399. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  82400. Index *pIdx = 0; /* Foreign key index for pFKey */
  82401. SrcList *pSrc;
  82402. int *aiCol = 0;
  82403. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  82404. assert( regOld==0 && regNew!=0 );
  82405. /* Inserting a single row into a parent table cannot cause an immediate
  82406. ** foreign key violation. So do nothing in this case. */
  82407. continue;
  82408. }
  82409. if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  82410. if( !isIgnoreErrors || db->mallocFailed ) return;
  82411. continue;
  82412. }
  82413. assert( aiCol || pFKey->nCol==1 );
  82414. /* Create a SrcList structure containing a single table (the table
  82415. ** the foreign key that refers to this table is attached to). This
  82416. ** is required for the sqlite3WhereXXX() interface. */
  82417. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  82418. if( pSrc ){
  82419. struct SrcList_item *pItem = pSrc->a;
  82420. pItem->pTab = pFKey->pFrom;
  82421. pItem->zName = pFKey->pFrom->zName;
  82422. pItem->pTab->nRef++;
  82423. pItem->iCursor = pParse->nTab++;
  82424. if( regNew!=0 ){
  82425. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  82426. }
  82427. if( regOld!=0 ){
  82428. /* If there is a RESTRICT action configured for the current operation
  82429. ** on the parent table of this FK, then throw an exception
  82430. ** immediately if the FK constraint is violated, even if this is a
  82431. ** deferred trigger. That's what RESTRICT means. To defer checking
  82432. ** the constraint, the FK should specify NO ACTION (represented
  82433. ** using OE_None). NO ACTION is the default. */
  82434. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  82435. }
  82436. pItem->zName = 0;
  82437. sqlite3SrcListDelete(db, pSrc);
  82438. }
  82439. sqlite3DbFree(db, aiCol);
  82440. }
  82441. }
  82442. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  82443. /*
  82444. ** This function is called before generating code to update or delete a
  82445. ** row contained in table pTab.
  82446. */
  82447. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  82448. Parse *pParse, /* Parse context */
  82449. Table *pTab /* Table being modified */
  82450. ){
  82451. u32 mask = 0;
  82452. if( pParse->db->flags&SQLITE_ForeignKeys ){
  82453. FKey *p;
  82454. int i;
  82455. for(p=pTab->pFKey; p; p=p->pNextFrom){
  82456. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  82457. }
  82458. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  82459. Index *pIdx = 0;
  82460. locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
  82461. if( pIdx ){
  82462. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  82463. }
  82464. }
  82465. }
  82466. return mask;
  82467. }
  82468. /*
  82469. ** This function is called before generating code to update or delete a
  82470. ** row contained in table pTab. If the operation is a DELETE, then
  82471. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  82472. ** to an array of size N, where N is the number of columns in table pTab.
  82473. ** If the i'th column is not modified by the UPDATE, then the corresponding
  82474. ** entry in the aChange[] array is set to -1. If the column is modified,
  82475. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  82476. ** UPDATE statement modifies the rowid fields of the table.
  82477. **
  82478. ** If any foreign key processing will be required, this function returns
  82479. ** true. If there is no foreign key related processing, this function
  82480. ** returns false.
  82481. */
  82482. SQLITE_PRIVATE int sqlite3FkRequired(
  82483. Parse *pParse, /* Parse context */
  82484. Table *pTab, /* Table being modified */
  82485. int *aChange, /* Non-NULL for UPDATE operations */
  82486. int chngRowid /* True for UPDATE that affects rowid */
  82487. ){
  82488. if( pParse->db->flags&SQLITE_ForeignKeys ){
  82489. if( !aChange ){
  82490. /* A DELETE operation. Foreign key processing is required if the
  82491. ** table in question is either the child or parent table for any
  82492. ** foreign key constraint. */
  82493. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  82494. }else{
  82495. /* This is an UPDATE. Foreign key processing is only required if the
  82496. ** operation modifies one or more child or parent key columns. */
  82497. int i;
  82498. FKey *p;
  82499. /* Check if any child key columns are being modified. */
  82500. for(p=pTab->pFKey; p; p=p->pNextFrom){
  82501. for(i=0; i<p->nCol; i++){
  82502. int iChildKey = p->aCol[i].iFrom;
  82503. if( aChange[iChildKey]>=0 ) return 1;
  82504. if( iChildKey==pTab->iPKey && chngRowid ) return 1;
  82505. }
  82506. }
  82507. /* Check if any parent key columns are being modified. */
  82508. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  82509. for(i=0; i<p->nCol; i++){
  82510. char *zKey = p->aCol[i].zCol;
  82511. int iKey;
  82512. for(iKey=0; iKey<pTab->nCol; iKey++){
  82513. Column *pCol = &pTab->aCol[iKey];
  82514. if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
  82515. : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
  82516. if( aChange[iKey]>=0 ) return 1;
  82517. if( iKey==pTab->iPKey && chngRowid ) return 1;
  82518. }
  82519. }
  82520. }
  82521. }
  82522. }
  82523. }
  82524. return 0;
  82525. }
  82526. /*
  82527. ** This function is called when an UPDATE or DELETE operation is being
  82528. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  82529. ** If the current operation is an UPDATE, then the pChanges parameter is
  82530. ** passed a pointer to the list of columns being modified. If it is a
  82531. ** DELETE, pChanges is passed a NULL pointer.
  82532. **
  82533. ** It returns a pointer to a Trigger structure containing a trigger
  82534. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  82535. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  82536. ** returned (these actions require no special handling by the triggers
  82537. ** sub-system, code for them is created by fkScanChildren()).
  82538. **
  82539. ** For example, if pFKey is the foreign key and pTab is table "p" in
  82540. ** the following schema:
  82541. **
  82542. ** CREATE TABLE p(pk PRIMARY KEY);
  82543. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  82544. **
  82545. ** then the returned trigger structure is equivalent to:
  82546. **
  82547. ** CREATE TRIGGER ... DELETE ON p BEGIN
  82548. ** DELETE FROM c WHERE ck = old.pk;
  82549. ** END;
  82550. **
  82551. ** The returned pointer is cached as part of the foreign key object. It
  82552. ** is eventually freed along with the rest of the foreign key object by
  82553. ** sqlite3FkDelete().
  82554. */
  82555. static Trigger *fkActionTrigger(
  82556. Parse *pParse, /* Parse context */
  82557. Table *pTab, /* Table being updated or deleted from */
  82558. FKey *pFKey, /* Foreign key to get action for */
  82559. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  82560. ){
  82561. sqlite3 *db = pParse->db; /* Database handle */
  82562. int action; /* One of OE_None, OE_Cascade etc. */
  82563. Trigger *pTrigger; /* Trigger definition to return */
  82564. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  82565. action = pFKey->aAction[iAction];
  82566. pTrigger = pFKey->apTrigger[iAction];
  82567. if( action!=OE_None && !pTrigger ){
  82568. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  82569. char const *zFrom; /* Name of child table */
  82570. int nFrom; /* Length in bytes of zFrom */
  82571. Index *pIdx = 0; /* Parent key index for this FK */
  82572. int *aiCol = 0; /* child table cols -> parent key cols */
  82573. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  82574. Expr *pWhere = 0; /* WHERE clause of trigger step */
  82575. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  82576. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  82577. int i; /* Iterator variable */
  82578. Expr *pWhen = 0; /* WHEN clause for the trigger */
  82579. if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  82580. assert( aiCol || pFKey->nCol==1 );
  82581. for(i=0; i<pFKey->nCol; i++){
  82582. Token tOld = { "old", 3 }; /* Literal "old" token */
  82583. Token tNew = { "new", 3 }; /* Literal "new" token */
  82584. Token tFromCol; /* Name of column in child table */
  82585. Token tToCol; /* Name of column in parent table */
  82586. int iFromCol; /* Idx of column in child table */
  82587. Expr *pEq; /* tFromCol = OLD.tToCol */
  82588. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  82589. assert( iFromCol>=0 );
  82590. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  82591. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  82592. tToCol.n = sqlite3Strlen30(tToCol.z);
  82593. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  82594. /* Create the expression "OLD.zToCol = zFromCol". It is important
  82595. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  82596. ** that the affinity and collation sequence associated with the
  82597. ** parent table are used for the comparison. */
  82598. pEq = sqlite3PExpr(pParse, TK_EQ,
  82599. sqlite3PExpr(pParse, TK_DOT,
  82600. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  82601. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  82602. , 0),
  82603. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  82604. , 0);
  82605. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  82606. /* For ON UPDATE, construct the next term of the WHEN clause.
  82607. ** The final WHEN clause will be like this:
  82608. **
  82609. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  82610. */
  82611. if( pChanges ){
  82612. pEq = sqlite3PExpr(pParse, TK_IS,
  82613. sqlite3PExpr(pParse, TK_DOT,
  82614. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  82615. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  82616. 0),
  82617. sqlite3PExpr(pParse, TK_DOT,
  82618. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  82619. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  82620. 0),
  82621. 0);
  82622. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  82623. }
  82624. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  82625. Expr *pNew;
  82626. if( action==OE_Cascade ){
  82627. pNew = sqlite3PExpr(pParse, TK_DOT,
  82628. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  82629. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  82630. , 0);
  82631. }else if( action==OE_SetDflt ){
  82632. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  82633. if( pDflt ){
  82634. pNew = sqlite3ExprDup(db, pDflt, 0);
  82635. }else{
  82636. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  82637. }
  82638. }else{
  82639. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  82640. }
  82641. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  82642. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  82643. }
  82644. }
  82645. sqlite3DbFree(db, aiCol);
  82646. zFrom = pFKey->pFrom->zName;
  82647. nFrom = sqlite3Strlen30(zFrom);
  82648. if( action==OE_Restrict ){
  82649. Token tFrom;
  82650. Expr *pRaise;
  82651. tFrom.z = zFrom;
  82652. tFrom.n = nFrom;
  82653. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  82654. if( pRaise ){
  82655. pRaise->affinity = OE_Abort;
  82656. }
  82657. pSelect = sqlite3SelectNew(pParse,
  82658. sqlite3ExprListAppend(pParse, 0, pRaise),
  82659. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  82660. pWhere,
  82661. 0, 0, 0, 0, 0, 0
  82662. );
  82663. pWhere = 0;
  82664. }
  82665. /* Disable lookaside memory allocation */
  82666. enableLookaside = db->lookaside.bEnabled;
  82667. db->lookaside.bEnabled = 0;
  82668. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  82669. sizeof(Trigger) + /* struct Trigger */
  82670. sizeof(TriggerStep) + /* Single step in trigger program */
  82671. nFrom + 1 /* Space for pStep->target.z */
  82672. );
  82673. if( pTrigger ){
  82674. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  82675. pStep->target.z = (char *)&pStep[1];
  82676. pStep->target.n = nFrom;
  82677. memcpy((char *)pStep->target.z, zFrom, nFrom);
  82678. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  82679. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  82680. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  82681. if( pWhen ){
  82682. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  82683. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  82684. }
  82685. }
  82686. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  82687. db->lookaside.bEnabled = enableLookaside;
  82688. sqlite3ExprDelete(db, pWhere);
  82689. sqlite3ExprDelete(db, pWhen);
  82690. sqlite3ExprListDelete(db, pList);
  82691. sqlite3SelectDelete(db, pSelect);
  82692. if( db->mallocFailed==1 ){
  82693. fkTriggerDelete(db, pTrigger);
  82694. return 0;
  82695. }
  82696. assert( pStep!=0 );
  82697. switch( action ){
  82698. case OE_Restrict:
  82699. pStep->op = TK_SELECT;
  82700. break;
  82701. case OE_Cascade:
  82702. if( !pChanges ){
  82703. pStep->op = TK_DELETE;
  82704. break;
  82705. }
  82706. default:
  82707. pStep->op = TK_UPDATE;
  82708. }
  82709. pStep->pTrig = pTrigger;
  82710. pTrigger->pSchema = pTab->pSchema;
  82711. pTrigger->pTabSchema = pTab->pSchema;
  82712. pFKey->apTrigger[iAction] = pTrigger;
  82713. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  82714. }
  82715. return pTrigger;
  82716. }
  82717. /*
  82718. ** This function is called when deleting or updating a row to implement
  82719. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  82720. */
  82721. SQLITE_PRIVATE void sqlite3FkActions(
  82722. Parse *pParse, /* Parse context */
  82723. Table *pTab, /* Table being updated or deleted from */
  82724. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  82725. int regOld /* Address of array containing old row */
  82726. ){
  82727. /* If foreign-key support is enabled, iterate through all FKs that
  82728. ** refer to table pTab. If there is an action associated with the FK
  82729. ** for this operation (either update or delete), invoke the associated
  82730. ** trigger sub-program. */
  82731. if( pParse->db->flags&SQLITE_ForeignKeys ){
  82732. FKey *pFKey; /* Iterator variable */
  82733. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  82734. Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  82735. if( pAction ){
  82736. sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
  82737. }
  82738. }
  82739. }
  82740. }
  82741. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  82742. /*
  82743. ** Free all memory associated with foreign key definitions attached to
  82744. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  82745. ** hash table.
  82746. */
  82747. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  82748. FKey *pFKey; /* Iterator variable */
  82749. FKey *pNext; /* Copy of pFKey->pNextFrom */
  82750. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  82751. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  82752. /* Remove the FK from the fkeyHash hash table. */
  82753. if( !db || db->pnBytesFreed==0 ){
  82754. if( pFKey->pPrevTo ){
  82755. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  82756. }else{
  82757. void *p = (void *)pFKey->pNextTo;
  82758. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  82759. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  82760. }
  82761. if( pFKey->pNextTo ){
  82762. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  82763. }
  82764. }
  82765. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  82766. ** classified as either immediate or deferred.
  82767. */
  82768. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  82769. /* Delete any triggers created to implement actions for this FK. */
  82770. #ifndef SQLITE_OMIT_TRIGGER
  82771. fkTriggerDelete(db, pFKey->apTrigger[0]);
  82772. fkTriggerDelete(db, pFKey->apTrigger[1]);
  82773. #endif
  82774. pNext = pFKey->pNextFrom;
  82775. sqlite3DbFree(db, pFKey);
  82776. }
  82777. }
  82778. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  82779. /************** End of fkey.c ************************************************/
  82780. /************** Begin file insert.c ******************************************/
  82781. /*
  82782. ** 2001 September 15
  82783. **
  82784. ** The author disclaims copyright to this source code. In place of
  82785. ** a legal notice, here is a blessing:
  82786. **
  82787. ** May you do good and not evil.
  82788. ** May you find forgiveness for yourself and forgive others.
  82789. ** May you share freely, never taking more than you give.
  82790. **
  82791. *************************************************************************
  82792. ** This file contains C code routines that are called by the parser
  82793. ** to handle INSERT statements in SQLite.
  82794. */
  82795. /*
  82796. ** Generate code that will open a table for reading.
  82797. */
  82798. SQLITE_PRIVATE void sqlite3OpenTable(
  82799. Parse *p, /* Generate code into this VDBE */
  82800. int iCur, /* The cursor number of the table */
  82801. int iDb, /* The database index in sqlite3.aDb[] */
  82802. Table *pTab, /* The table to be opened */
  82803. int opcode /* OP_OpenRead or OP_OpenWrite */
  82804. ){
  82805. Vdbe *v;
  82806. assert( !IsVirtual(pTab) );
  82807. v = sqlite3GetVdbe(p);
  82808. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  82809. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  82810. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  82811. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  82812. VdbeComment((v, "%s", pTab->zName));
  82813. }
  82814. /*
  82815. ** Return a pointer to the column affinity string associated with index
  82816. ** pIdx. A column affinity string has one character for each column in
  82817. ** the table, according to the affinity of the column:
  82818. **
  82819. ** Character Column affinity
  82820. ** ------------------------------
  82821. ** 'a' TEXT
  82822. ** 'b' NONE
  82823. ** 'c' NUMERIC
  82824. ** 'd' INTEGER
  82825. ** 'e' REAL
  82826. **
  82827. ** An extra 'd' is appended to the end of the string to cover the
  82828. ** rowid that appears as the last column in every index.
  82829. **
  82830. ** Memory for the buffer containing the column index affinity string
  82831. ** is managed along with the rest of the Index structure. It will be
  82832. ** released when sqlite3DeleteIndex() is called.
  82833. */
  82834. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  82835. if( !pIdx->zColAff ){
  82836. /* The first time a column affinity string for a particular index is
  82837. ** required, it is allocated and populated here. It is then stored as
  82838. ** a member of the Index structure for subsequent use.
  82839. **
  82840. ** The column affinity string will eventually be deleted by
  82841. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  82842. ** up.
  82843. */
  82844. int n;
  82845. Table *pTab = pIdx->pTable;
  82846. sqlite3 *db = sqlite3VdbeDb(v);
  82847. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  82848. if( !pIdx->zColAff ){
  82849. db->mallocFailed = 1;
  82850. return 0;
  82851. }
  82852. for(n=0; n<pIdx->nColumn; n++){
  82853. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  82854. }
  82855. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  82856. pIdx->zColAff[n] = 0;
  82857. }
  82858. return pIdx->zColAff;
  82859. }
  82860. /*
  82861. ** Set P4 of the most recently inserted opcode to a column affinity
  82862. ** string for table pTab. A column affinity string has one character
  82863. ** for each column indexed by the index, according to the affinity of the
  82864. ** column:
  82865. **
  82866. ** Character Column affinity
  82867. ** ------------------------------
  82868. ** 'a' TEXT
  82869. ** 'b' NONE
  82870. ** 'c' NUMERIC
  82871. ** 'd' INTEGER
  82872. ** 'e' REAL
  82873. */
  82874. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  82875. /* The first time a column affinity string for a particular table
  82876. ** is required, it is allocated and populated here. It is then
  82877. ** stored as a member of the Table structure for subsequent use.
  82878. **
  82879. ** The column affinity string will eventually be deleted by
  82880. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  82881. */
  82882. if( !pTab->zColAff ){
  82883. char *zColAff;
  82884. int i;
  82885. sqlite3 *db = sqlite3VdbeDb(v);
  82886. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  82887. if( !zColAff ){
  82888. db->mallocFailed = 1;
  82889. return;
  82890. }
  82891. for(i=0; i<pTab->nCol; i++){
  82892. zColAff[i] = pTab->aCol[i].affinity;
  82893. }
  82894. zColAff[pTab->nCol] = '\0';
  82895. pTab->zColAff = zColAff;
  82896. }
  82897. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  82898. }
  82899. /*
  82900. ** Return non-zero if the table pTab in database iDb or any of its indices
  82901. ** have been opened at any point in the VDBE program beginning at location
  82902. ** iStartAddr throught the end of the program. This is used to see if
  82903. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  82904. ** run without using temporary table for the results of the SELECT.
  82905. */
  82906. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  82907. Vdbe *v = sqlite3GetVdbe(p);
  82908. int i;
  82909. int iEnd = sqlite3VdbeCurrentAddr(v);
  82910. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82911. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  82912. #endif
  82913. for(i=iStartAddr; i<iEnd; i++){
  82914. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  82915. assert( pOp!=0 );
  82916. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  82917. Index *pIndex;
  82918. int tnum = pOp->p2;
  82919. if( tnum==pTab->tnum ){
  82920. return 1;
  82921. }
  82922. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  82923. if( tnum==pIndex->tnum ){
  82924. return 1;
  82925. }
  82926. }
  82927. }
  82928. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82929. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  82930. assert( pOp->p4.pVtab!=0 );
  82931. assert( pOp->p4type==P4_VTAB );
  82932. return 1;
  82933. }
  82934. #endif
  82935. }
  82936. return 0;
  82937. }
  82938. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82939. /*
  82940. ** Locate or create an AutoincInfo structure associated with table pTab
  82941. ** which is in database iDb. Return the register number for the register
  82942. ** that holds the maximum rowid.
  82943. **
  82944. ** There is at most one AutoincInfo structure per table even if the
  82945. ** same table is autoincremented multiple times due to inserts within
  82946. ** triggers. A new AutoincInfo structure is created if this is the
  82947. ** first use of table pTab. On 2nd and subsequent uses, the original
  82948. ** AutoincInfo structure is used.
  82949. **
  82950. ** Three memory locations are allocated:
  82951. **
  82952. ** (1) Register to hold the name of the pTab table.
  82953. ** (2) Register to hold the maximum ROWID of pTab.
  82954. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  82955. **
  82956. ** The 2nd register is the one that is returned. That is all the
  82957. ** insert routine needs to know about.
  82958. */
  82959. static int autoIncBegin(
  82960. Parse *pParse, /* Parsing context */
  82961. int iDb, /* Index of the database holding pTab */
  82962. Table *pTab /* The table we are writing to */
  82963. ){
  82964. int memId = 0; /* Register holding maximum rowid */
  82965. if( pTab->tabFlags & TF_Autoincrement ){
  82966. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  82967. AutoincInfo *pInfo;
  82968. pInfo = pToplevel->pAinc;
  82969. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  82970. if( pInfo==0 ){
  82971. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  82972. if( pInfo==0 ) return 0;
  82973. pInfo->pNext = pToplevel->pAinc;
  82974. pToplevel->pAinc = pInfo;
  82975. pInfo->pTab = pTab;
  82976. pInfo->iDb = iDb;
  82977. pToplevel->nMem++; /* Register to hold name of table */
  82978. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  82979. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  82980. }
  82981. memId = pInfo->regCtr;
  82982. }
  82983. return memId;
  82984. }
  82985. /*
  82986. ** This routine generates code that will initialize all of the
  82987. ** register used by the autoincrement tracker.
  82988. */
  82989. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  82990. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  82991. sqlite3 *db = pParse->db; /* The database connection */
  82992. Db *pDb; /* Database only autoinc table */
  82993. int memId; /* Register holding max rowid */
  82994. int addr; /* A VDBE address */
  82995. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  82996. /* This routine is never called during trigger-generation. It is
  82997. ** only called from the top-level */
  82998. assert( pParse->pTriggerTab==0 );
  82999. assert( pParse==sqlite3ParseToplevel(pParse) );
  83000. assert( v ); /* We failed long ago if this is not so */
  83001. for(p = pParse->pAinc; p; p = p->pNext){
  83002. pDb = &db->aDb[p->iDb];
  83003. memId = p->regCtr;
  83004. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  83005. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  83006. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  83007. addr = sqlite3VdbeCurrentAddr(v);
  83008. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  83009. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  83010. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  83011. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  83012. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  83013. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  83014. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  83015. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  83016. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  83017. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  83018. sqlite3VdbeAddOp0(v, OP_Close);
  83019. }
  83020. }
  83021. /*
  83022. ** Update the maximum rowid for an autoincrement calculation.
  83023. **
  83024. ** This routine should be called when the top of the stack holds a
  83025. ** new rowid that is about to be inserted. If that new rowid is
  83026. ** larger than the maximum rowid in the memId memory cell, then the
  83027. ** memory cell is updated. The stack is unchanged.
  83028. */
  83029. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  83030. if( memId>0 ){
  83031. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  83032. }
  83033. }
  83034. /*
  83035. ** This routine generates the code needed to write autoincrement
  83036. ** maximum rowid values back into the sqlite_sequence register.
  83037. ** Every statement that might do an INSERT into an autoincrement
  83038. ** table (either directly or through triggers) needs to call this
  83039. ** routine just before the "exit" code.
  83040. */
  83041. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  83042. AutoincInfo *p;
  83043. Vdbe *v = pParse->pVdbe;
  83044. sqlite3 *db = pParse->db;
  83045. assert( v );
  83046. for(p = pParse->pAinc; p; p = p->pNext){
  83047. Db *pDb = &db->aDb[p->iDb];
  83048. int j1, j2, j3, j4, j5;
  83049. int iRec;
  83050. int memId = p->regCtr;
  83051. iRec = sqlite3GetTempReg(pParse);
  83052. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  83053. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  83054. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  83055. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  83056. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  83057. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  83058. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  83059. sqlite3VdbeJumpHere(v, j2);
  83060. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  83061. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  83062. sqlite3VdbeJumpHere(v, j4);
  83063. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  83064. sqlite3VdbeJumpHere(v, j1);
  83065. sqlite3VdbeJumpHere(v, j5);
  83066. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  83067. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  83068. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83069. sqlite3VdbeAddOp0(v, OP_Close);
  83070. sqlite3ReleaseTempReg(pParse, iRec);
  83071. }
  83072. }
  83073. #else
  83074. /*
  83075. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  83076. ** above are all no-ops
  83077. */
  83078. # define autoIncBegin(A,B,C) (0)
  83079. # define autoIncStep(A,B,C)
  83080. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  83081. /*
  83082. ** Generate code for a co-routine that will evaluate a subquery one
  83083. ** row at a time.
  83084. **
  83085. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  83086. ** Information about the location of co-routine and the registers it will use
  83087. ** is returned by filling in the pDest object.
  83088. **
  83089. ** Registers are allocated as follows:
  83090. **
  83091. ** pDest->iSDParm The register holding the next entry-point of the
  83092. ** co-routine. Run the co-routine to its next breakpoint
  83093. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  83094. **
  83095. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  83096. ** co-routine. This register is 0 if the previous Yield
  83097. ** generated a new result row, or 1 if the subquery
  83098. ** has completed. If the Yield is called again
  83099. ** after this register becomes 1, then the VDBE will
  83100. ** halt with an SQLITE_INTERNAL error.
  83101. **
  83102. ** pDest->iSdst First result register.
  83103. **
  83104. ** pDest->nSdst Number of result registers.
  83105. **
  83106. ** This routine handles all of the register allocation and fills in the
  83107. ** pDest structure appropriately.
  83108. **
  83109. ** Here is a schematic of the generated code assuming that X is the
  83110. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  83111. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  83112. ** registers that hold the result set, reg[pDest->iSdst] through
  83113. ** reg[pDest->iSdst+pDest->nSdst-1]:
  83114. **
  83115. ** X <- A
  83116. ** EOF <- 0
  83117. ** goto B
  83118. ** A: setup for the SELECT
  83119. ** loop rows in the SELECT
  83120. ** load results into registers R..S
  83121. ** yield X
  83122. ** end loop
  83123. ** cleanup after the SELECT
  83124. ** EOF <- 1
  83125. ** yield X
  83126. ** halt-error
  83127. ** B:
  83128. **
  83129. ** To use this subroutine, the caller generates code as follows:
  83130. **
  83131. ** [ Co-routine generated by this subroutine, shown above ]
  83132. ** S: yield X
  83133. ** if EOF goto E
  83134. ** if skip this row, goto C
  83135. ** if terminate loop, goto E
  83136. ** deal with this row
  83137. ** C: goto S
  83138. ** E:
  83139. */
  83140. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  83141. int regYield; /* Register holding co-routine entry-point */
  83142. int regEof; /* Register holding co-routine completion flag */
  83143. int addrTop; /* Top of the co-routine */
  83144. int j1; /* Jump instruction */
  83145. int rc; /* Result code */
  83146. Vdbe *v; /* VDBE under construction */
  83147. regYield = ++pParse->nMem;
  83148. regEof = ++pParse->nMem;
  83149. v = sqlite3GetVdbe(pParse);
  83150. addrTop = sqlite3VdbeCurrentAddr(v);
  83151. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  83152. VdbeComment((v, "Co-routine entry point"));
  83153. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  83154. VdbeComment((v, "Co-routine completion flag"));
  83155. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  83156. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  83157. rc = sqlite3Select(pParse, pSelect, pDest);
  83158. assert( pParse->nErr==0 || rc );
  83159. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  83160. if( rc ) return rc;
  83161. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  83162. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  83163. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  83164. VdbeComment((v, "End of coroutine"));
  83165. sqlite3VdbeJumpHere(v, j1); /* label B: */
  83166. return rc;
  83167. }
  83168. /* Forward declaration */
  83169. static int xferOptimization(
  83170. Parse *pParse, /* Parser context */
  83171. Table *pDest, /* The table we are inserting into */
  83172. Select *pSelect, /* A SELECT statement to use as the data source */
  83173. int onError, /* How to handle constraint errors */
  83174. int iDbDest /* The database of pDest */
  83175. );
  83176. /*
  83177. ** This routine is call to handle SQL of the following forms:
  83178. **
  83179. ** insert into TABLE (IDLIST) values(EXPRLIST)
  83180. ** insert into TABLE (IDLIST) select
  83181. **
  83182. ** The IDLIST following the table name is always optional. If omitted,
  83183. ** then a list of all columns for the table is substituted. The IDLIST
  83184. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  83185. **
  83186. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  83187. ** statement above, and pSelect is NULL. For the second form, pList is
  83188. ** NULL and pSelect is a pointer to the select statement used to generate
  83189. ** data for the insert.
  83190. **
  83191. ** The code generated follows one of four templates. For a simple
  83192. ** select with data coming from a VALUES clause, the code executes
  83193. ** once straight down through. Pseudo-code follows (we call this
  83194. ** the "1st template"):
  83195. **
  83196. ** open write cursor to <table> and its indices
  83197. ** puts VALUES clause expressions onto the stack
  83198. ** write the resulting record into <table>
  83199. ** cleanup
  83200. **
  83201. ** The three remaining templates assume the statement is of the form
  83202. **
  83203. ** INSERT INTO <table> SELECT ...
  83204. **
  83205. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  83206. ** in other words if the SELECT pulls all columns from a single table
  83207. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  83208. ** if <table2> and <table1> are distinct tables but have identical
  83209. ** schemas, including all the same indices, then a special optimization
  83210. ** is invoked that copies raw records from <table2> over to <table1>.
  83211. ** See the xferOptimization() function for the implementation of this
  83212. ** template. This is the 2nd template.
  83213. **
  83214. ** open a write cursor to <table>
  83215. ** open read cursor on <table2>
  83216. ** transfer all records in <table2> over to <table>
  83217. ** close cursors
  83218. ** foreach index on <table>
  83219. ** open a write cursor on the <table> index
  83220. ** open a read cursor on the corresponding <table2> index
  83221. ** transfer all records from the read to the write cursors
  83222. ** close cursors
  83223. ** end foreach
  83224. **
  83225. ** The 3rd template is for when the second template does not apply
  83226. ** and the SELECT clause does not read from <table> at any time.
  83227. ** The generated code follows this template:
  83228. **
  83229. ** EOF <- 0
  83230. ** X <- A
  83231. ** goto B
  83232. ** A: setup for the SELECT
  83233. ** loop over the rows in the SELECT
  83234. ** load values into registers R..R+n
  83235. ** yield X
  83236. ** end loop
  83237. ** cleanup after the SELECT
  83238. ** EOF <- 1
  83239. ** yield X
  83240. ** goto A
  83241. ** B: open write cursor to <table> and its indices
  83242. ** C: yield X
  83243. ** if EOF goto D
  83244. ** insert the select result into <table> from R..R+n
  83245. ** goto C
  83246. ** D: cleanup
  83247. **
  83248. ** The 4th template is used if the insert statement takes its
  83249. ** values from a SELECT but the data is being inserted into a table
  83250. ** that is also read as part of the SELECT. In the third form,
  83251. ** we have to use a intermediate table to store the results of
  83252. ** the select. The template is like this:
  83253. **
  83254. ** EOF <- 0
  83255. ** X <- A
  83256. ** goto B
  83257. ** A: setup for the SELECT
  83258. ** loop over the tables in the SELECT
  83259. ** load value into register R..R+n
  83260. ** yield X
  83261. ** end loop
  83262. ** cleanup after the SELECT
  83263. ** EOF <- 1
  83264. ** yield X
  83265. ** halt-error
  83266. ** B: open temp table
  83267. ** L: yield X
  83268. ** if EOF goto M
  83269. ** insert row from R..R+n into temp table
  83270. ** goto L
  83271. ** M: open write cursor to <table> and its indices
  83272. ** rewind temp table
  83273. ** C: loop over rows of intermediate table
  83274. ** transfer values form intermediate table into <table>
  83275. ** end loop
  83276. ** D: cleanup
  83277. */
  83278. SQLITE_PRIVATE void sqlite3Insert(
  83279. Parse *pParse, /* Parser context */
  83280. SrcList *pTabList, /* Name of table into which we are inserting */
  83281. ExprList *pList, /* List of values to be inserted */
  83282. Select *pSelect, /* A SELECT statement to use as the data source */
  83283. IdList *pColumn, /* Column names corresponding to IDLIST. */
  83284. int onError /* How to handle constraint errors */
  83285. ){
  83286. sqlite3 *db; /* The main database structure */
  83287. Table *pTab; /* The table to insert into. aka TABLE */
  83288. char *zTab; /* Name of the table into which we are inserting */
  83289. const char *zDb; /* Name of the database holding this table */
  83290. int i, j, idx; /* Loop counters */
  83291. Vdbe *v; /* Generate code into this virtual machine */
  83292. Index *pIdx; /* For looping over indices of the table */
  83293. int nColumn; /* Number of columns in the data */
  83294. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  83295. int baseCur = 0; /* VDBE Cursor number for pTab */
  83296. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  83297. int endOfLoop; /* Label for the end of the insertion loop */
  83298. int useTempTable = 0; /* Store SELECT results in intermediate table */
  83299. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  83300. int addrInsTop = 0; /* Jump to label "D" */
  83301. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  83302. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  83303. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  83304. int iDb; /* Index of database holding TABLE */
  83305. Db *pDb; /* The database containing table being inserted into */
  83306. int appendFlag = 0; /* True if the insert is likely to be an append */
  83307. /* Register allocations */
  83308. int regFromSelect = 0;/* Base register for data coming from SELECT */
  83309. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  83310. int regRowCount = 0; /* Memory cell used for the row counter */
  83311. int regIns; /* Block of regs holding rowid+data being inserted */
  83312. int regRowid; /* registers holding insert rowid */
  83313. int regData; /* register holding first column to insert */
  83314. int regEof = 0; /* Register recording end of SELECT data */
  83315. int *aRegIdx = 0; /* One register allocated to each index */
  83316. #ifndef SQLITE_OMIT_TRIGGER
  83317. int isView; /* True if attempting to insert into a view */
  83318. Trigger *pTrigger; /* List of triggers on pTab, if required */
  83319. int tmask; /* Mask of trigger times */
  83320. #endif
  83321. db = pParse->db;
  83322. memset(&dest, 0, sizeof(dest));
  83323. if( pParse->nErr || db->mallocFailed ){
  83324. goto insert_cleanup;
  83325. }
  83326. /* Locate the table into which we will be inserting new information.
  83327. */
  83328. assert( pTabList->nSrc==1 );
  83329. zTab = pTabList->a[0].zName;
  83330. if( NEVER(zTab==0) ) goto insert_cleanup;
  83331. pTab = sqlite3SrcListLookup(pParse, pTabList);
  83332. if( pTab==0 ){
  83333. goto insert_cleanup;
  83334. }
  83335. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83336. assert( iDb<db->nDb );
  83337. pDb = &db->aDb[iDb];
  83338. zDb = pDb->zName;
  83339. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  83340. goto insert_cleanup;
  83341. }
  83342. /* Figure out if we have any triggers and if the table being
  83343. ** inserted into is a view
  83344. */
  83345. #ifndef SQLITE_OMIT_TRIGGER
  83346. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  83347. isView = pTab->pSelect!=0;
  83348. #else
  83349. # define pTrigger 0
  83350. # define tmask 0
  83351. # define isView 0
  83352. #endif
  83353. #ifdef SQLITE_OMIT_VIEW
  83354. # undef isView
  83355. # define isView 0
  83356. #endif
  83357. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  83358. /* If pTab is really a view, make sure it has been initialized.
  83359. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  83360. ** module table).
  83361. */
  83362. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  83363. goto insert_cleanup;
  83364. }
  83365. /* Ensure that:
  83366. * (a) the table is not read-only,
  83367. * (b) that if it is a view then ON INSERT triggers exist
  83368. */
  83369. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  83370. goto insert_cleanup;
  83371. }
  83372. /* Allocate a VDBE
  83373. */
  83374. v = sqlite3GetVdbe(pParse);
  83375. if( v==0 ) goto insert_cleanup;
  83376. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  83377. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  83378. #ifndef SQLITE_OMIT_XFER_OPT
  83379. /* If the statement is of the form
  83380. **
  83381. ** INSERT INTO <table1> SELECT * FROM <table2>;
  83382. **
  83383. ** Then special optimizations can be applied that make the transfer
  83384. ** very fast and which reduce fragmentation of indices.
  83385. **
  83386. ** This is the 2nd template.
  83387. */
  83388. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  83389. assert( !pTrigger );
  83390. assert( pList==0 );
  83391. goto insert_end;
  83392. }
  83393. #endif /* SQLITE_OMIT_XFER_OPT */
  83394. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  83395. ** sqlite_sequence table and store it in memory cell regAutoinc.
  83396. */
  83397. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  83398. /* Figure out how many columns of data are supplied. If the data
  83399. ** is coming from a SELECT statement, then generate a co-routine that
  83400. ** produces a single row of the SELECT on each invocation. The
  83401. ** co-routine is the common header to the 3rd and 4th templates.
  83402. */
  83403. if( pSelect ){
  83404. /* Data is coming from a SELECT. Generate a co-routine to run that
  83405. ** SELECT. */
  83406. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  83407. if( rc ) goto insert_cleanup;
  83408. regEof = dest.iSDParm + 1;
  83409. regFromSelect = dest.iSdst;
  83410. assert( pSelect->pEList );
  83411. nColumn = pSelect->pEList->nExpr;
  83412. assert( dest.nSdst==nColumn );
  83413. /* Set useTempTable to TRUE if the result of the SELECT statement
  83414. ** should be written into a temporary table (template 4). Set to
  83415. ** FALSE if each* row of the SELECT can be written directly into
  83416. ** the destination table (template 3).
  83417. **
  83418. ** A temp table must be used if the table being updated is also one
  83419. ** of the tables being read by the SELECT statement. Also use a
  83420. ** temp table in the case of row triggers.
  83421. */
  83422. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  83423. useTempTable = 1;
  83424. }
  83425. if( useTempTable ){
  83426. /* Invoke the coroutine to extract information from the SELECT
  83427. ** and add it to a transient table srcTab. The code generated
  83428. ** here is from the 4th template:
  83429. **
  83430. ** B: open temp table
  83431. ** L: yield X
  83432. ** if EOF goto M
  83433. ** insert row from R..R+n into temp table
  83434. ** goto L
  83435. ** M: ...
  83436. */
  83437. int regRec; /* Register to hold packed record */
  83438. int regTempRowid; /* Register to hold temp table ROWID */
  83439. int addrTop; /* Label "L" */
  83440. int addrIf; /* Address of jump to M */
  83441. srcTab = pParse->nTab++;
  83442. regRec = sqlite3GetTempReg(pParse);
  83443. regTempRowid = sqlite3GetTempReg(pParse);
  83444. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  83445. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  83446. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  83447. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  83448. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  83449. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  83450. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  83451. sqlite3VdbeJumpHere(v, addrIf);
  83452. sqlite3ReleaseTempReg(pParse, regRec);
  83453. sqlite3ReleaseTempReg(pParse, regTempRowid);
  83454. }
  83455. }else{
  83456. /* This is the case if the data for the INSERT is coming from a VALUES
  83457. ** clause
  83458. */
  83459. NameContext sNC;
  83460. memset(&sNC, 0, sizeof(sNC));
  83461. sNC.pParse = pParse;
  83462. srcTab = -1;
  83463. assert( useTempTable==0 );
  83464. nColumn = pList ? pList->nExpr : 0;
  83465. for(i=0; i<nColumn; i++){
  83466. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  83467. goto insert_cleanup;
  83468. }
  83469. }
  83470. }
  83471. /* Make sure the number of columns in the source data matches the number
  83472. ** of columns to be inserted into the table.
  83473. */
  83474. if( IsVirtual(pTab) ){
  83475. for(i=0; i<pTab->nCol; i++){
  83476. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  83477. }
  83478. }
  83479. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  83480. sqlite3ErrorMsg(pParse,
  83481. "table %S has %d columns but %d values were supplied",
  83482. pTabList, 0, pTab->nCol-nHidden, nColumn);
  83483. goto insert_cleanup;
  83484. }
  83485. if( pColumn!=0 && nColumn!=pColumn->nId ){
  83486. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  83487. goto insert_cleanup;
  83488. }
  83489. /* If the INSERT statement included an IDLIST term, then make sure
  83490. ** all elements of the IDLIST really are columns of the table and
  83491. ** remember the column indices.
  83492. **
  83493. ** If the table has an INTEGER PRIMARY KEY column and that column
  83494. ** is named in the IDLIST, then record in the keyColumn variable
  83495. ** the index into IDLIST of the primary key column. keyColumn is
  83496. ** the index of the primary key as it appears in IDLIST, not as
  83497. ** is appears in the original table. (The index of the primary
  83498. ** key in the original table is pTab->iPKey.)
  83499. */
  83500. if( pColumn ){
  83501. for(i=0; i<pColumn->nId; i++){
  83502. pColumn->a[i].idx = -1;
  83503. }
  83504. for(i=0; i<pColumn->nId; i++){
  83505. for(j=0; j<pTab->nCol; j++){
  83506. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  83507. pColumn->a[i].idx = j;
  83508. if( j==pTab->iPKey ){
  83509. keyColumn = i;
  83510. }
  83511. break;
  83512. }
  83513. }
  83514. if( j>=pTab->nCol ){
  83515. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  83516. keyColumn = i;
  83517. }else{
  83518. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  83519. pTabList, 0, pColumn->a[i].zName);
  83520. pParse->checkSchema = 1;
  83521. goto insert_cleanup;
  83522. }
  83523. }
  83524. }
  83525. }
  83526. /* If there is no IDLIST term but the table has an integer primary
  83527. ** key, the set the keyColumn variable to the primary key column index
  83528. ** in the original table definition.
  83529. */
  83530. if( pColumn==0 && nColumn>0 ){
  83531. keyColumn = pTab->iPKey;
  83532. }
  83533. /* Initialize the count of rows to be inserted
  83534. */
  83535. if( db->flags & SQLITE_CountRows ){
  83536. regRowCount = ++pParse->nMem;
  83537. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  83538. }
  83539. /* If this is not a view, open the table and and all indices */
  83540. if( !isView ){
  83541. int nIdx;
  83542. baseCur = pParse->nTab;
  83543. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  83544. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  83545. if( aRegIdx==0 ){
  83546. goto insert_cleanup;
  83547. }
  83548. for(i=0; i<nIdx; i++){
  83549. aRegIdx[i] = ++pParse->nMem;
  83550. }
  83551. }
  83552. /* This is the top of the main insertion loop */
  83553. if( useTempTable ){
  83554. /* This block codes the top of loop only. The complete loop is the
  83555. ** following pseudocode (template 4):
  83556. **
  83557. ** rewind temp table
  83558. ** C: loop over rows of intermediate table
  83559. ** transfer values form intermediate table into <table>
  83560. ** end loop
  83561. ** D: ...
  83562. */
  83563. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  83564. addrCont = sqlite3VdbeCurrentAddr(v);
  83565. }else if( pSelect ){
  83566. /* This block codes the top of loop only. The complete loop is the
  83567. ** following pseudocode (template 3):
  83568. **
  83569. ** C: yield X
  83570. ** if EOF goto D
  83571. ** insert the select result into <table> from R..R+n
  83572. ** goto C
  83573. ** D: ...
  83574. */
  83575. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  83576. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  83577. }
  83578. /* Allocate registers for holding the rowid of the new row,
  83579. ** the content of the new row, and the assemblied row record.
  83580. */
  83581. regRowid = regIns = pParse->nMem+1;
  83582. pParse->nMem += pTab->nCol + 1;
  83583. if( IsVirtual(pTab) ){
  83584. regRowid++;
  83585. pParse->nMem++;
  83586. }
  83587. regData = regRowid+1;
  83588. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  83589. */
  83590. endOfLoop = sqlite3VdbeMakeLabel(v);
  83591. if( tmask & TRIGGER_BEFORE ){
  83592. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  83593. /* build the NEW.* reference row. Note that if there is an INTEGER
  83594. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  83595. ** translated into a unique ID for the row. But on a BEFORE trigger,
  83596. ** we do not know what the unique ID will be (because the insert has
  83597. ** not happened yet) so we substitute a rowid of -1
  83598. */
  83599. if( keyColumn<0 ){
  83600. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  83601. }else{
  83602. int j1;
  83603. if( useTempTable ){
  83604. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  83605. }else{
  83606. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  83607. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  83608. }
  83609. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  83610. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  83611. sqlite3VdbeJumpHere(v, j1);
  83612. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  83613. }
  83614. /* Cannot have triggers on a virtual table. If it were possible,
  83615. ** this block would have to account for hidden column.
  83616. */
  83617. assert( !IsVirtual(pTab) );
  83618. /* Create the new column data
  83619. */
  83620. for(i=0; i<pTab->nCol; i++){
  83621. if( pColumn==0 ){
  83622. j = i;
  83623. }else{
  83624. for(j=0; j<pColumn->nId; j++){
  83625. if( pColumn->a[j].idx==i ) break;
  83626. }
  83627. }
  83628. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  83629. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  83630. }else if( useTempTable ){
  83631. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  83632. }else{
  83633. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  83634. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  83635. }
  83636. }
  83637. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  83638. ** do not attempt any conversions before assembling the record.
  83639. ** If this is a real table, attempt conversions as required by the
  83640. ** table column affinities.
  83641. */
  83642. if( !isView ){
  83643. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  83644. sqlite3TableAffinityStr(v, pTab);
  83645. }
  83646. /* Fire BEFORE or INSTEAD OF triggers */
  83647. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  83648. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  83649. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  83650. }
  83651. /* Push the record number for the new entry onto the stack. The
  83652. ** record number is a randomly generate integer created by NewRowid
  83653. ** except when the table has an INTEGER PRIMARY KEY column, in which
  83654. ** case the record number is the same as that column.
  83655. */
  83656. if( !isView ){
  83657. if( IsVirtual(pTab) ){
  83658. /* The row that the VUpdate opcode will delete: none */
  83659. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  83660. }
  83661. if( keyColumn>=0 ){
  83662. if( useTempTable ){
  83663. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  83664. }else if( pSelect ){
  83665. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  83666. }else{
  83667. VdbeOp *pOp;
  83668. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  83669. pOp = sqlite3VdbeGetOp(v, -1);
  83670. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  83671. appendFlag = 1;
  83672. pOp->opcode = OP_NewRowid;
  83673. pOp->p1 = baseCur;
  83674. pOp->p2 = regRowid;
  83675. pOp->p3 = regAutoinc;
  83676. }
  83677. }
  83678. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  83679. ** to generate a unique primary key value.
  83680. */
  83681. if( !appendFlag ){
  83682. int j1;
  83683. if( !IsVirtual(pTab) ){
  83684. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  83685. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  83686. sqlite3VdbeJumpHere(v, j1);
  83687. }else{
  83688. j1 = sqlite3VdbeCurrentAddr(v);
  83689. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  83690. }
  83691. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  83692. }
  83693. }else if( IsVirtual(pTab) ){
  83694. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  83695. }else{
  83696. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  83697. appendFlag = 1;
  83698. }
  83699. autoIncStep(pParse, regAutoinc, regRowid);
  83700. /* Push onto the stack, data for all columns of the new entry, beginning
  83701. ** with the first column.
  83702. */
  83703. nHidden = 0;
  83704. for(i=0; i<pTab->nCol; i++){
  83705. int iRegStore = regRowid+1+i;
  83706. if( i==pTab->iPKey ){
  83707. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  83708. ** Whenever this column is read, the record number will be substituted
  83709. ** in its place. So will fill this column with a NULL to avoid
  83710. ** taking up data space with information that will never be used. */
  83711. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  83712. continue;
  83713. }
  83714. if( pColumn==0 ){
  83715. if( IsHiddenColumn(&pTab->aCol[i]) ){
  83716. assert( IsVirtual(pTab) );
  83717. j = -1;
  83718. nHidden++;
  83719. }else{
  83720. j = i - nHidden;
  83721. }
  83722. }else{
  83723. for(j=0; j<pColumn->nId; j++){
  83724. if( pColumn->a[j].idx==i ) break;
  83725. }
  83726. }
  83727. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  83728. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  83729. }else if( useTempTable ){
  83730. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  83731. }else if( pSelect ){
  83732. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  83733. }else{
  83734. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  83735. }
  83736. }
  83737. /* Generate code to check constraints and generate index keys and
  83738. ** do the insertion.
  83739. */
  83740. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83741. if( IsVirtual(pTab) ){
  83742. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  83743. sqlite3VtabMakeWritable(pParse, pTab);
  83744. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  83745. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  83746. sqlite3MayAbort(pParse);
  83747. }else
  83748. #endif
  83749. {
  83750. int isReplace; /* Set to true if constraints may cause a replace */
  83751. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  83752. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  83753. );
  83754. sqlite3FkCheck(pParse, pTab, 0, regIns);
  83755. sqlite3CompleteInsertion(
  83756. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  83757. );
  83758. }
  83759. }
  83760. /* Update the count of rows that are inserted
  83761. */
  83762. if( (db->flags & SQLITE_CountRows)!=0 ){
  83763. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  83764. }
  83765. if( pTrigger ){
  83766. /* Code AFTER triggers */
  83767. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  83768. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  83769. }
  83770. /* The bottom of the main insertion loop, if the data source
  83771. ** is a SELECT statement.
  83772. */
  83773. sqlite3VdbeResolveLabel(v, endOfLoop);
  83774. if( useTempTable ){
  83775. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  83776. sqlite3VdbeJumpHere(v, addrInsTop);
  83777. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  83778. }else if( pSelect ){
  83779. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  83780. sqlite3VdbeJumpHere(v, addrInsTop);
  83781. }
  83782. if( !IsVirtual(pTab) && !isView ){
  83783. /* Close all tables opened */
  83784. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  83785. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  83786. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  83787. }
  83788. }
  83789. insert_end:
  83790. /* Update the sqlite_sequence table by storing the content of the
  83791. ** maximum rowid counter values recorded while inserting into
  83792. ** autoincrement tables.
  83793. */
  83794. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  83795. sqlite3AutoincrementEnd(pParse);
  83796. }
  83797. /*
  83798. ** Return the number of rows inserted. If this routine is
  83799. ** generating code because of a call to sqlite3NestedParse(), do not
  83800. ** invoke the callback function.
  83801. */
  83802. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  83803. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  83804. sqlite3VdbeSetNumCols(v, 1);
  83805. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  83806. }
  83807. insert_cleanup:
  83808. sqlite3SrcListDelete(db, pTabList);
  83809. sqlite3ExprListDelete(db, pList);
  83810. sqlite3SelectDelete(db, pSelect);
  83811. sqlite3IdListDelete(db, pColumn);
  83812. sqlite3DbFree(db, aRegIdx);
  83813. }
  83814. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  83815. ** thely may interfere with compilation of other functions in this file
  83816. ** (or in another file, if this file becomes part of the amalgamation). */
  83817. #ifdef isView
  83818. #undef isView
  83819. #endif
  83820. #ifdef pTrigger
  83821. #undef pTrigger
  83822. #endif
  83823. #ifdef tmask
  83824. #undef tmask
  83825. #endif
  83826. /*
  83827. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  83828. **
  83829. ** The input is a range of consecutive registers as follows:
  83830. **
  83831. ** 1. The rowid of the row after the update.
  83832. **
  83833. ** 2. The data in the first column of the entry after the update.
  83834. **
  83835. ** i. Data from middle columns...
  83836. **
  83837. ** N. The data in the last column of the entry after the update.
  83838. **
  83839. ** The regRowid parameter is the index of the register containing (1).
  83840. **
  83841. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  83842. ** the address of a register containing the rowid before the update takes
  83843. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  83844. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  83845. ** indicates that the rowid was explicitly specified as part of the
  83846. ** INSERT statement. If rowidChng is false, it means that the rowid is
  83847. ** computed automatically in an insert or that the rowid value is not
  83848. ** modified by an update.
  83849. **
  83850. ** The code generated by this routine store new index entries into
  83851. ** registers identified by aRegIdx[]. No index entry is created for
  83852. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  83853. ** the same as the order of indices on the linked list of indices
  83854. ** attached to the table.
  83855. **
  83856. ** This routine also generates code to check constraints. NOT NULL,
  83857. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  83858. ** then the appropriate action is performed. There are five possible
  83859. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  83860. **
  83861. ** Constraint type Action What Happens
  83862. ** --------------- ---------- ----------------------------------------
  83863. ** any ROLLBACK The current transaction is rolled back and
  83864. ** sqlite3_exec() returns immediately with a
  83865. ** return code of SQLITE_CONSTRAINT.
  83866. **
  83867. ** any ABORT Back out changes from the current command
  83868. ** only (do not do a complete rollback) then
  83869. ** cause sqlite3_exec() to return immediately
  83870. ** with SQLITE_CONSTRAINT.
  83871. **
  83872. ** any FAIL Sqlite3_exec() returns immediately with a
  83873. ** return code of SQLITE_CONSTRAINT. The
  83874. ** transaction is not rolled back and any
  83875. ** prior changes are retained.
  83876. **
  83877. ** any IGNORE The record number and data is popped from
  83878. ** the stack and there is an immediate jump
  83879. ** to label ignoreDest.
  83880. **
  83881. ** NOT NULL REPLACE The NULL value is replace by the default
  83882. ** value for that column. If the default value
  83883. ** is NULL, the action is the same as ABORT.
  83884. **
  83885. ** UNIQUE REPLACE The other row that conflicts with the row
  83886. ** being inserted is removed.
  83887. **
  83888. ** CHECK REPLACE Illegal. The results in an exception.
  83889. **
  83890. ** Which action to take is determined by the overrideError parameter.
  83891. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  83892. ** is used. Or if pParse->onError==OE_Default then the onError value
  83893. ** for the constraint is used.
  83894. **
  83895. ** The calling routine must open a read/write cursor for pTab with
  83896. ** cursor number "baseCur". All indices of pTab must also have open
  83897. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  83898. ** Except, if there is no possibility of a REPLACE action then
  83899. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  83900. */
  83901. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  83902. Parse *pParse, /* The parser context */
  83903. Table *pTab, /* the table into which we are inserting */
  83904. int baseCur, /* Index of a read/write cursor pointing at pTab */
  83905. int regRowid, /* Index of the range of input registers */
  83906. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  83907. int rowidChng, /* True if the rowid might collide with existing entry */
  83908. int isUpdate, /* True for UPDATE, False for INSERT */
  83909. int overrideError, /* Override onError to this if not OE_Default */
  83910. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  83911. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  83912. ){
  83913. int i; /* loop counter */
  83914. Vdbe *v; /* VDBE under constrution */
  83915. int nCol; /* Number of columns */
  83916. int onError; /* Conflict resolution strategy */
  83917. int j1; /* Addresss of jump instruction */
  83918. int j2 = 0, j3; /* Addresses of jump instructions */
  83919. int regData; /* Register containing first data column */
  83920. int iCur; /* Table cursor number */
  83921. Index *pIdx; /* Pointer to one of the indices */
  83922. sqlite3 *db; /* Database connection */
  83923. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  83924. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  83925. db = pParse->db;
  83926. v = sqlite3GetVdbe(pParse);
  83927. assert( v!=0 );
  83928. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  83929. nCol = pTab->nCol;
  83930. regData = regRowid + 1;
  83931. /* Test all NOT NULL constraints.
  83932. */
  83933. for(i=0; i<nCol; i++){
  83934. if( i==pTab->iPKey ){
  83935. continue;
  83936. }
  83937. onError = pTab->aCol[i].notNull;
  83938. if( onError==OE_None ) continue;
  83939. if( overrideError!=OE_Default ){
  83940. onError = overrideError;
  83941. }else if( onError==OE_Default ){
  83942. onError = OE_Abort;
  83943. }
  83944. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  83945. onError = OE_Abort;
  83946. }
  83947. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  83948. || onError==OE_Ignore || onError==OE_Replace );
  83949. switch( onError ){
  83950. case OE_Abort:
  83951. sqlite3MayAbort(pParse);
  83952. case OE_Rollback:
  83953. case OE_Fail: {
  83954. char *zMsg;
  83955. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  83956. SQLITE_CONSTRAINT, onError, regData+i);
  83957. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  83958. pTab->zName, pTab->aCol[i].zName);
  83959. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  83960. break;
  83961. }
  83962. case OE_Ignore: {
  83963. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  83964. break;
  83965. }
  83966. default: {
  83967. assert( onError==OE_Replace );
  83968. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  83969. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  83970. sqlite3VdbeJumpHere(v, j1);
  83971. break;
  83972. }
  83973. }
  83974. }
  83975. /* Test all CHECK constraints
  83976. */
  83977. #ifndef SQLITE_OMIT_CHECK
  83978. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  83979. ExprList *pCheck = pTab->pCheck;
  83980. pParse->ckBase = regData;
  83981. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  83982. for(i=0; i<pCheck->nExpr; i++){
  83983. int allOk = sqlite3VdbeMakeLabel(v);
  83984. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  83985. if( onError==OE_Ignore ){
  83986. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  83987. }else{
  83988. char *zConsName = pCheck->a[i].zName;
  83989. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  83990. if( zConsName ){
  83991. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  83992. }else{
  83993. zConsName = 0;
  83994. }
  83995. sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);
  83996. }
  83997. sqlite3VdbeResolveLabel(v, allOk);
  83998. }
  83999. }
  84000. #endif /* !defined(SQLITE_OMIT_CHECK) */
  84001. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  84002. ** of the new record does not previously exist. Except, if this
  84003. ** is an UPDATE and the primary key is not changing, that is OK.
  84004. */
  84005. if( rowidChng ){
  84006. onError = pTab->keyConf;
  84007. if( overrideError!=OE_Default ){
  84008. onError = overrideError;
  84009. }else if( onError==OE_Default ){
  84010. onError = OE_Abort;
  84011. }
  84012. if( isUpdate ){
  84013. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  84014. }
  84015. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  84016. switch( onError ){
  84017. default: {
  84018. onError = OE_Abort;
  84019. /* Fall thru into the next case */
  84020. }
  84021. case OE_Rollback:
  84022. case OE_Abort:
  84023. case OE_Fail: {
  84024. sqlite3HaltConstraint(
  84025. pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
  84026. break;
  84027. }
  84028. case OE_Replace: {
  84029. /* If there are DELETE triggers on this table and the
  84030. ** recursive-triggers flag is set, call GenerateRowDelete() to
  84031. ** remove the conflicting row from the table. This will fire
  84032. ** the triggers and remove both the table and index b-tree entries.
  84033. **
  84034. ** Otherwise, if there are no triggers or the recursive-triggers
  84035. ** flag is not set, but the table has one or more indexes, call
  84036. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  84037. ** only. The table b-tree entry will be replaced by the new entry
  84038. ** when it is inserted.
  84039. **
  84040. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  84041. ** also invoke MultiWrite() to indicate that this VDBE may require
  84042. ** statement rollback (if the statement is aborted after the delete
  84043. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  84044. ** but being more selective here allows statements like:
  84045. **
  84046. ** REPLACE INTO t(rowid) VALUES($newrowid)
  84047. **
  84048. ** to run without a statement journal if there are no indexes on the
  84049. ** table.
  84050. */
  84051. Trigger *pTrigger = 0;
  84052. if( db->flags&SQLITE_RecTriggers ){
  84053. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  84054. }
  84055. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  84056. sqlite3MultiWrite(pParse);
  84057. sqlite3GenerateRowDelete(
  84058. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  84059. );
  84060. }else if( pTab->pIndex ){
  84061. sqlite3MultiWrite(pParse);
  84062. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  84063. }
  84064. seenReplace = 1;
  84065. break;
  84066. }
  84067. case OE_Ignore: {
  84068. assert( seenReplace==0 );
  84069. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  84070. break;
  84071. }
  84072. }
  84073. sqlite3VdbeJumpHere(v, j3);
  84074. if( isUpdate ){
  84075. sqlite3VdbeJumpHere(v, j2);
  84076. }
  84077. }
  84078. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  84079. ** index and making sure that duplicate entries do not already exist.
  84080. ** Add the new records to the indices as we go.
  84081. */
  84082. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  84083. int regIdx;
  84084. int regR;
  84085. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  84086. /* Create a key for accessing the index entry */
  84087. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  84088. for(i=0; i<pIdx->nColumn; i++){
  84089. int idx = pIdx->aiColumn[i];
  84090. if( idx==pTab->iPKey ){
  84091. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  84092. }else{
  84093. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  84094. }
  84095. }
  84096. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  84097. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  84098. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  84099. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  84100. /* Find out what action to take in case there is an indexing conflict */
  84101. onError = pIdx->onError;
  84102. if( onError==OE_None ){
  84103. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  84104. continue; /* pIdx is not a UNIQUE index */
  84105. }
  84106. if( overrideError!=OE_Default ){
  84107. onError = overrideError;
  84108. }else if( onError==OE_Default ){
  84109. onError = OE_Abort;
  84110. }
  84111. if( seenReplace ){
  84112. if( onError==OE_Ignore ) onError = OE_Replace;
  84113. else if( onError==OE_Fail ) onError = OE_Abort;
  84114. }
  84115. /* Check to see if the new index entry will be unique */
  84116. regR = sqlite3GetTempReg(pParse);
  84117. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  84118. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  84119. regR, SQLITE_INT_TO_PTR(regIdx),
  84120. P4_INT32);
  84121. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  84122. /* Generate code that executes if the new index entry is not unique */
  84123. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  84124. || onError==OE_Ignore || onError==OE_Replace );
  84125. switch( onError ){
  84126. case OE_Rollback:
  84127. case OE_Abort:
  84128. case OE_Fail: {
  84129. int j;
  84130. StrAccum errMsg;
  84131. const char *zSep;
  84132. char *zErr;
  84133. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  84134. errMsg.db = db;
  84135. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  84136. for(j=0; j<pIdx->nColumn; j++){
  84137. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  84138. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  84139. zSep = ", ";
  84140. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  84141. }
  84142. sqlite3StrAccumAppend(&errMsg,
  84143. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  84144. zErr = sqlite3StrAccumFinish(&errMsg);
  84145. sqlite3HaltConstraint(pParse, onError, zErr, 0);
  84146. sqlite3DbFree(errMsg.db, zErr);
  84147. break;
  84148. }
  84149. case OE_Ignore: {
  84150. assert( seenReplace==0 );
  84151. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  84152. break;
  84153. }
  84154. default: {
  84155. Trigger *pTrigger = 0;
  84156. assert( onError==OE_Replace );
  84157. sqlite3MultiWrite(pParse);
  84158. if( db->flags&SQLITE_RecTriggers ){
  84159. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  84160. }
  84161. sqlite3GenerateRowDelete(
  84162. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  84163. );
  84164. seenReplace = 1;
  84165. break;
  84166. }
  84167. }
  84168. sqlite3VdbeJumpHere(v, j3);
  84169. sqlite3ReleaseTempReg(pParse, regR);
  84170. }
  84171. if( pbMayReplace ){
  84172. *pbMayReplace = seenReplace;
  84173. }
  84174. }
  84175. /*
  84176. ** This routine generates code to finish the INSERT or UPDATE operation
  84177. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  84178. ** A consecutive range of registers starting at regRowid contains the
  84179. ** rowid and the content to be inserted.
  84180. **
  84181. ** The arguments to this routine should be the same as the first six
  84182. ** arguments to sqlite3GenerateConstraintChecks.
  84183. */
  84184. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  84185. Parse *pParse, /* The parser context */
  84186. Table *pTab, /* the table into which we are inserting */
  84187. int baseCur, /* Index of a read/write cursor pointing at pTab */
  84188. int regRowid, /* Range of content */
  84189. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  84190. int isUpdate, /* True for UPDATE, False for INSERT */
  84191. int appendBias, /* True if this is likely to be an append */
  84192. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  84193. ){
  84194. int i;
  84195. Vdbe *v;
  84196. int nIdx;
  84197. Index *pIdx;
  84198. u8 pik_flags;
  84199. int regData;
  84200. int regRec;
  84201. v = sqlite3GetVdbe(pParse);
  84202. assert( v!=0 );
  84203. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  84204. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  84205. for(i=nIdx-1; i>=0; i--){
  84206. if( aRegIdx[i]==0 ) continue;
  84207. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  84208. if( useSeekResult ){
  84209. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  84210. }
  84211. }
  84212. regData = regRowid + 1;
  84213. regRec = sqlite3GetTempReg(pParse);
  84214. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  84215. sqlite3TableAffinityStr(v, pTab);
  84216. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  84217. if( pParse->nested ){
  84218. pik_flags = 0;
  84219. }else{
  84220. pik_flags = OPFLAG_NCHANGE;
  84221. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  84222. }
  84223. if( appendBias ){
  84224. pik_flags |= OPFLAG_APPEND;
  84225. }
  84226. if( useSeekResult ){
  84227. pik_flags |= OPFLAG_USESEEKRESULT;
  84228. }
  84229. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  84230. if( !pParse->nested ){
  84231. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  84232. }
  84233. sqlite3VdbeChangeP5(v, pik_flags);
  84234. }
  84235. /*
  84236. ** Generate code that will open cursors for a table and for all
  84237. ** indices of that table. The "baseCur" parameter is the cursor number used
  84238. ** for the table. Indices are opened on subsequent cursors.
  84239. **
  84240. ** Return the number of indices on the table.
  84241. */
  84242. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  84243. Parse *pParse, /* Parsing context */
  84244. Table *pTab, /* Table to be opened */
  84245. int baseCur, /* Cursor number assigned to the table */
  84246. int op /* OP_OpenRead or OP_OpenWrite */
  84247. ){
  84248. int i;
  84249. int iDb;
  84250. Index *pIdx;
  84251. Vdbe *v;
  84252. if( IsVirtual(pTab) ) return 0;
  84253. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84254. v = sqlite3GetVdbe(pParse);
  84255. assert( v!=0 );
  84256. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  84257. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  84258. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  84259. assert( pIdx->pSchema==pTab->pSchema );
  84260. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  84261. (char*)pKey, P4_KEYINFO_HANDOFF);
  84262. VdbeComment((v, "%s", pIdx->zName));
  84263. }
  84264. if( pParse->nTab<baseCur+i ){
  84265. pParse->nTab = baseCur+i;
  84266. }
  84267. return i-1;
  84268. }
  84269. #ifdef SQLITE_TEST
  84270. /*
  84271. ** The following global variable is incremented whenever the
  84272. ** transfer optimization is used. This is used for testing
  84273. ** purposes only - to make sure the transfer optimization really
  84274. ** is happening when it is suppose to.
  84275. */
  84276. SQLITE_API int sqlite3_xferopt_count;
  84277. #endif /* SQLITE_TEST */
  84278. #ifndef SQLITE_OMIT_XFER_OPT
  84279. /*
  84280. ** Check to collation names to see if they are compatible.
  84281. */
  84282. static int xferCompatibleCollation(const char *z1, const char *z2){
  84283. if( z1==0 ){
  84284. return z2==0;
  84285. }
  84286. if( z2==0 ){
  84287. return 0;
  84288. }
  84289. return sqlite3StrICmp(z1, z2)==0;
  84290. }
  84291. /*
  84292. ** Check to see if index pSrc is compatible as a source of data
  84293. ** for index pDest in an insert transfer optimization. The rules
  84294. ** for a compatible index:
  84295. **
  84296. ** * The index is over the same set of columns
  84297. ** * The same DESC and ASC markings occurs on all columns
  84298. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  84299. ** * The same collating sequence on each column
  84300. */
  84301. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  84302. int i;
  84303. assert( pDest && pSrc );
  84304. assert( pDest->pTable!=pSrc->pTable );
  84305. if( pDest->nColumn!=pSrc->nColumn ){
  84306. return 0; /* Different number of columns */
  84307. }
  84308. if( pDest->onError!=pSrc->onError ){
  84309. return 0; /* Different conflict resolution strategies */
  84310. }
  84311. for(i=0; i<pSrc->nColumn; i++){
  84312. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  84313. return 0; /* Different columns indexed */
  84314. }
  84315. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  84316. return 0; /* Different sort orders */
  84317. }
  84318. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  84319. return 0; /* Different collating sequences */
  84320. }
  84321. }
  84322. /* If no test above fails then the indices must be compatible */
  84323. return 1;
  84324. }
  84325. /*
  84326. ** Attempt the transfer optimization on INSERTs of the form
  84327. **
  84328. ** INSERT INTO tab1 SELECT * FROM tab2;
  84329. **
  84330. ** The xfer optimization transfers raw records from tab2 over to tab1.
  84331. ** Columns are not decoded and reassemblied, which greatly improves
  84332. ** performance. Raw index records are transferred in the same way.
  84333. **
  84334. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  84335. ** There are lots of rules for determining compatibility - see comments
  84336. ** embedded in the code for details.
  84337. **
  84338. ** This routine returns TRUE if the optimization is guaranteed to be used.
  84339. ** Sometimes the xfer optimization will only work if the destination table
  84340. ** is empty - a factor that can only be determined at run-time. In that
  84341. ** case, this routine generates code for the xfer optimization but also
  84342. ** does a test to see if the destination table is empty and jumps over the
  84343. ** xfer optimization code if the test fails. In that case, this routine
  84344. ** returns FALSE so that the caller will know to go ahead and generate
  84345. ** an unoptimized transfer. This routine also returns FALSE if there
  84346. ** is no chance that the xfer optimization can be applied.
  84347. **
  84348. ** This optimization is particularly useful at making VACUUM run faster.
  84349. */
  84350. static int xferOptimization(
  84351. Parse *pParse, /* Parser context */
  84352. Table *pDest, /* The table we are inserting into */
  84353. Select *pSelect, /* A SELECT statement to use as the data source */
  84354. int onError, /* How to handle constraint errors */
  84355. int iDbDest /* The database of pDest */
  84356. ){
  84357. ExprList *pEList; /* The result set of the SELECT */
  84358. Table *pSrc; /* The table in the FROM clause of SELECT */
  84359. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  84360. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  84361. int i; /* Loop counter */
  84362. int iDbSrc; /* The database of pSrc */
  84363. int iSrc, iDest; /* Cursors from source and destination */
  84364. int addr1, addr2; /* Loop addresses */
  84365. int emptyDestTest; /* Address of test for empty pDest */
  84366. int emptySrcTest; /* Address of test for empty pSrc */
  84367. Vdbe *v; /* The VDBE we are building */
  84368. KeyInfo *pKey; /* Key information for an index */
  84369. int regAutoinc; /* Memory register used by AUTOINC */
  84370. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  84371. int regData, regRowid; /* Registers holding data and rowid */
  84372. if( pSelect==0 ){
  84373. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  84374. }
  84375. if( sqlite3TriggerList(pParse, pDest) ){
  84376. return 0; /* tab1 must not have triggers */
  84377. }
  84378. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84379. if( pDest->tabFlags & TF_Virtual ){
  84380. return 0; /* tab1 must not be a virtual table */
  84381. }
  84382. #endif
  84383. if( onError==OE_Default ){
  84384. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  84385. if( onError==OE_Default ) onError = OE_Abort;
  84386. }
  84387. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  84388. if( pSelect->pSrc->nSrc!=1 ){
  84389. return 0; /* FROM clause must have exactly one term */
  84390. }
  84391. if( pSelect->pSrc->a[0].pSelect ){
  84392. return 0; /* FROM clause cannot contain a subquery */
  84393. }
  84394. if( pSelect->pWhere ){
  84395. return 0; /* SELECT may not have a WHERE clause */
  84396. }
  84397. if( pSelect->pOrderBy ){
  84398. return 0; /* SELECT may not have an ORDER BY clause */
  84399. }
  84400. /* Do not need to test for a HAVING clause. If HAVING is present but
  84401. ** there is no ORDER BY, we will get an error. */
  84402. if( pSelect->pGroupBy ){
  84403. return 0; /* SELECT may not have a GROUP BY clause */
  84404. }
  84405. if( pSelect->pLimit ){
  84406. return 0; /* SELECT may not have a LIMIT clause */
  84407. }
  84408. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  84409. if( pSelect->pPrior ){
  84410. return 0; /* SELECT may not be a compound query */
  84411. }
  84412. if( pSelect->selFlags & SF_Distinct ){
  84413. return 0; /* SELECT may not be DISTINCT */
  84414. }
  84415. pEList = pSelect->pEList;
  84416. assert( pEList!=0 );
  84417. if( pEList->nExpr!=1 ){
  84418. return 0; /* The result set must have exactly one column */
  84419. }
  84420. assert( pEList->a[0].pExpr );
  84421. if( pEList->a[0].pExpr->op!=TK_ALL ){
  84422. return 0; /* The result set must be the special operator "*" */
  84423. }
  84424. /* At this point we have established that the statement is of the
  84425. ** correct syntactic form to participate in this optimization. Now
  84426. ** we have to check the semantics.
  84427. */
  84428. pItem = pSelect->pSrc->a;
  84429. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  84430. if( pSrc==0 ){
  84431. return 0; /* FROM clause does not contain a real table */
  84432. }
  84433. if( pSrc==pDest ){
  84434. return 0; /* tab1 and tab2 may not be the same table */
  84435. }
  84436. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84437. if( pSrc->tabFlags & TF_Virtual ){
  84438. return 0; /* tab2 must not be a virtual table */
  84439. }
  84440. #endif
  84441. if( pSrc->pSelect ){
  84442. return 0; /* tab2 may not be a view */
  84443. }
  84444. if( pDest->nCol!=pSrc->nCol ){
  84445. return 0; /* Number of columns must be the same in tab1 and tab2 */
  84446. }
  84447. if( pDest->iPKey!=pSrc->iPKey ){
  84448. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  84449. }
  84450. for(i=0; i<pDest->nCol; i++){
  84451. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  84452. return 0; /* Affinity must be the same on all columns */
  84453. }
  84454. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  84455. return 0; /* Collating sequence must be the same on all columns */
  84456. }
  84457. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  84458. return 0; /* tab2 must be NOT NULL if tab1 is */
  84459. }
  84460. }
  84461. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  84462. if( pDestIdx->onError!=OE_None ){
  84463. destHasUniqueIdx = 1;
  84464. }
  84465. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  84466. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  84467. }
  84468. if( pSrcIdx==0 ){
  84469. return 0; /* pDestIdx has no corresponding index in pSrc */
  84470. }
  84471. }
  84472. #ifndef SQLITE_OMIT_CHECK
  84473. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
  84474. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  84475. }
  84476. #endif
  84477. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84478. /* Disallow the transfer optimization if the destination table constains
  84479. ** any foreign key constraints. This is more restrictive than necessary.
  84480. ** But the main beneficiary of the transfer optimization is the VACUUM
  84481. ** command, and the VACUUM command disables foreign key constraints. So
  84482. ** the extra complication to make this rule less restrictive is probably
  84483. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  84484. */
  84485. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  84486. return 0;
  84487. }
  84488. #endif
  84489. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  84490. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  84491. }
  84492. /* If we get this far, it means that the xfer optimization is at
  84493. ** least a possibility, though it might only work if the destination
  84494. ** table (tab1) is initially empty.
  84495. */
  84496. #ifdef SQLITE_TEST
  84497. sqlite3_xferopt_count++;
  84498. #endif
  84499. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  84500. v = sqlite3GetVdbe(pParse);
  84501. sqlite3CodeVerifySchema(pParse, iDbSrc);
  84502. iSrc = pParse->nTab++;
  84503. iDest = pParse->nTab++;
  84504. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  84505. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  84506. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  84507. || destHasUniqueIdx /* (2) */
  84508. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  84509. ){
  84510. /* In some circumstances, we are able to run the xfer optimization
  84511. ** only if the destination table is initially empty. This code makes
  84512. ** that determination. Conditions under which the destination must
  84513. ** be empty:
  84514. **
  84515. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  84516. ** (If the destination is not initially empty, the rowid fields
  84517. ** of index entries might need to change.)
  84518. **
  84519. ** (2) The destination has a unique index. (The xfer optimization
  84520. ** is unable to test uniqueness.)
  84521. **
  84522. ** (3) onError is something other than OE_Abort and OE_Rollback.
  84523. */
  84524. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  84525. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  84526. sqlite3VdbeJumpHere(v, addr1);
  84527. }else{
  84528. emptyDestTest = 0;
  84529. }
  84530. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  84531. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  84532. regData = sqlite3GetTempReg(pParse);
  84533. regRowid = sqlite3GetTempReg(pParse);
  84534. if( pDest->iPKey>=0 ){
  84535. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  84536. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  84537. sqlite3HaltConstraint(
  84538. pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
  84539. sqlite3VdbeJumpHere(v, addr2);
  84540. autoIncStep(pParse, regAutoinc, regRowid);
  84541. }else if( pDest->pIndex==0 ){
  84542. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  84543. }else{
  84544. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  84545. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  84546. }
  84547. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  84548. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  84549. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  84550. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  84551. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  84552. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  84553. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  84554. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  84555. }
  84556. assert( pSrcIdx );
  84557. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  84558. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  84559. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  84560. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  84561. (char*)pKey, P4_KEYINFO_HANDOFF);
  84562. VdbeComment((v, "%s", pSrcIdx->zName));
  84563. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  84564. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  84565. (char*)pKey, P4_KEYINFO_HANDOFF);
  84566. VdbeComment((v, "%s", pDestIdx->zName));
  84567. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  84568. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  84569. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  84570. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  84571. sqlite3VdbeJumpHere(v, addr1);
  84572. }
  84573. sqlite3VdbeJumpHere(v, emptySrcTest);
  84574. sqlite3ReleaseTempReg(pParse, regRowid);
  84575. sqlite3ReleaseTempReg(pParse, regData);
  84576. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  84577. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  84578. if( emptyDestTest ){
  84579. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  84580. sqlite3VdbeJumpHere(v, emptyDestTest);
  84581. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  84582. return 0;
  84583. }else{
  84584. return 1;
  84585. }
  84586. }
  84587. #endif /* SQLITE_OMIT_XFER_OPT */
  84588. /************** End of insert.c **********************************************/
  84589. /************** Begin file legacy.c ******************************************/
  84590. /*
  84591. ** 2001 September 15
  84592. **
  84593. ** The author disclaims copyright to this source code. In place of
  84594. ** a legal notice, here is a blessing:
  84595. **
  84596. ** May you do good and not evil.
  84597. ** May you find forgiveness for yourself and forgive others.
  84598. ** May you share freely, never taking more than you give.
  84599. **
  84600. *************************************************************************
  84601. ** Main file for the SQLite library. The routines in this file
  84602. ** implement the programmer interface to the library. Routines in
  84603. ** other files are for internal use by SQLite and should not be
  84604. ** accessed by users of the library.
  84605. */
  84606. /*
  84607. ** Execute SQL code. Return one of the SQLITE_ success/failure
  84608. ** codes. Also write an error message into memory obtained from
  84609. ** malloc() and make *pzErrMsg point to that message.
  84610. **
  84611. ** If the SQL is a query, then for each row in the query result
  84612. ** the xCallback() function is called. pArg becomes the first
  84613. ** argument to xCallback(). If xCallback=NULL then no callback
  84614. ** is invoked, even for queries.
  84615. */
  84616. SQLITE_API int sqlite3_exec(
  84617. sqlite3 *db, /* The database on which the SQL executes */
  84618. const char *zSql, /* The SQL to be executed */
  84619. sqlite3_callback xCallback, /* Invoke this callback routine */
  84620. void *pArg, /* First argument to xCallback() */
  84621. char **pzErrMsg /* Write error messages here */
  84622. ){
  84623. int rc = SQLITE_OK; /* Return code */
  84624. const char *zLeftover; /* Tail of unprocessed SQL */
  84625. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  84626. char **azCols = 0; /* Names of result columns */
  84627. int nRetry = 0; /* Number of retry attempts */
  84628. int callbackIsInit; /* True if callback data is initialized */
  84629. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  84630. if( zSql==0 ) zSql = "";
  84631. sqlite3_mutex_enter(db->mutex);
  84632. sqlite3Error(db, SQLITE_OK, 0);
  84633. while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
  84634. int nCol;
  84635. char **azVals = 0;
  84636. pStmt = 0;
  84637. rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
  84638. assert( rc==SQLITE_OK || pStmt==0 );
  84639. if( rc!=SQLITE_OK ){
  84640. continue;
  84641. }
  84642. if( !pStmt ){
  84643. /* this happens for a comment or white-space */
  84644. zSql = zLeftover;
  84645. continue;
  84646. }
  84647. callbackIsInit = 0;
  84648. nCol = sqlite3_column_count(pStmt);
  84649. while( 1 ){
  84650. int i;
  84651. rc = sqlite3_step(pStmt);
  84652. /* Invoke the callback function if required */
  84653. if( xCallback && (SQLITE_ROW==rc ||
  84654. (SQLITE_DONE==rc && !callbackIsInit
  84655. && db->flags&SQLITE_NullCallback)) ){
  84656. if( !callbackIsInit ){
  84657. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  84658. if( azCols==0 ){
  84659. goto exec_out;
  84660. }
  84661. for(i=0; i<nCol; i++){
  84662. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  84663. /* sqlite3VdbeSetColName() installs column names as UTF8
  84664. ** strings so there is no way for sqlite3_column_name() to fail. */
  84665. assert( azCols[i]!=0 );
  84666. }
  84667. callbackIsInit = 1;
  84668. }
  84669. if( rc==SQLITE_ROW ){
  84670. azVals = &azCols[nCol];
  84671. for(i=0; i<nCol; i++){
  84672. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  84673. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  84674. db->mallocFailed = 1;
  84675. goto exec_out;
  84676. }
  84677. }
  84678. }
  84679. if( xCallback(pArg, nCol, azVals, azCols) ){
  84680. rc = SQLITE_ABORT;
  84681. sqlite3VdbeFinalize((Vdbe *)pStmt);
  84682. pStmt = 0;
  84683. sqlite3Error(db, SQLITE_ABORT, 0);
  84684. goto exec_out;
  84685. }
  84686. }
  84687. if( rc!=SQLITE_ROW ){
  84688. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  84689. pStmt = 0;
  84690. if( rc!=SQLITE_SCHEMA ){
  84691. nRetry = 0;
  84692. zSql = zLeftover;
  84693. while( sqlite3Isspace(zSql[0]) ) zSql++;
  84694. }
  84695. break;
  84696. }
  84697. }
  84698. sqlite3DbFree(db, azCols);
  84699. azCols = 0;
  84700. }
  84701. exec_out:
  84702. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  84703. sqlite3DbFree(db, azCols);
  84704. rc = sqlite3ApiExit(db, rc);
  84705. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  84706. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  84707. *pzErrMsg = sqlite3Malloc(nErrMsg);
  84708. if( *pzErrMsg ){
  84709. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  84710. }else{
  84711. rc = SQLITE_NOMEM;
  84712. sqlite3Error(db, SQLITE_NOMEM, 0);
  84713. }
  84714. }else if( pzErrMsg ){
  84715. *pzErrMsg = 0;
  84716. }
  84717. assert( (rc&db->errMask)==rc );
  84718. sqlite3_mutex_leave(db->mutex);
  84719. return rc;
  84720. }
  84721. /************** End of legacy.c **********************************************/
  84722. /************** Begin file loadext.c *****************************************/
  84723. /*
  84724. ** 2006 June 7
  84725. **
  84726. ** The author disclaims copyright to this source code. In place of
  84727. ** a legal notice, here is a blessing:
  84728. **
  84729. ** May you do good and not evil.
  84730. ** May you find forgiveness for yourself and forgive others.
  84731. ** May you share freely, never taking more than you give.
  84732. **
  84733. *************************************************************************
  84734. ** This file contains code used to dynamically load extensions into
  84735. ** the SQLite library.
  84736. */
  84737. #ifndef SQLITE_CORE
  84738. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  84739. #endif
  84740. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  84741. /************** Begin file sqlite3ext.h **************************************/
  84742. /*
  84743. ** 2006 June 7
  84744. **
  84745. ** The author disclaims copyright to this source code. In place of
  84746. ** a legal notice, here is a blessing:
  84747. **
  84748. ** May you do good and not evil.
  84749. ** May you find forgiveness for yourself and forgive others.
  84750. ** May you share freely, never taking more than you give.
  84751. **
  84752. *************************************************************************
  84753. ** This header file defines the SQLite interface for use by
  84754. ** shared libraries that want to be imported as extensions into
  84755. ** an SQLite instance. Shared libraries that intend to be loaded
  84756. ** as extensions by SQLite should #include this file instead of
  84757. ** sqlite3.h.
  84758. */
  84759. #ifndef _SQLITE3EXT_H_
  84760. #define _SQLITE3EXT_H_
  84761. typedef struct sqlite3_api_routines sqlite3_api_routines;
  84762. /*
  84763. ** The following structure holds pointers to all of the SQLite API
  84764. ** routines.
  84765. **
  84766. ** WARNING: In order to maintain backwards compatibility, add new
  84767. ** interfaces to the end of this structure only. If you insert new
  84768. ** interfaces in the middle of this structure, then older different
  84769. ** versions of SQLite will not be able to load each others' shared
  84770. ** libraries!
  84771. */
  84772. struct sqlite3_api_routines {
  84773. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  84774. int (*aggregate_count)(sqlite3_context*);
  84775. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  84776. int (*bind_double)(sqlite3_stmt*,int,double);
  84777. int (*bind_int)(sqlite3_stmt*,int,int);
  84778. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  84779. int (*bind_null)(sqlite3_stmt*,int);
  84780. int (*bind_parameter_count)(sqlite3_stmt*);
  84781. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  84782. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  84783. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  84784. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  84785. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  84786. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  84787. int (*busy_timeout)(sqlite3*,int ms);
  84788. int (*changes)(sqlite3*);
  84789. int (*close)(sqlite3*);
  84790. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  84791. int eTextRep,const char*));
  84792. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  84793. int eTextRep,const void*));
  84794. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  84795. int (*column_bytes)(sqlite3_stmt*,int iCol);
  84796. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  84797. int (*column_count)(sqlite3_stmt*pStmt);
  84798. const char * (*column_database_name)(sqlite3_stmt*,int);
  84799. const void * (*column_database_name16)(sqlite3_stmt*,int);
  84800. const char * (*column_decltype)(sqlite3_stmt*,int i);
  84801. const void * (*column_decltype16)(sqlite3_stmt*,int);
  84802. double (*column_double)(sqlite3_stmt*,int iCol);
  84803. int (*column_int)(sqlite3_stmt*,int iCol);
  84804. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  84805. const char * (*column_name)(sqlite3_stmt*,int);
  84806. const void * (*column_name16)(sqlite3_stmt*,int);
  84807. const char * (*column_origin_name)(sqlite3_stmt*,int);
  84808. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  84809. const char * (*column_table_name)(sqlite3_stmt*,int);
  84810. const void * (*column_table_name16)(sqlite3_stmt*,int);
  84811. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  84812. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  84813. int (*column_type)(sqlite3_stmt*,int iCol);
  84814. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  84815. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  84816. int (*complete)(const char*sql);
  84817. int (*complete16)(const void*sql);
  84818. int (*create_collation)(sqlite3*,const char*,int,void*,
  84819. int(*)(void*,int,const void*,int,const void*));
  84820. int (*create_collation16)(sqlite3*,const void*,int,void*,
  84821. int(*)(void*,int,const void*,int,const void*));
  84822. int (*create_function)(sqlite3*,const char*,int,int,void*,
  84823. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  84824. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  84825. void (*xFinal)(sqlite3_context*));
  84826. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  84827. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  84828. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  84829. void (*xFinal)(sqlite3_context*));
  84830. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  84831. int (*data_count)(sqlite3_stmt*pStmt);
  84832. sqlite3 * (*db_handle)(sqlite3_stmt*);
  84833. int (*declare_vtab)(sqlite3*,const char*);
  84834. int (*enable_shared_cache)(int);
  84835. int (*errcode)(sqlite3*db);
  84836. const char * (*errmsg)(sqlite3*);
  84837. const void * (*errmsg16)(sqlite3*);
  84838. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  84839. int (*expired)(sqlite3_stmt*);
  84840. int (*finalize)(sqlite3_stmt*pStmt);
  84841. void (*free)(void*);
  84842. void (*free_table)(char**result);
  84843. int (*get_autocommit)(sqlite3*);
  84844. void * (*get_auxdata)(sqlite3_context*,int);
  84845. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  84846. int (*global_recover)(void);
  84847. void (*interruptx)(sqlite3*);
  84848. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  84849. const char * (*libversion)(void);
  84850. int (*libversion_number)(void);
  84851. void *(*malloc)(int);
  84852. char * (*mprintf)(const char*,...);
  84853. int (*open)(const char*,sqlite3**);
  84854. int (*open16)(const void*,sqlite3**);
  84855. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  84856. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  84857. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  84858. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  84859. void *(*realloc)(void*,int);
  84860. int (*reset)(sqlite3_stmt*pStmt);
  84861. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  84862. void (*result_double)(sqlite3_context*,double);
  84863. void (*result_error)(sqlite3_context*,const char*,int);
  84864. void (*result_error16)(sqlite3_context*,const void*,int);
  84865. void (*result_int)(sqlite3_context*,int);
  84866. void (*result_int64)(sqlite3_context*,sqlite_int64);
  84867. void (*result_null)(sqlite3_context*);
  84868. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  84869. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  84870. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  84871. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  84872. void (*result_value)(sqlite3_context*,sqlite3_value*);
  84873. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  84874. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  84875. const char*,const char*),void*);
  84876. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  84877. char * (*snprintf)(int,char*,const char*,...);
  84878. int (*step)(sqlite3_stmt*);
  84879. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  84880. char const**,char const**,int*,int*,int*);
  84881. void (*thread_cleanup)(void);
  84882. int (*total_changes)(sqlite3*);
  84883. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  84884. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  84885. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  84886. sqlite_int64),void*);
  84887. void * (*user_data)(sqlite3_context*);
  84888. const void * (*value_blob)(sqlite3_value*);
  84889. int (*value_bytes)(sqlite3_value*);
  84890. int (*value_bytes16)(sqlite3_value*);
  84891. double (*value_double)(sqlite3_value*);
  84892. int (*value_int)(sqlite3_value*);
  84893. sqlite_int64 (*value_int64)(sqlite3_value*);
  84894. int (*value_numeric_type)(sqlite3_value*);
  84895. const unsigned char * (*value_text)(sqlite3_value*);
  84896. const void * (*value_text16)(sqlite3_value*);
  84897. const void * (*value_text16be)(sqlite3_value*);
  84898. const void * (*value_text16le)(sqlite3_value*);
  84899. int (*value_type)(sqlite3_value*);
  84900. char *(*vmprintf)(const char*,va_list);
  84901. /* Added ??? */
  84902. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  84903. /* Added by 3.3.13 */
  84904. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  84905. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  84906. int (*clear_bindings)(sqlite3_stmt*);
  84907. /* Added by 3.4.1 */
  84908. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  84909. void (*xDestroy)(void *));
  84910. /* Added by 3.5.0 */
  84911. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  84912. int (*blob_bytes)(sqlite3_blob*);
  84913. int (*blob_close)(sqlite3_blob*);
  84914. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  84915. int,sqlite3_blob**);
  84916. int (*blob_read)(sqlite3_blob*,void*,int,int);
  84917. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  84918. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  84919. int(*)(void*,int,const void*,int,const void*),
  84920. void(*)(void*));
  84921. int (*file_control)(sqlite3*,const char*,int,void*);
  84922. sqlite3_int64 (*memory_highwater)(int);
  84923. sqlite3_int64 (*memory_used)(void);
  84924. sqlite3_mutex *(*mutex_alloc)(int);
  84925. void (*mutex_enter)(sqlite3_mutex*);
  84926. void (*mutex_free)(sqlite3_mutex*);
  84927. void (*mutex_leave)(sqlite3_mutex*);
  84928. int (*mutex_try)(sqlite3_mutex*);
  84929. int (*open_v2)(const char*,sqlite3**,int,const char*);
  84930. int (*release_memory)(int);
  84931. void (*result_error_nomem)(sqlite3_context*);
  84932. void (*result_error_toobig)(sqlite3_context*);
  84933. int (*sleep)(int);
  84934. void (*soft_heap_limit)(int);
  84935. sqlite3_vfs *(*vfs_find)(const char*);
  84936. int (*vfs_register)(sqlite3_vfs*,int);
  84937. int (*vfs_unregister)(sqlite3_vfs*);
  84938. int (*xthreadsafe)(void);
  84939. void (*result_zeroblob)(sqlite3_context*,int);
  84940. void (*result_error_code)(sqlite3_context*,int);
  84941. int (*test_control)(int, ...);
  84942. void (*randomness)(int,void*);
  84943. sqlite3 *(*context_db_handle)(sqlite3_context*);
  84944. int (*extended_result_codes)(sqlite3*,int);
  84945. int (*limit)(sqlite3*,int,int);
  84946. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  84947. const char *(*sql)(sqlite3_stmt*);
  84948. int (*status)(int,int*,int*,int);
  84949. int (*backup_finish)(sqlite3_backup*);
  84950. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  84951. int (*backup_pagecount)(sqlite3_backup*);
  84952. int (*backup_remaining)(sqlite3_backup*);
  84953. int (*backup_step)(sqlite3_backup*,int);
  84954. const char *(*compileoption_get)(int);
  84955. int (*compileoption_used)(const char*);
  84956. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  84957. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  84958. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  84959. void (*xFinal)(sqlite3_context*),
  84960. void(*xDestroy)(void*));
  84961. int (*db_config)(sqlite3*,int,...);
  84962. sqlite3_mutex *(*db_mutex)(sqlite3*);
  84963. int (*db_status)(sqlite3*,int,int*,int*,int);
  84964. int (*extended_errcode)(sqlite3*);
  84965. void (*log)(int,const char*,...);
  84966. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  84967. const char *(*sourceid)(void);
  84968. int (*stmt_status)(sqlite3_stmt*,int,int);
  84969. int (*strnicmp)(const char*,const char*,int);
  84970. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  84971. int (*wal_autocheckpoint)(sqlite3*,int);
  84972. int (*wal_checkpoint)(sqlite3*,const char*);
  84973. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  84974. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  84975. int (*vtab_config)(sqlite3*,int op,...);
  84976. int (*vtab_on_conflict)(sqlite3*);
  84977. };
  84978. /*
  84979. ** The following macros redefine the API routines so that they are
  84980. ** redirected throught the global sqlite3_api structure.
  84981. **
  84982. ** This header file is also used by the loadext.c source file
  84983. ** (part of the main SQLite library - not an extension) so that
  84984. ** it can get access to the sqlite3_api_routines structure
  84985. ** definition. But the main library does not want to redefine
  84986. ** the API. So the redefinition macros are only valid if the
  84987. ** SQLITE_CORE macros is undefined.
  84988. */
  84989. #ifndef SQLITE_CORE
  84990. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  84991. #ifndef SQLITE_OMIT_DEPRECATED
  84992. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  84993. #endif
  84994. #define sqlite3_bind_blob sqlite3_api->bind_blob
  84995. #define sqlite3_bind_double sqlite3_api->bind_double
  84996. #define sqlite3_bind_int sqlite3_api->bind_int
  84997. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  84998. #define sqlite3_bind_null sqlite3_api->bind_null
  84999. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  85000. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  85001. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  85002. #define sqlite3_bind_text sqlite3_api->bind_text
  85003. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  85004. #define sqlite3_bind_value sqlite3_api->bind_value
  85005. #define sqlite3_busy_handler sqlite3_api->busy_handler
  85006. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  85007. #define sqlite3_changes sqlite3_api->changes
  85008. #define sqlite3_close sqlite3_api->close
  85009. #define sqlite3_collation_needed sqlite3_api->collation_needed
  85010. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  85011. #define sqlite3_column_blob sqlite3_api->column_blob
  85012. #define sqlite3_column_bytes sqlite3_api->column_bytes
  85013. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  85014. #define sqlite3_column_count sqlite3_api->column_count
  85015. #define sqlite3_column_database_name sqlite3_api->column_database_name
  85016. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  85017. #define sqlite3_column_decltype sqlite3_api->column_decltype
  85018. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  85019. #define sqlite3_column_double sqlite3_api->column_double
  85020. #define sqlite3_column_int sqlite3_api->column_int
  85021. #define sqlite3_column_int64 sqlite3_api->column_int64
  85022. #define sqlite3_column_name sqlite3_api->column_name
  85023. #define sqlite3_column_name16 sqlite3_api->column_name16
  85024. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  85025. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  85026. #define sqlite3_column_table_name sqlite3_api->column_table_name
  85027. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  85028. #define sqlite3_column_text sqlite3_api->column_text
  85029. #define sqlite3_column_text16 sqlite3_api->column_text16
  85030. #define sqlite3_column_type sqlite3_api->column_type
  85031. #define sqlite3_column_value sqlite3_api->column_value
  85032. #define sqlite3_commit_hook sqlite3_api->commit_hook
  85033. #define sqlite3_complete sqlite3_api->complete
  85034. #define sqlite3_complete16 sqlite3_api->complete16
  85035. #define sqlite3_create_collation sqlite3_api->create_collation
  85036. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  85037. #define sqlite3_create_function sqlite3_api->create_function
  85038. #define sqlite3_create_function16 sqlite3_api->create_function16
  85039. #define sqlite3_create_module sqlite3_api->create_module
  85040. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  85041. #define sqlite3_data_count sqlite3_api->data_count
  85042. #define sqlite3_db_handle sqlite3_api->db_handle
  85043. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  85044. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  85045. #define sqlite3_errcode sqlite3_api->errcode
  85046. #define sqlite3_errmsg sqlite3_api->errmsg
  85047. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  85048. #define sqlite3_exec sqlite3_api->exec
  85049. #ifndef SQLITE_OMIT_DEPRECATED
  85050. #define sqlite3_expired sqlite3_api->expired
  85051. #endif
  85052. #define sqlite3_finalize sqlite3_api->finalize
  85053. #define sqlite3_free sqlite3_api->free
  85054. #define sqlite3_free_table sqlite3_api->free_table
  85055. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  85056. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  85057. #define sqlite3_get_table sqlite3_api->get_table
  85058. #ifndef SQLITE_OMIT_DEPRECATED
  85059. #define sqlite3_global_recover sqlite3_api->global_recover
  85060. #endif
  85061. #define sqlite3_interrupt sqlite3_api->interruptx
  85062. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  85063. #define sqlite3_libversion sqlite3_api->libversion
  85064. #define sqlite3_libversion_number sqlite3_api->libversion_number
  85065. #define sqlite3_malloc sqlite3_api->malloc
  85066. #define sqlite3_mprintf sqlite3_api->mprintf
  85067. #define sqlite3_open sqlite3_api->open
  85068. #define sqlite3_open16 sqlite3_api->open16
  85069. #define sqlite3_prepare sqlite3_api->prepare
  85070. #define sqlite3_prepare16 sqlite3_api->prepare16
  85071. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  85072. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  85073. #define sqlite3_profile sqlite3_api->profile
  85074. #define sqlite3_progress_handler sqlite3_api->progress_handler
  85075. #define sqlite3_realloc sqlite3_api->realloc
  85076. #define sqlite3_reset sqlite3_api->reset
  85077. #define sqlite3_result_blob sqlite3_api->result_blob
  85078. #define sqlite3_result_double sqlite3_api->result_double
  85079. #define sqlite3_result_error sqlite3_api->result_error
  85080. #define sqlite3_result_error16 sqlite3_api->result_error16
  85081. #define sqlite3_result_int sqlite3_api->result_int
  85082. #define sqlite3_result_int64 sqlite3_api->result_int64
  85083. #define sqlite3_result_null sqlite3_api->result_null
  85084. #define sqlite3_result_text sqlite3_api->result_text
  85085. #define sqlite3_result_text16 sqlite3_api->result_text16
  85086. #define sqlite3_result_text16be sqlite3_api->result_text16be
  85087. #define sqlite3_result_text16le sqlite3_api->result_text16le
  85088. #define sqlite3_result_value sqlite3_api->result_value
  85089. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  85090. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  85091. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  85092. #define sqlite3_snprintf sqlite3_api->snprintf
  85093. #define sqlite3_step sqlite3_api->step
  85094. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  85095. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  85096. #define sqlite3_total_changes sqlite3_api->total_changes
  85097. #define sqlite3_trace sqlite3_api->trace
  85098. #ifndef SQLITE_OMIT_DEPRECATED
  85099. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  85100. #endif
  85101. #define sqlite3_update_hook sqlite3_api->update_hook
  85102. #define sqlite3_user_data sqlite3_api->user_data
  85103. #define sqlite3_value_blob sqlite3_api->value_blob
  85104. #define sqlite3_value_bytes sqlite3_api->value_bytes
  85105. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  85106. #define sqlite3_value_double sqlite3_api->value_double
  85107. #define sqlite3_value_int sqlite3_api->value_int
  85108. #define sqlite3_value_int64 sqlite3_api->value_int64
  85109. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  85110. #define sqlite3_value_text sqlite3_api->value_text
  85111. #define sqlite3_value_text16 sqlite3_api->value_text16
  85112. #define sqlite3_value_text16be sqlite3_api->value_text16be
  85113. #define sqlite3_value_text16le sqlite3_api->value_text16le
  85114. #define sqlite3_value_type sqlite3_api->value_type
  85115. #define sqlite3_vmprintf sqlite3_api->vmprintf
  85116. #define sqlite3_overload_function sqlite3_api->overload_function
  85117. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  85118. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  85119. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  85120. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  85121. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  85122. #define sqlite3_blob_close sqlite3_api->blob_close
  85123. #define sqlite3_blob_open sqlite3_api->blob_open
  85124. #define sqlite3_blob_read sqlite3_api->blob_read
  85125. #define sqlite3_blob_write sqlite3_api->blob_write
  85126. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  85127. #define sqlite3_file_control sqlite3_api->file_control
  85128. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  85129. #define sqlite3_memory_used sqlite3_api->memory_used
  85130. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  85131. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  85132. #define sqlite3_mutex_free sqlite3_api->mutex_free
  85133. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  85134. #define sqlite3_mutex_try sqlite3_api->mutex_try
  85135. #define sqlite3_open_v2 sqlite3_api->open_v2
  85136. #define sqlite3_release_memory sqlite3_api->release_memory
  85137. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  85138. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  85139. #define sqlite3_sleep sqlite3_api->sleep
  85140. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  85141. #define sqlite3_vfs_find sqlite3_api->vfs_find
  85142. #define sqlite3_vfs_register sqlite3_api->vfs_register
  85143. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  85144. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  85145. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  85146. #define sqlite3_result_error_code sqlite3_api->result_error_code
  85147. #define sqlite3_test_control sqlite3_api->test_control
  85148. #define sqlite3_randomness sqlite3_api->randomness
  85149. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  85150. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  85151. #define sqlite3_limit sqlite3_api->limit
  85152. #define sqlite3_next_stmt sqlite3_api->next_stmt
  85153. #define sqlite3_sql sqlite3_api->sql
  85154. #define sqlite3_status sqlite3_api->status
  85155. #define sqlite3_backup_finish sqlite3_api->backup_finish
  85156. #define sqlite3_backup_init sqlite3_api->backup_init
  85157. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  85158. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  85159. #define sqlite3_backup_step sqlite3_api->backup_step
  85160. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  85161. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  85162. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  85163. #define sqlite3_db_config sqlite3_api->db_config
  85164. #define sqlite3_db_mutex sqlite3_api->db_mutex
  85165. #define sqlite3_db_status sqlite3_api->db_status
  85166. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  85167. #define sqlite3_log sqlite3_api->log
  85168. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  85169. #define sqlite3_sourceid sqlite3_api->sourceid
  85170. #define sqlite3_stmt_status sqlite3_api->stmt_status
  85171. #define sqlite3_strnicmp sqlite3_api->strnicmp
  85172. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  85173. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  85174. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  85175. #define sqlite3_wal_hook sqlite3_api->wal_hook
  85176. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  85177. #define sqlite3_vtab_config sqlite3_api->vtab_config
  85178. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  85179. #endif /* SQLITE_CORE */
  85180. #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
  85181. #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
  85182. #endif /* _SQLITE3EXT_H_ */
  85183. /************** End of sqlite3ext.h ******************************************/
  85184. /************** Continuing where we left off in loadext.c ********************/
  85185. /* #include <string.h> */
  85186. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  85187. /*
  85188. ** Some API routines are omitted when various features are
  85189. ** excluded from a build of SQLite. Substitute a NULL pointer
  85190. ** for any missing APIs.
  85191. */
  85192. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  85193. # define sqlite3_column_database_name 0
  85194. # define sqlite3_column_database_name16 0
  85195. # define sqlite3_column_table_name 0
  85196. # define sqlite3_column_table_name16 0
  85197. # define sqlite3_column_origin_name 0
  85198. # define sqlite3_column_origin_name16 0
  85199. # define sqlite3_table_column_metadata 0
  85200. #endif
  85201. #ifdef SQLITE_OMIT_AUTHORIZATION
  85202. # define sqlite3_set_authorizer 0
  85203. #endif
  85204. #ifdef SQLITE_OMIT_UTF16
  85205. # define sqlite3_bind_text16 0
  85206. # define sqlite3_collation_needed16 0
  85207. # define sqlite3_column_decltype16 0
  85208. # define sqlite3_column_name16 0
  85209. # define sqlite3_column_text16 0
  85210. # define sqlite3_complete16 0
  85211. # define sqlite3_create_collation16 0
  85212. # define sqlite3_create_function16 0
  85213. # define sqlite3_errmsg16 0
  85214. # define sqlite3_open16 0
  85215. # define sqlite3_prepare16 0
  85216. # define sqlite3_prepare16_v2 0
  85217. # define sqlite3_result_error16 0
  85218. # define sqlite3_result_text16 0
  85219. # define sqlite3_result_text16be 0
  85220. # define sqlite3_result_text16le 0
  85221. # define sqlite3_value_text16 0
  85222. # define sqlite3_value_text16be 0
  85223. # define sqlite3_value_text16le 0
  85224. # define sqlite3_column_database_name16 0
  85225. # define sqlite3_column_table_name16 0
  85226. # define sqlite3_column_origin_name16 0
  85227. #endif
  85228. #ifdef SQLITE_OMIT_COMPLETE
  85229. # define sqlite3_complete 0
  85230. # define sqlite3_complete16 0
  85231. #endif
  85232. #ifdef SQLITE_OMIT_DECLTYPE
  85233. # define sqlite3_column_decltype16 0
  85234. # define sqlite3_column_decltype 0
  85235. #endif
  85236. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  85237. # define sqlite3_progress_handler 0
  85238. #endif
  85239. #ifdef SQLITE_OMIT_VIRTUALTABLE
  85240. # define sqlite3_create_module 0
  85241. # define sqlite3_create_module_v2 0
  85242. # define sqlite3_declare_vtab 0
  85243. # define sqlite3_vtab_config 0
  85244. # define sqlite3_vtab_on_conflict 0
  85245. #endif
  85246. #ifdef SQLITE_OMIT_SHARED_CACHE
  85247. # define sqlite3_enable_shared_cache 0
  85248. #endif
  85249. #ifdef SQLITE_OMIT_TRACE
  85250. # define sqlite3_profile 0
  85251. # define sqlite3_trace 0
  85252. #endif
  85253. #ifdef SQLITE_OMIT_GET_TABLE
  85254. # define sqlite3_free_table 0
  85255. # define sqlite3_get_table 0
  85256. #endif
  85257. #ifdef SQLITE_OMIT_INCRBLOB
  85258. #define sqlite3_bind_zeroblob 0
  85259. #define sqlite3_blob_bytes 0
  85260. #define sqlite3_blob_close 0
  85261. #define sqlite3_blob_open 0
  85262. #define sqlite3_blob_read 0
  85263. #define sqlite3_blob_write 0
  85264. #define sqlite3_blob_reopen 0
  85265. #endif
  85266. /*
  85267. ** The following structure contains pointers to all SQLite API routines.
  85268. ** A pointer to this structure is passed into extensions when they are
  85269. ** loaded so that the extension can make calls back into the SQLite
  85270. ** library.
  85271. **
  85272. ** When adding new APIs, add them to the bottom of this structure
  85273. ** in order to preserve backwards compatibility.
  85274. **
  85275. ** Extensions that use newer APIs should first call the
  85276. ** sqlite3_libversion_number() to make sure that the API they
  85277. ** intend to use is supported by the library. Extensions should
  85278. ** also check to make sure that the pointer to the function is
  85279. ** not NULL before calling it.
  85280. */
  85281. static const sqlite3_api_routines sqlite3Apis = {
  85282. sqlite3_aggregate_context,
  85283. #ifndef SQLITE_OMIT_DEPRECATED
  85284. sqlite3_aggregate_count,
  85285. #else
  85286. 0,
  85287. #endif
  85288. sqlite3_bind_blob,
  85289. sqlite3_bind_double,
  85290. sqlite3_bind_int,
  85291. sqlite3_bind_int64,
  85292. sqlite3_bind_null,
  85293. sqlite3_bind_parameter_count,
  85294. sqlite3_bind_parameter_index,
  85295. sqlite3_bind_parameter_name,
  85296. sqlite3_bind_text,
  85297. sqlite3_bind_text16,
  85298. sqlite3_bind_value,
  85299. sqlite3_busy_handler,
  85300. sqlite3_busy_timeout,
  85301. sqlite3_changes,
  85302. sqlite3_close,
  85303. sqlite3_collation_needed,
  85304. sqlite3_collation_needed16,
  85305. sqlite3_column_blob,
  85306. sqlite3_column_bytes,
  85307. sqlite3_column_bytes16,
  85308. sqlite3_column_count,
  85309. sqlite3_column_database_name,
  85310. sqlite3_column_database_name16,
  85311. sqlite3_column_decltype,
  85312. sqlite3_column_decltype16,
  85313. sqlite3_column_double,
  85314. sqlite3_column_int,
  85315. sqlite3_column_int64,
  85316. sqlite3_column_name,
  85317. sqlite3_column_name16,
  85318. sqlite3_column_origin_name,
  85319. sqlite3_column_origin_name16,
  85320. sqlite3_column_table_name,
  85321. sqlite3_column_table_name16,
  85322. sqlite3_column_text,
  85323. sqlite3_column_text16,
  85324. sqlite3_column_type,
  85325. sqlite3_column_value,
  85326. sqlite3_commit_hook,
  85327. sqlite3_complete,
  85328. sqlite3_complete16,
  85329. sqlite3_create_collation,
  85330. sqlite3_create_collation16,
  85331. sqlite3_create_function,
  85332. sqlite3_create_function16,
  85333. sqlite3_create_module,
  85334. sqlite3_data_count,
  85335. sqlite3_db_handle,
  85336. sqlite3_declare_vtab,
  85337. sqlite3_enable_shared_cache,
  85338. sqlite3_errcode,
  85339. sqlite3_errmsg,
  85340. sqlite3_errmsg16,
  85341. sqlite3_exec,
  85342. #ifndef SQLITE_OMIT_DEPRECATED
  85343. sqlite3_expired,
  85344. #else
  85345. 0,
  85346. #endif
  85347. sqlite3_finalize,
  85348. sqlite3_free,
  85349. sqlite3_free_table,
  85350. sqlite3_get_autocommit,
  85351. sqlite3_get_auxdata,
  85352. sqlite3_get_table,
  85353. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  85354. sqlite3_interrupt,
  85355. sqlite3_last_insert_rowid,
  85356. sqlite3_libversion,
  85357. sqlite3_libversion_number,
  85358. sqlite3_malloc,
  85359. sqlite3_mprintf,
  85360. sqlite3_open,
  85361. sqlite3_open16,
  85362. sqlite3_prepare,
  85363. sqlite3_prepare16,
  85364. sqlite3_profile,
  85365. sqlite3_progress_handler,
  85366. sqlite3_realloc,
  85367. sqlite3_reset,
  85368. sqlite3_result_blob,
  85369. sqlite3_result_double,
  85370. sqlite3_result_error,
  85371. sqlite3_result_error16,
  85372. sqlite3_result_int,
  85373. sqlite3_result_int64,
  85374. sqlite3_result_null,
  85375. sqlite3_result_text,
  85376. sqlite3_result_text16,
  85377. sqlite3_result_text16be,
  85378. sqlite3_result_text16le,
  85379. sqlite3_result_value,
  85380. sqlite3_rollback_hook,
  85381. sqlite3_set_authorizer,
  85382. sqlite3_set_auxdata,
  85383. sqlite3_snprintf,
  85384. sqlite3_step,
  85385. sqlite3_table_column_metadata,
  85386. #ifndef SQLITE_OMIT_DEPRECATED
  85387. sqlite3_thread_cleanup,
  85388. #else
  85389. 0,
  85390. #endif
  85391. sqlite3_total_changes,
  85392. sqlite3_trace,
  85393. #ifndef SQLITE_OMIT_DEPRECATED
  85394. sqlite3_transfer_bindings,
  85395. #else
  85396. 0,
  85397. #endif
  85398. sqlite3_update_hook,
  85399. sqlite3_user_data,
  85400. sqlite3_value_blob,
  85401. sqlite3_value_bytes,
  85402. sqlite3_value_bytes16,
  85403. sqlite3_value_double,
  85404. sqlite3_value_int,
  85405. sqlite3_value_int64,
  85406. sqlite3_value_numeric_type,
  85407. sqlite3_value_text,
  85408. sqlite3_value_text16,
  85409. sqlite3_value_text16be,
  85410. sqlite3_value_text16le,
  85411. sqlite3_value_type,
  85412. sqlite3_vmprintf,
  85413. /*
  85414. ** The original API set ends here. All extensions can call any
  85415. ** of the APIs above provided that the pointer is not NULL. But
  85416. ** before calling APIs that follow, extension should check the
  85417. ** sqlite3_libversion_number() to make sure they are dealing with
  85418. ** a library that is new enough to support that API.
  85419. *************************************************************************
  85420. */
  85421. sqlite3_overload_function,
  85422. /*
  85423. ** Added after 3.3.13
  85424. */
  85425. sqlite3_prepare_v2,
  85426. sqlite3_prepare16_v2,
  85427. sqlite3_clear_bindings,
  85428. /*
  85429. ** Added for 3.4.1
  85430. */
  85431. sqlite3_create_module_v2,
  85432. /*
  85433. ** Added for 3.5.0
  85434. */
  85435. sqlite3_bind_zeroblob,
  85436. sqlite3_blob_bytes,
  85437. sqlite3_blob_close,
  85438. sqlite3_blob_open,
  85439. sqlite3_blob_read,
  85440. sqlite3_blob_write,
  85441. sqlite3_create_collation_v2,
  85442. sqlite3_file_control,
  85443. sqlite3_memory_highwater,
  85444. sqlite3_memory_used,
  85445. #ifdef SQLITE_MUTEX_OMIT
  85446. 0,
  85447. 0,
  85448. 0,
  85449. 0,
  85450. 0,
  85451. #else
  85452. sqlite3_mutex_alloc,
  85453. sqlite3_mutex_enter,
  85454. sqlite3_mutex_free,
  85455. sqlite3_mutex_leave,
  85456. sqlite3_mutex_try,
  85457. #endif
  85458. sqlite3_open_v2,
  85459. sqlite3_release_memory,
  85460. sqlite3_result_error_nomem,
  85461. sqlite3_result_error_toobig,
  85462. sqlite3_sleep,
  85463. sqlite3_soft_heap_limit,
  85464. sqlite3_vfs_find,
  85465. sqlite3_vfs_register,
  85466. sqlite3_vfs_unregister,
  85467. /*
  85468. ** Added for 3.5.8
  85469. */
  85470. sqlite3_threadsafe,
  85471. sqlite3_result_zeroblob,
  85472. sqlite3_result_error_code,
  85473. sqlite3_test_control,
  85474. sqlite3_randomness,
  85475. sqlite3_context_db_handle,
  85476. /*
  85477. ** Added for 3.6.0
  85478. */
  85479. sqlite3_extended_result_codes,
  85480. sqlite3_limit,
  85481. sqlite3_next_stmt,
  85482. sqlite3_sql,
  85483. sqlite3_status,
  85484. /*
  85485. ** Added for 3.7.4
  85486. */
  85487. sqlite3_backup_finish,
  85488. sqlite3_backup_init,
  85489. sqlite3_backup_pagecount,
  85490. sqlite3_backup_remaining,
  85491. sqlite3_backup_step,
  85492. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  85493. sqlite3_compileoption_get,
  85494. sqlite3_compileoption_used,
  85495. #else
  85496. 0,
  85497. 0,
  85498. #endif
  85499. sqlite3_create_function_v2,
  85500. sqlite3_db_config,
  85501. sqlite3_db_mutex,
  85502. sqlite3_db_status,
  85503. sqlite3_extended_errcode,
  85504. sqlite3_log,
  85505. sqlite3_soft_heap_limit64,
  85506. sqlite3_sourceid,
  85507. sqlite3_stmt_status,
  85508. sqlite3_strnicmp,
  85509. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  85510. sqlite3_unlock_notify,
  85511. #else
  85512. 0,
  85513. #endif
  85514. #ifndef SQLITE_OMIT_WAL
  85515. sqlite3_wal_autocheckpoint,
  85516. sqlite3_wal_checkpoint,
  85517. sqlite3_wal_hook,
  85518. #else
  85519. 0,
  85520. 0,
  85521. 0,
  85522. #endif
  85523. sqlite3_blob_reopen,
  85524. sqlite3_vtab_config,
  85525. sqlite3_vtab_on_conflict,
  85526. };
  85527. /*
  85528. ** Attempt to load an SQLite extension library contained in the file
  85529. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  85530. ** default entry point name (sqlite3_extension_init) is used. Use
  85531. ** of the default name is recommended.
  85532. **
  85533. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  85534. **
  85535. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  85536. ** error message text. The calling function should free this memory
  85537. ** by calling sqlite3DbFree(db, ).
  85538. */
  85539. static int sqlite3LoadExtension(
  85540. sqlite3 *db, /* Load the extension into this database connection */
  85541. const char *zFile, /* Name of the shared library containing extension */
  85542. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  85543. char **pzErrMsg /* Put error message here if not 0 */
  85544. ){
  85545. sqlite3_vfs *pVfs = db->pVfs;
  85546. void *handle;
  85547. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  85548. char *zErrmsg = 0;
  85549. void **aHandle;
  85550. int nMsg = 300 + sqlite3Strlen30(zFile);
  85551. if( pzErrMsg ) *pzErrMsg = 0;
  85552. /* Ticket #1863. To avoid a creating security problems for older
  85553. ** applications that relink against newer versions of SQLite, the
  85554. ** ability to run load_extension is turned off by default. One
  85555. ** must call sqlite3_enable_load_extension() to turn on extension
  85556. ** loading. Otherwise you get the following error.
  85557. */
  85558. if( (db->flags & SQLITE_LoadExtension)==0 ){
  85559. if( pzErrMsg ){
  85560. *pzErrMsg = sqlite3_mprintf("not authorized");
  85561. }
  85562. return SQLITE_ERROR;
  85563. }
  85564. if( zProc==0 ){
  85565. zProc = "sqlite3_extension_init";
  85566. }
  85567. handle = sqlite3OsDlOpen(pVfs, zFile);
  85568. if( handle==0 ){
  85569. if( pzErrMsg ){
  85570. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  85571. if( zErrmsg ){
  85572. sqlite3_snprintf(nMsg, zErrmsg,
  85573. "unable to open shared library [%s]", zFile);
  85574. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  85575. }
  85576. }
  85577. return SQLITE_ERROR;
  85578. }
  85579. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  85580. sqlite3OsDlSym(pVfs, handle, zProc);
  85581. if( xInit==0 ){
  85582. if( pzErrMsg ){
  85583. nMsg += sqlite3Strlen30(zProc);
  85584. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  85585. if( zErrmsg ){
  85586. sqlite3_snprintf(nMsg, zErrmsg,
  85587. "no entry point [%s] in shared library [%s]", zProc,zFile);
  85588. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  85589. }
  85590. sqlite3OsDlClose(pVfs, handle);
  85591. }
  85592. return SQLITE_ERROR;
  85593. }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  85594. if( pzErrMsg ){
  85595. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  85596. }
  85597. sqlite3_free(zErrmsg);
  85598. sqlite3OsDlClose(pVfs, handle);
  85599. return SQLITE_ERROR;
  85600. }
  85601. /* Append the new shared library handle to the db->aExtension array. */
  85602. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  85603. if( aHandle==0 ){
  85604. return SQLITE_NOMEM;
  85605. }
  85606. if( db->nExtension>0 ){
  85607. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  85608. }
  85609. sqlite3DbFree(db, db->aExtension);
  85610. db->aExtension = aHandle;
  85611. db->aExtension[db->nExtension++] = handle;
  85612. return SQLITE_OK;
  85613. }
  85614. SQLITE_API int sqlite3_load_extension(
  85615. sqlite3 *db, /* Load the extension into this database connection */
  85616. const char *zFile, /* Name of the shared library containing extension */
  85617. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  85618. char **pzErrMsg /* Put error message here if not 0 */
  85619. ){
  85620. int rc;
  85621. sqlite3_mutex_enter(db->mutex);
  85622. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  85623. rc = sqlite3ApiExit(db, rc);
  85624. sqlite3_mutex_leave(db->mutex);
  85625. return rc;
  85626. }
  85627. /*
  85628. ** Call this routine when the database connection is closing in order
  85629. ** to clean up loaded extensions
  85630. */
  85631. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  85632. int i;
  85633. assert( sqlite3_mutex_held(db->mutex) );
  85634. for(i=0; i<db->nExtension; i++){
  85635. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  85636. }
  85637. sqlite3DbFree(db, db->aExtension);
  85638. }
  85639. /*
  85640. ** Enable or disable extension loading. Extension loading is disabled by
  85641. ** default so as not to open security holes in older applications.
  85642. */
  85643. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  85644. sqlite3_mutex_enter(db->mutex);
  85645. if( onoff ){
  85646. db->flags |= SQLITE_LoadExtension;
  85647. }else{
  85648. db->flags &= ~SQLITE_LoadExtension;
  85649. }
  85650. sqlite3_mutex_leave(db->mutex);
  85651. return SQLITE_OK;
  85652. }
  85653. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  85654. /*
  85655. ** The auto-extension code added regardless of whether or not extension
  85656. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  85657. ** code if regular extension loading is not available. This is that
  85658. ** dummy pointer.
  85659. */
  85660. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  85661. static const sqlite3_api_routines sqlite3Apis = { 0 };
  85662. #endif
  85663. /*
  85664. ** The following object holds the list of automatically loaded
  85665. ** extensions.
  85666. **
  85667. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  85668. ** mutex must be held while accessing this list.
  85669. */
  85670. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  85671. static SQLITE_WSD struct sqlite3AutoExtList {
  85672. int nExt; /* Number of entries in aExt[] */
  85673. void (**aExt)(void); /* Pointers to the extension init functions */
  85674. } sqlite3Autoext = { 0, 0 };
  85675. /* The "wsdAutoext" macro will resolve to the autoextension
  85676. ** state vector. If writable static data is unsupported on the target,
  85677. ** we have to locate the state vector at run-time. In the more common
  85678. ** case where writable static data is supported, wsdStat can refer directly
  85679. ** to the "sqlite3Autoext" state vector declared above.
  85680. */
  85681. #ifdef SQLITE_OMIT_WSD
  85682. # define wsdAutoextInit \
  85683. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  85684. # define wsdAutoext x[0]
  85685. #else
  85686. # define wsdAutoextInit
  85687. # define wsdAutoext sqlite3Autoext
  85688. #endif
  85689. /*
  85690. ** Register a statically linked extension that is automatically
  85691. ** loaded by every new database connection.
  85692. */
  85693. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  85694. int rc = SQLITE_OK;
  85695. #ifndef SQLITE_OMIT_AUTOINIT
  85696. rc = sqlite3_initialize();
  85697. if( rc ){
  85698. return rc;
  85699. }else
  85700. #endif
  85701. {
  85702. int i;
  85703. #if SQLITE_THREADSAFE
  85704. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  85705. #endif
  85706. wsdAutoextInit;
  85707. sqlite3_mutex_enter(mutex);
  85708. for(i=0; i<wsdAutoext.nExt; i++){
  85709. if( wsdAutoext.aExt[i]==xInit ) break;
  85710. }
  85711. if( i==wsdAutoext.nExt ){
  85712. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  85713. void (**aNew)(void);
  85714. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  85715. if( aNew==0 ){
  85716. rc = SQLITE_NOMEM;
  85717. }else{
  85718. wsdAutoext.aExt = aNew;
  85719. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  85720. wsdAutoext.nExt++;
  85721. }
  85722. }
  85723. sqlite3_mutex_leave(mutex);
  85724. assert( (rc&0xff)==rc );
  85725. return rc;
  85726. }
  85727. }
  85728. /*
  85729. ** Reset the automatic extension loading mechanism.
  85730. */
  85731. SQLITE_API void sqlite3_reset_auto_extension(void){
  85732. #ifndef SQLITE_OMIT_AUTOINIT
  85733. if( sqlite3_initialize()==SQLITE_OK )
  85734. #endif
  85735. {
  85736. #if SQLITE_THREADSAFE
  85737. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  85738. #endif
  85739. wsdAutoextInit;
  85740. sqlite3_mutex_enter(mutex);
  85741. sqlite3_free(wsdAutoext.aExt);
  85742. wsdAutoext.aExt = 0;
  85743. wsdAutoext.nExt = 0;
  85744. sqlite3_mutex_leave(mutex);
  85745. }
  85746. }
  85747. /*
  85748. ** Load all automatic extensions.
  85749. **
  85750. ** If anything goes wrong, set an error in the database connection.
  85751. */
  85752. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  85753. int i;
  85754. int go = 1;
  85755. int rc;
  85756. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  85757. wsdAutoextInit;
  85758. if( wsdAutoext.nExt==0 ){
  85759. /* Common case: early out without every having to acquire a mutex */
  85760. return;
  85761. }
  85762. for(i=0; go; i++){
  85763. char *zErrmsg;
  85764. #if SQLITE_THREADSAFE
  85765. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  85766. #endif
  85767. sqlite3_mutex_enter(mutex);
  85768. if( i>=wsdAutoext.nExt ){
  85769. xInit = 0;
  85770. go = 0;
  85771. }else{
  85772. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  85773. wsdAutoext.aExt[i];
  85774. }
  85775. sqlite3_mutex_leave(mutex);
  85776. zErrmsg = 0;
  85777. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  85778. sqlite3Error(db, rc,
  85779. "automatic extension loading failed: %s", zErrmsg);
  85780. go = 0;
  85781. }
  85782. sqlite3_free(zErrmsg);
  85783. }
  85784. }
  85785. /************** End of loadext.c *********************************************/
  85786. /************** Begin file pragma.c ******************************************/
  85787. /*
  85788. ** 2003 April 6
  85789. **
  85790. ** The author disclaims copyright to this source code. In place of
  85791. ** a legal notice, here is a blessing:
  85792. **
  85793. ** May you do good and not evil.
  85794. ** May you find forgiveness for yourself and forgive others.
  85795. ** May you share freely, never taking more than you give.
  85796. **
  85797. *************************************************************************
  85798. ** This file contains code used to implement the PRAGMA command.
  85799. */
  85800. /*
  85801. ** Interpret the given string as a safety level. Return 0 for OFF,
  85802. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  85803. ** unrecognized string argument. The FULL option is disallowed
  85804. ** if the omitFull parameter it 1.
  85805. **
  85806. ** Note that the values returned are one less that the values that
  85807. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  85808. ** to support legacy SQL code. The safety level used to be boolean
  85809. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  85810. */
  85811. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  85812. /* 123456789 123456789 */
  85813. static const char zText[] = "onoffalseyestruefull";
  85814. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  85815. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  85816. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  85817. int i, n;
  85818. if( sqlite3Isdigit(*z) ){
  85819. return (u8)sqlite3Atoi(z);
  85820. }
  85821. n = sqlite3Strlen30(z);
  85822. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  85823. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  85824. return iValue[i];
  85825. }
  85826. }
  85827. return dflt;
  85828. }
  85829. /*
  85830. ** Interpret the given string as a boolean value.
  85831. */
  85832. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  85833. return getSafetyLevel(z,1,dflt)!=0;
  85834. }
  85835. /* The sqlite3GetBoolean() function is used by other modules but the
  85836. ** remainder of this file is specific to PRAGMA processing. So omit
  85837. ** the rest of the file if PRAGMAs are omitted from the build.
  85838. */
  85839. #if !defined(SQLITE_OMIT_PRAGMA)
  85840. /*
  85841. ** Interpret the given string as a locking mode value.
  85842. */
  85843. static int getLockingMode(const char *z){
  85844. if( z ){
  85845. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  85846. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  85847. }
  85848. return PAGER_LOCKINGMODE_QUERY;
  85849. }
  85850. #ifndef SQLITE_OMIT_AUTOVACUUM
  85851. /*
  85852. ** Interpret the given string as an auto-vacuum mode value.
  85853. **
  85854. ** The following strings, "none", "full" and "incremental" are
  85855. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  85856. */
  85857. static int getAutoVacuum(const char *z){
  85858. int i;
  85859. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  85860. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  85861. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  85862. i = sqlite3Atoi(z);
  85863. return (u8)((i>=0&&i<=2)?i:0);
  85864. }
  85865. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  85866. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85867. /*
  85868. ** Interpret the given string as a temp db location. Return 1 for file
  85869. ** backed temporary databases, 2 for the Red-Black tree in memory database
  85870. ** and 0 to use the compile-time default.
  85871. */
  85872. static int getTempStore(const char *z){
  85873. if( z[0]>='0' && z[0]<='2' ){
  85874. return z[0] - '0';
  85875. }else if( sqlite3StrICmp(z, "file")==0 ){
  85876. return 1;
  85877. }else if( sqlite3StrICmp(z, "memory")==0 ){
  85878. return 2;
  85879. }else{
  85880. return 0;
  85881. }
  85882. }
  85883. #endif /* SQLITE_PAGER_PRAGMAS */
  85884. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85885. /*
  85886. ** Invalidate temp storage, either when the temp storage is changed
  85887. ** from default, or when 'file' and the temp_store_directory has changed
  85888. */
  85889. static int invalidateTempStorage(Parse *pParse){
  85890. sqlite3 *db = pParse->db;
  85891. if( db->aDb[1].pBt!=0 ){
  85892. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  85893. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  85894. "from within a transaction");
  85895. return SQLITE_ERROR;
  85896. }
  85897. sqlite3BtreeClose(db->aDb[1].pBt);
  85898. db->aDb[1].pBt = 0;
  85899. sqlite3ResetAllSchemasOfConnection(db);
  85900. }
  85901. return SQLITE_OK;
  85902. }
  85903. #endif /* SQLITE_PAGER_PRAGMAS */
  85904. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85905. /*
  85906. ** If the TEMP database is open, close it and mark the database schema
  85907. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  85908. ** or DEFAULT_TEMP_STORE pragmas.
  85909. */
  85910. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  85911. int ts = getTempStore(zStorageType);
  85912. sqlite3 *db = pParse->db;
  85913. if( db->temp_store==ts ) return SQLITE_OK;
  85914. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  85915. return SQLITE_ERROR;
  85916. }
  85917. db->temp_store = (u8)ts;
  85918. return SQLITE_OK;
  85919. }
  85920. #endif /* SQLITE_PAGER_PRAGMAS */
  85921. /*
  85922. ** Generate code to return a single integer value.
  85923. */
  85924. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  85925. Vdbe *v = sqlite3GetVdbe(pParse);
  85926. int mem = ++pParse->nMem;
  85927. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  85928. if( pI64 ){
  85929. memcpy(pI64, &value, sizeof(value));
  85930. }
  85931. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  85932. sqlite3VdbeSetNumCols(v, 1);
  85933. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  85934. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  85935. }
  85936. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  85937. /*
  85938. ** Check to see if zRight and zLeft refer to a pragma that queries
  85939. ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  85940. ** Also, implement the pragma.
  85941. */
  85942. static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  85943. static const struct sPragmaType {
  85944. const char *zName; /* Name of the pragma */
  85945. int mask; /* Mask for the db->flags value */
  85946. } aPragma[] = {
  85947. { "full_column_names", SQLITE_FullColNames },
  85948. { "short_column_names", SQLITE_ShortColNames },
  85949. { "count_changes", SQLITE_CountRows },
  85950. { "empty_result_callbacks", SQLITE_NullCallback },
  85951. { "legacy_file_format", SQLITE_LegacyFileFmt },
  85952. { "fullfsync", SQLITE_FullFSync },
  85953. { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
  85954. { "reverse_unordered_selects", SQLITE_ReverseOrder },
  85955. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  85956. { "automatic_index", SQLITE_AutoIndex },
  85957. #endif
  85958. #ifdef SQLITE_DEBUG
  85959. { "sql_trace", SQLITE_SqlTrace },
  85960. { "vdbe_listing", SQLITE_VdbeListing },
  85961. { "vdbe_trace", SQLITE_VdbeTrace },
  85962. #endif
  85963. #ifndef SQLITE_OMIT_CHECK
  85964. { "ignore_check_constraints", SQLITE_IgnoreChecks },
  85965. #endif
  85966. /* The following is VERY experimental */
  85967. { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
  85968. /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
  85969. ** flag if there are any active statements. */
  85970. { "read_uncommitted", SQLITE_ReadUncommitted },
  85971. { "recursive_triggers", SQLITE_RecTriggers },
  85972. /* This flag may only be set if both foreign-key and trigger support
  85973. ** are present in the build. */
  85974. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  85975. { "foreign_keys", SQLITE_ForeignKeys },
  85976. #endif
  85977. };
  85978. int i;
  85979. const struct sPragmaType *p;
  85980. for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
  85981. if( sqlite3StrICmp(zLeft, p->zName)==0 ){
  85982. sqlite3 *db = pParse->db;
  85983. Vdbe *v;
  85984. v = sqlite3GetVdbe(pParse);
  85985. assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
  85986. if( ALWAYS(v) ){
  85987. if( zRight==0 ){
  85988. returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
  85989. }else{
  85990. int mask = p->mask; /* Mask of bits to set or clear. */
  85991. if( db->autoCommit==0 ){
  85992. /* Foreign key support may not be enabled or disabled while not
  85993. ** in auto-commit mode. */
  85994. mask &= ~(SQLITE_ForeignKeys);
  85995. }
  85996. if( sqlite3GetBoolean(zRight, 0) ){
  85997. db->flags |= mask;
  85998. }else{
  85999. db->flags &= ~mask;
  86000. }
  86001. /* Many of the flag-pragmas modify the code generated by the SQL
  86002. ** compiler (eg. count_changes). So add an opcode to expire all
  86003. ** compiled SQL statements after modifying a pragma value.
  86004. */
  86005. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  86006. }
  86007. }
  86008. return 1;
  86009. }
  86010. }
  86011. return 0;
  86012. }
  86013. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  86014. /*
  86015. ** Return a human-readable name for a constraint resolution action.
  86016. */
  86017. #ifndef SQLITE_OMIT_FOREIGN_KEY
  86018. static const char *actionName(u8 action){
  86019. const char *zName;
  86020. switch( action ){
  86021. case OE_SetNull: zName = "SET NULL"; break;
  86022. case OE_SetDflt: zName = "SET DEFAULT"; break;
  86023. case OE_Cascade: zName = "CASCADE"; break;
  86024. case OE_Restrict: zName = "RESTRICT"; break;
  86025. default: zName = "NO ACTION";
  86026. assert( action==OE_None ); break;
  86027. }
  86028. return zName;
  86029. }
  86030. #endif
  86031. /*
  86032. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  86033. ** defined in pager.h. This function returns the associated lowercase
  86034. ** journal-mode name.
  86035. */
  86036. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  86037. static char * const azModeName[] = {
  86038. "delete", "persist", "off", "truncate", "memory"
  86039. #ifndef SQLITE_OMIT_WAL
  86040. , "wal"
  86041. #endif
  86042. };
  86043. assert( PAGER_JOURNALMODE_DELETE==0 );
  86044. assert( PAGER_JOURNALMODE_PERSIST==1 );
  86045. assert( PAGER_JOURNALMODE_OFF==2 );
  86046. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  86047. assert( PAGER_JOURNALMODE_MEMORY==4 );
  86048. assert( PAGER_JOURNALMODE_WAL==5 );
  86049. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  86050. if( eMode==ArraySize(azModeName) ) return 0;
  86051. return azModeName[eMode];
  86052. }
  86053. /*
  86054. ** Process a pragma statement.
  86055. **
  86056. ** Pragmas are of this form:
  86057. **
  86058. ** PRAGMA [database.]id [= value]
  86059. **
  86060. ** The identifier might also be a string. The value is a string, and
  86061. ** identifier, or a number. If minusFlag is true, then the value is
  86062. ** a number that was preceded by a minus sign.
  86063. **
  86064. ** If the left side is "database.id" then pId1 is the database name
  86065. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  86066. ** id and pId2 is any empty string.
  86067. */
  86068. SQLITE_PRIVATE void sqlite3Pragma(
  86069. Parse *pParse,
  86070. Token *pId1, /* First part of [database.]id field */
  86071. Token *pId2, /* Second part of [database.]id field, or NULL */
  86072. Token *pValue, /* Token for <value>, or NULL */
  86073. int minusFlag /* True if a '-' sign preceded <value> */
  86074. ){
  86075. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  86076. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  86077. const char *zDb = 0; /* The database name */
  86078. Token *pId; /* Pointer to <id> token */
  86079. int iDb; /* Database index for <database> */
  86080. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  86081. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  86082. sqlite3 *db = pParse->db; /* The database connection */
  86083. Db *pDb; /* The specific database being pragmaed */
  86084. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db); /* Prepared statement */
  86085. if( v==0 ) return;
  86086. sqlite3VdbeRunOnlyOnce(v);
  86087. pParse->nMem = 2;
  86088. /* Interpret the [database.] part of the pragma statement. iDb is the
  86089. ** index of the database this pragma is being applied to in db.aDb[]. */
  86090. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  86091. if( iDb<0 ) return;
  86092. pDb = &db->aDb[iDb];
  86093. /* If the temp database has been explicitly named as part of the
  86094. ** pragma, make sure it is open.
  86095. */
  86096. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  86097. return;
  86098. }
  86099. zLeft = sqlite3NameFromToken(db, pId);
  86100. if( !zLeft ) return;
  86101. if( minusFlag ){
  86102. zRight = sqlite3MPrintf(db, "-%T", pValue);
  86103. }else{
  86104. zRight = sqlite3NameFromToken(db, pValue);
  86105. }
  86106. assert( pId2 );
  86107. zDb = pId2->n>0 ? pDb->zName : 0;
  86108. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  86109. goto pragma_out;
  86110. }
  86111. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  86112. ** connection. If it returns SQLITE_OK, then assume that the VFS
  86113. ** handled the pragma and generate a no-op prepared statement.
  86114. */
  86115. aFcntl[0] = 0;
  86116. aFcntl[1] = zLeft;
  86117. aFcntl[2] = zRight;
  86118. aFcntl[3] = 0;
  86119. db->busyHandler.nBusy = 0;
  86120. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  86121. if( rc==SQLITE_OK ){
  86122. if( aFcntl[0] ){
  86123. int mem = ++pParse->nMem;
  86124. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  86125. sqlite3VdbeSetNumCols(v, 1);
  86126. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  86127. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  86128. sqlite3_free(aFcntl[0]);
  86129. }
  86130. }else if( rc!=SQLITE_NOTFOUND ){
  86131. if( aFcntl[0] ){
  86132. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  86133. sqlite3_free(aFcntl[0]);
  86134. }
  86135. pParse->nErr++;
  86136. pParse->rc = rc;
  86137. }else
  86138. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  86139. /*
  86140. ** PRAGMA [database.]default_cache_size
  86141. ** PRAGMA [database.]default_cache_size=N
  86142. **
  86143. ** The first form reports the current persistent setting for the
  86144. ** page cache size. The value returned is the maximum number of
  86145. ** pages in the page cache. The second form sets both the current
  86146. ** page cache size value and the persistent page cache size value
  86147. ** stored in the database file.
  86148. **
  86149. ** Older versions of SQLite would set the default cache size to a
  86150. ** negative number to indicate synchronous=OFF. These days, synchronous
  86151. ** is always on by default regardless of the sign of the default cache
  86152. ** size. But continue to take the absolute value of the default cache
  86153. ** size of historical compatibility.
  86154. */
  86155. if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
  86156. static const VdbeOpList getCacheSize[] = {
  86157. { OP_Transaction, 0, 0, 0}, /* 0 */
  86158. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  86159. { OP_IfPos, 1, 7, 0},
  86160. { OP_Integer, 0, 2, 0},
  86161. { OP_Subtract, 1, 2, 1},
  86162. { OP_IfPos, 1, 7, 0},
  86163. { OP_Integer, 0, 1, 0}, /* 6 */
  86164. { OP_ResultRow, 1, 1, 0},
  86165. };
  86166. int addr;
  86167. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86168. sqlite3VdbeUsesBtree(v, iDb);
  86169. if( !zRight ){
  86170. sqlite3VdbeSetNumCols(v, 1);
  86171. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  86172. pParse->nMem += 2;
  86173. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  86174. sqlite3VdbeChangeP1(v, addr, iDb);
  86175. sqlite3VdbeChangeP1(v, addr+1, iDb);
  86176. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  86177. }else{
  86178. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  86179. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86180. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  86181. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  86182. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86183. pDb->pSchema->cache_size = size;
  86184. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  86185. }
  86186. }else
  86187. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  86188. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  86189. /*
  86190. ** PRAGMA [database.]page_size
  86191. ** PRAGMA [database.]page_size=N
  86192. **
  86193. ** The first form reports the current setting for the
  86194. ** database page size in bytes. The second form sets the
  86195. ** database page size value. The value can only be set if
  86196. ** the database has not yet been created.
  86197. */
  86198. if( sqlite3StrICmp(zLeft,"page_size")==0 ){
  86199. Btree *pBt = pDb->pBt;
  86200. assert( pBt!=0 );
  86201. if( !zRight ){
  86202. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  86203. returnSingleInt(pParse, "page_size", size);
  86204. }else{
  86205. /* Malloc may fail when setting the page-size, as there is an internal
  86206. ** buffer that the pager module resizes using sqlite3_realloc().
  86207. */
  86208. db->nextPagesize = sqlite3Atoi(zRight);
  86209. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  86210. db->mallocFailed = 1;
  86211. }
  86212. }
  86213. }else
  86214. /*
  86215. ** PRAGMA [database.]secure_delete
  86216. ** PRAGMA [database.]secure_delete=ON/OFF
  86217. **
  86218. ** The first form reports the current setting for the
  86219. ** secure_delete flag. The second form changes the secure_delete
  86220. ** flag setting and reports thenew value.
  86221. */
  86222. if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
  86223. Btree *pBt = pDb->pBt;
  86224. int b = -1;
  86225. assert( pBt!=0 );
  86226. if( zRight ){
  86227. b = sqlite3GetBoolean(zRight, 0);
  86228. }
  86229. if( pId2->n==0 && b>=0 ){
  86230. int ii;
  86231. for(ii=0; ii<db->nDb; ii++){
  86232. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  86233. }
  86234. }
  86235. b = sqlite3BtreeSecureDelete(pBt, b);
  86236. returnSingleInt(pParse, "secure_delete", b);
  86237. }else
  86238. /*
  86239. ** PRAGMA [database.]max_page_count
  86240. ** PRAGMA [database.]max_page_count=N
  86241. **
  86242. ** The first form reports the current setting for the
  86243. ** maximum number of pages in the database file. The
  86244. ** second form attempts to change this setting. Both
  86245. ** forms return the current setting.
  86246. **
  86247. ** The absolute value of N is used. This is undocumented and might
  86248. ** change. The only purpose is to provide an easy way to test
  86249. ** the sqlite3AbsInt32() function.
  86250. **
  86251. ** PRAGMA [database.]page_count
  86252. **
  86253. ** Return the number of pages in the specified database.
  86254. */
  86255. if( sqlite3StrICmp(zLeft,"page_count")==0
  86256. || sqlite3StrICmp(zLeft,"max_page_count")==0
  86257. ){
  86258. int iReg;
  86259. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86260. sqlite3CodeVerifySchema(pParse, iDb);
  86261. iReg = ++pParse->nMem;
  86262. if( sqlite3Tolower(zLeft[0])=='p' ){
  86263. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  86264. }else{
  86265. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  86266. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  86267. }
  86268. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  86269. sqlite3VdbeSetNumCols(v, 1);
  86270. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  86271. }else
  86272. /*
  86273. ** PRAGMA [database.]locking_mode
  86274. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  86275. */
  86276. if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
  86277. const char *zRet = "normal";
  86278. int eMode = getLockingMode(zRight);
  86279. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  86280. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  86281. ** the current default locking mode (which may be different to
  86282. ** the locking-mode of the main database).
  86283. */
  86284. eMode = db->dfltLockMode;
  86285. }else{
  86286. Pager *pPager;
  86287. if( pId2->n==0 ){
  86288. /* This indicates that no database name was specified as part
  86289. ** of the PRAGMA command. In this case the locking-mode must be
  86290. ** set on all attached databases, as well as the main db file.
  86291. **
  86292. ** Also, the sqlite3.dfltLockMode variable is set so that
  86293. ** any subsequently attached databases also use the specified
  86294. ** locking mode.
  86295. */
  86296. int ii;
  86297. assert(pDb==&db->aDb[0]);
  86298. for(ii=2; ii<db->nDb; ii++){
  86299. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  86300. sqlite3PagerLockingMode(pPager, eMode);
  86301. }
  86302. db->dfltLockMode = (u8)eMode;
  86303. }
  86304. pPager = sqlite3BtreePager(pDb->pBt);
  86305. eMode = sqlite3PagerLockingMode(pPager, eMode);
  86306. }
  86307. assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
  86308. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  86309. zRet = "exclusive";
  86310. }
  86311. sqlite3VdbeSetNumCols(v, 1);
  86312. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  86313. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  86314. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  86315. }else
  86316. /*
  86317. ** PRAGMA [database.]journal_mode
  86318. ** PRAGMA [database.]journal_mode =
  86319. ** (delete|persist|off|truncate|memory|wal|off)
  86320. */
  86321. if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
  86322. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  86323. int ii; /* Loop counter */
  86324. /* Force the schema to be loaded on all databases. This causes all
  86325. ** database files to be opened and the journal_modes set. This is
  86326. ** necessary because subsequent processing must know if the databases
  86327. ** are in WAL mode. */
  86328. if( sqlite3ReadSchema(pParse) ){
  86329. goto pragma_out;
  86330. }
  86331. sqlite3VdbeSetNumCols(v, 1);
  86332. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  86333. if( zRight==0 ){
  86334. /* If there is no "=MODE" part of the pragma, do a query for the
  86335. ** current mode */
  86336. eMode = PAGER_JOURNALMODE_QUERY;
  86337. }else{
  86338. const char *zMode;
  86339. int n = sqlite3Strlen30(zRight);
  86340. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  86341. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  86342. }
  86343. if( !zMode ){
  86344. /* If the "=MODE" part does not match any known journal mode,
  86345. ** then do a query */
  86346. eMode = PAGER_JOURNALMODE_QUERY;
  86347. }
  86348. }
  86349. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  86350. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  86351. iDb = 0;
  86352. pId2->n = 1;
  86353. }
  86354. for(ii=db->nDb-1; ii>=0; ii--){
  86355. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  86356. sqlite3VdbeUsesBtree(v, ii);
  86357. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  86358. }
  86359. }
  86360. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  86361. }else
  86362. /*
  86363. ** PRAGMA [database.]journal_size_limit
  86364. ** PRAGMA [database.]journal_size_limit=N
  86365. **
  86366. ** Get or set the size limit on rollback journal files.
  86367. */
  86368. if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
  86369. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  86370. i64 iLimit = -2;
  86371. if( zRight ){
  86372. sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
  86373. if( iLimit<-1 ) iLimit = -1;
  86374. }
  86375. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  86376. returnSingleInt(pParse, "journal_size_limit", iLimit);
  86377. }else
  86378. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  86379. /*
  86380. ** PRAGMA [database.]auto_vacuum
  86381. ** PRAGMA [database.]auto_vacuum=N
  86382. **
  86383. ** Get or set the value of the database 'auto-vacuum' parameter.
  86384. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  86385. */
  86386. #ifndef SQLITE_OMIT_AUTOVACUUM
  86387. if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
  86388. Btree *pBt = pDb->pBt;
  86389. assert( pBt!=0 );
  86390. if( sqlite3ReadSchema(pParse) ){
  86391. goto pragma_out;
  86392. }
  86393. if( !zRight ){
  86394. int auto_vacuum;
  86395. if( ALWAYS(pBt) ){
  86396. auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
  86397. }else{
  86398. auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
  86399. }
  86400. returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
  86401. }else{
  86402. int eAuto = getAutoVacuum(zRight);
  86403. assert( eAuto>=0 && eAuto<=2 );
  86404. db->nextAutovac = (u8)eAuto;
  86405. if( ALWAYS(eAuto>=0) ){
  86406. /* Call SetAutoVacuum() to set initialize the internal auto and
  86407. ** incr-vacuum flags. This is required in case this connection
  86408. ** creates the database file. It is important that it is created
  86409. ** as an auto-vacuum capable db.
  86410. */
  86411. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  86412. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  86413. /* When setting the auto_vacuum mode to either "full" or
  86414. ** "incremental", write the value of meta[6] in the database
  86415. ** file. Before writing to meta[6], check that meta[3] indicates
  86416. ** that this really is an auto-vacuum capable database.
  86417. */
  86418. static const VdbeOpList setMeta6[] = {
  86419. { OP_Transaction, 0, 1, 0}, /* 0 */
  86420. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  86421. { OP_If, 1, 0, 0}, /* 2 */
  86422. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  86423. { OP_Integer, 0, 1, 0}, /* 4 */
  86424. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  86425. };
  86426. int iAddr;
  86427. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  86428. sqlite3VdbeChangeP1(v, iAddr, iDb);
  86429. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  86430. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  86431. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  86432. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  86433. sqlite3VdbeUsesBtree(v, iDb);
  86434. }
  86435. }
  86436. }
  86437. }else
  86438. #endif
  86439. /*
  86440. ** PRAGMA [database.]incremental_vacuum(N)
  86441. **
  86442. ** Do N steps of incremental vacuuming on a database.
  86443. */
  86444. #ifndef SQLITE_OMIT_AUTOVACUUM
  86445. if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
  86446. int iLimit, addr;
  86447. if( sqlite3ReadSchema(pParse) ){
  86448. goto pragma_out;
  86449. }
  86450. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  86451. iLimit = 0x7fffffff;
  86452. }
  86453. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86454. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  86455. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  86456. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  86457. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  86458. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  86459. sqlite3VdbeJumpHere(v, addr);
  86460. }else
  86461. #endif
  86462. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  86463. /*
  86464. ** PRAGMA [database.]cache_size
  86465. ** PRAGMA [database.]cache_size=N
  86466. **
  86467. ** The first form reports the current local setting for the
  86468. ** page cache size. The second form sets the local
  86469. ** page cache size value. If N is positive then that is the
  86470. ** number of pages in the cache. If N is negative, then the
  86471. ** number of pages is adjusted so that the cache uses -N kibibytes
  86472. ** of memory.
  86473. */
  86474. if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
  86475. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86476. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86477. if( !zRight ){
  86478. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  86479. }else{
  86480. int size = sqlite3Atoi(zRight);
  86481. pDb->pSchema->cache_size = size;
  86482. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  86483. }
  86484. }else
  86485. /*
  86486. ** PRAGMA temp_store
  86487. ** PRAGMA temp_store = "default"|"memory"|"file"
  86488. **
  86489. ** Return or set the local value of the temp_store flag. Changing
  86490. ** the local value does not make changes to the disk file and the default
  86491. ** value will be restored the next time the database is opened.
  86492. **
  86493. ** Note that it is possible for the library compile-time options to
  86494. ** override this setting
  86495. */
  86496. if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
  86497. if( !zRight ){
  86498. returnSingleInt(pParse, "temp_store", db->temp_store);
  86499. }else{
  86500. changeTempStorage(pParse, zRight);
  86501. }
  86502. }else
  86503. /*
  86504. ** PRAGMA temp_store_directory
  86505. ** PRAGMA temp_store_directory = ""|"directory_name"
  86506. **
  86507. ** Return or set the local value of the temp_store_directory flag. Changing
  86508. ** the value sets a specific directory to be used for temporary files.
  86509. ** Setting to a null string reverts to the default temporary directory search.
  86510. ** If temporary directory is changed, then invalidateTempStorage.
  86511. **
  86512. */
  86513. if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
  86514. if( !zRight ){
  86515. if( sqlite3_temp_directory ){
  86516. sqlite3VdbeSetNumCols(v, 1);
  86517. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  86518. "temp_store_directory", SQLITE_STATIC);
  86519. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  86520. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  86521. }
  86522. }else{
  86523. #ifndef SQLITE_OMIT_WSD
  86524. if( zRight[0] ){
  86525. int res;
  86526. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  86527. if( rc!=SQLITE_OK || res==0 ){
  86528. sqlite3ErrorMsg(pParse, "not a writable directory");
  86529. goto pragma_out;
  86530. }
  86531. }
  86532. if( SQLITE_TEMP_STORE==0
  86533. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  86534. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  86535. ){
  86536. invalidateTempStorage(pParse);
  86537. }
  86538. sqlite3_free(sqlite3_temp_directory);
  86539. if( zRight[0] ){
  86540. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  86541. }else{
  86542. sqlite3_temp_directory = 0;
  86543. }
  86544. #endif /* SQLITE_OMIT_WSD */
  86545. }
  86546. }else
  86547. #if SQLITE_OS_WIN
  86548. /*
  86549. ** PRAGMA data_store_directory
  86550. ** PRAGMA data_store_directory = ""|"directory_name"
  86551. **
  86552. ** Return or set the local value of the data_store_directory flag. Changing
  86553. ** the value sets a specific directory to be used for database files that
  86554. ** were specified with a relative pathname. Setting to a null string reverts
  86555. ** to the default database directory, which for database files specified with
  86556. ** a relative path will probably be based on the current directory for the
  86557. ** process. Database file specified with an absolute path are not impacted
  86558. ** by this setting, regardless of its value.
  86559. **
  86560. */
  86561. if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
  86562. if( !zRight ){
  86563. if( sqlite3_data_directory ){
  86564. sqlite3VdbeSetNumCols(v, 1);
  86565. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  86566. "data_store_directory", SQLITE_STATIC);
  86567. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  86568. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  86569. }
  86570. }else{
  86571. #ifndef SQLITE_OMIT_WSD
  86572. if( zRight[0] ){
  86573. int res;
  86574. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  86575. if( rc!=SQLITE_OK || res==0 ){
  86576. sqlite3ErrorMsg(pParse, "not a writable directory");
  86577. goto pragma_out;
  86578. }
  86579. }
  86580. sqlite3_free(sqlite3_data_directory);
  86581. if( zRight[0] ){
  86582. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  86583. }else{
  86584. sqlite3_data_directory = 0;
  86585. }
  86586. #endif /* SQLITE_OMIT_WSD */
  86587. }
  86588. }else
  86589. #endif
  86590. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  86591. # if defined(__APPLE__)
  86592. # define SQLITE_ENABLE_LOCKING_STYLE 1
  86593. # else
  86594. # define SQLITE_ENABLE_LOCKING_STYLE 0
  86595. # endif
  86596. #endif
  86597. #if SQLITE_ENABLE_LOCKING_STYLE
  86598. /*
  86599. ** PRAGMA [database.]lock_proxy_file
  86600. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  86601. **
  86602. ** Return or set the value of the lock_proxy_file flag. Changing
  86603. ** the value sets a specific file to be used for database access locks.
  86604. **
  86605. */
  86606. if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
  86607. if( !zRight ){
  86608. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  86609. char *proxy_file_path = NULL;
  86610. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  86611. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  86612. &proxy_file_path);
  86613. if( proxy_file_path ){
  86614. sqlite3VdbeSetNumCols(v, 1);
  86615. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  86616. "lock_proxy_file", SQLITE_STATIC);
  86617. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  86618. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  86619. }
  86620. }else{
  86621. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  86622. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  86623. int res;
  86624. if( zRight[0] ){
  86625. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  86626. zRight);
  86627. } else {
  86628. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  86629. NULL);
  86630. }
  86631. if( res!=SQLITE_OK ){
  86632. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  86633. goto pragma_out;
  86634. }
  86635. }
  86636. }else
  86637. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  86638. /*
  86639. ** PRAGMA [database.]synchronous
  86640. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  86641. **
  86642. ** Return or set the local value of the synchronous flag. Changing
  86643. ** the local value does not make changes to the disk file and the
  86644. ** default value will be restored the next time the database is
  86645. ** opened.
  86646. */
  86647. if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
  86648. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86649. if( !zRight ){
  86650. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  86651. }else{
  86652. if( !db->autoCommit ){
  86653. sqlite3ErrorMsg(pParse,
  86654. "Safety level may not be changed inside a transaction");
  86655. }else{
  86656. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  86657. }
  86658. }
  86659. }else
  86660. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  86661. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  86662. if( flagPragma(pParse, zLeft, zRight) ){
  86663. /* The flagPragma() subroutine also generates any necessary code
  86664. ** there is nothing more to do here */
  86665. }else
  86666. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  86667. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  86668. /*
  86669. ** PRAGMA table_info(<table>)
  86670. **
  86671. ** Return a single row for each column of the named table. The columns of
  86672. ** the returned data set are:
  86673. **
  86674. ** cid: Column id (numbered from left to right, starting at 0)
  86675. ** name: Column name
  86676. ** type: Column declaration type.
  86677. ** notnull: True if 'NOT NULL' is part of column declaration
  86678. ** dflt_value: The default value for the column, if any.
  86679. */
  86680. if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
  86681. Table *pTab;
  86682. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86683. pTab = sqlite3FindTable(db, zRight, zDb);
  86684. if( pTab ){
  86685. int i;
  86686. int nHidden = 0;
  86687. Column *pCol;
  86688. sqlite3VdbeSetNumCols(v, 6);
  86689. pParse->nMem = 6;
  86690. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  86691. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  86692. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  86693. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  86694. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  86695. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  86696. sqlite3ViewGetColumnNames(pParse, pTab);
  86697. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  86698. if( IsHiddenColumn(pCol) ){
  86699. nHidden++;
  86700. continue;
  86701. }
  86702. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  86703. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  86704. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  86705. pCol->zType ? pCol->zType : "", 0);
  86706. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  86707. if( pCol->zDflt ){
  86708. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  86709. }else{
  86710. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  86711. }
  86712. sqlite3VdbeAddOp2(v, OP_Integer,
  86713. (pCol->colFlags&COLFLAG_PRIMKEY)!=0, 6);
  86714. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  86715. }
  86716. }
  86717. }else
  86718. if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
  86719. Index *pIdx;
  86720. Table *pTab;
  86721. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86722. pIdx = sqlite3FindIndex(db, zRight, zDb);
  86723. if( pIdx ){
  86724. int i;
  86725. pTab = pIdx->pTable;
  86726. sqlite3VdbeSetNumCols(v, 3);
  86727. pParse->nMem = 3;
  86728. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  86729. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  86730. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  86731. for(i=0; i<pIdx->nColumn; i++){
  86732. int cnum = pIdx->aiColumn[i];
  86733. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  86734. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  86735. assert( pTab->nCol>cnum );
  86736. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  86737. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  86738. }
  86739. }
  86740. }else
  86741. if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
  86742. Index *pIdx;
  86743. Table *pTab;
  86744. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86745. pTab = sqlite3FindTable(db, zRight, zDb);
  86746. if( pTab ){
  86747. v = sqlite3GetVdbe(pParse);
  86748. pIdx = pTab->pIndex;
  86749. if( pIdx ){
  86750. int i = 0;
  86751. sqlite3VdbeSetNumCols(v, 3);
  86752. pParse->nMem = 3;
  86753. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  86754. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  86755. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  86756. while(pIdx){
  86757. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  86758. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  86759. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  86760. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  86761. ++i;
  86762. pIdx = pIdx->pNext;
  86763. }
  86764. }
  86765. }
  86766. }else
  86767. if( sqlite3StrICmp(zLeft, "database_list")==0 ){
  86768. int i;
  86769. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86770. sqlite3VdbeSetNumCols(v, 3);
  86771. pParse->nMem = 3;
  86772. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  86773. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  86774. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  86775. for(i=0; i<db->nDb; i++){
  86776. if( db->aDb[i].pBt==0 ) continue;
  86777. assert( db->aDb[i].zName!=0 );
  86778. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  86779. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  86780. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  86781. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  86782. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  86783. }
  86784. }else
  86785. if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
  86786. int i = 0;
  86787. HashElem *p;
  86788. sqlite3VdbeSetNumCols(v, 2);
  86789. pParse->nMem = 2;
  86790. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  86791. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  86792. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  86793. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  86794. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  86795. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  86796. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  86797. }
  86798. }else
  86799. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  86800. #ifndef SQLITE_OMIT_FOREIGN_KEY
  86801. if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
  86802. FKey *pFK;
  86803. Table *pTab;
  86804. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86805. pTab = sqlite3FindTable(db, zRight, zDb);
  86806. if( pTab ){
  86807. v = sqlite3GetVdbe(pParse);
  86808. pFK = pTab->pFKey;
  86809. if( pFK ){
  86810. int i = 0;
  86811. sqlite3VdbeSetNumCols(v, 8);
  86812. pParse->nMem = 8;
  86813. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  86814. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  86815. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  86816. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  86817. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  86818. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  86819. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  86820. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  86821. while(pFK){
  86822. int j;
  86823. for(j=0; j<pFK->nCol; j++){
  86824. char *zCol = pFK->aCol[j].zCol;
  86825. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  86826. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  86827. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  86828. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  86829. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  86830. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  86831. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  86832. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  86833. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  86834. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  86835. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  86836. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  86837. }
  86838. ++i;
  86839. pFK = pFK->pNextFrom;
  86840. }
  86841. }
  86842. }
  86843. }else
  86844. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  86845. #ifndef NDEBUG
  86846. if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
  86847. if( zRight ){
  86848. if( sqlite3GetBoolean(zRight, 0) ){
  86849. sqlite3ParserTrace(stderr, "parser: ");
  86850. }else{
  86851. sqlite3ParserTrace(0, 0);
  86852. }
  86853. }
  86854. }else
  86855. #endif
  86856. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  86857. ** used will be case sensitive or not depending on the RHS.
  86858. */
  86859. if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
  86860. if( zRight ){
  86861. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  86862. }
  86863. }else
  86864. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  86865. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  86866. #endif
  86867. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  86868. /* Pragma "quick_check" is an experimental reduced version of
  86869. ** integrity_check designed to detect most database corruption
  86870. ** without most of the overhead of a full integrity-check.
  86871. */
  86872. if( sqlite3StrICmp(zLeft, "integrity_check")==0
  86873. || sqlite3StrICmp(zLeft, "quick_check")==0
  86874. ){
  86875. int i, j, addr, mxErr;
  86876. /* Code that appears at the end of the integrity check. If no error
  86877. ** messages have been generated, output OK. Otherwise output the
  86878. ** error message
  86879. */
  86880. static const VdbeOpList endCode[] = {
  86881. { OP_AddImm, 1, 0, 0}, /* 0 */
  86882. { OP_IfNeg, 1, 0, 0}, /* 1 */
  86883. { OP_String8, 0, 3, 0}, /* 2 */
  86884. { OP_ResultRow, 3, 1, 0},
  86885. };
  86886. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  86887. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  86888. ** then iDb is set to the index of the database identified by <db>.
  86889. ** In this case, the integrity of database iDb only is verified by
  86890. ** the VDBE created below.
  86891. **
  86892. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  86893. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  86894. ** to -1 here, to indicate that the VDBE should verify the integrity
  86895. ** of all attached databases. */
  86896. assert( iDb>=0 );
  86897. assert( iDb==0 || pId2->z );
  86898. if( pId2->z==0 ) iDb = -1;
  86899. /* Initialize the VDBE program */
  86900. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  86901. pParse->nMem = 6;
  86902. sqlite3VdbeSetNumCols(v, 1);
  86903. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  86904. /* Set the maximum error count */
  86905. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  86906. if( zRight ){
  86907. sqlite3GetInt32(zRight, &mxErr);
  86908. if( mxErr<=0 ){
  86909. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  86910. }
  86911. }
  86912. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  86913. /* Do an integrity check on each database file */
  86914. for(i=0; i<db->nDb; i++){
  86915. HashElem *x;
  86916. Hash *pTbls;
  86917. int cnt = 0;
  86918. if( OMIT_TEMPDB && i==1 ) continue;
  86919. if( iDb>=0 && i!=iDb ) continue;
  86920. sqlite3CodeVerifySchema(pParse, i);
  86921. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  86922. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  86923. sqlite3VdbeJumpHere(v, addr);
  86924. /* Do an integrity check of the B-Tree
  86925. **
  86926. ** Begin by filling registers 2, 3, ... with the root pages numbers
  86927. ** for all tables and indices in the database.
  86928. */
  86929. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  86930. pTbls = &db->aDb[i].pSchema->tblHash;
  86931. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  86932. Table *pTab = sqliteHashData(x);
  86933. Index *pIdx;
  86934. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  86935. cnt++;
  86936. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86937. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  86938. cnt++;
  86939. }
  86940. }
  86941. /* Make sure sufficient number of registers have been allocated */
  86942. if( pParse->nMem < cnt+4 ){
  86943. pParse->nMem = cnt+4;
  86944. }
  86945. /* Do the b-tree integrity checks */
  86946. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  86947. sqlite3VdbeChangeP5(v, (u8)i);
  86948. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  86949. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  86950. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  86951. P4_DYNAMIC);
  86952. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  86953. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  86954. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  86955. sqlite3VdbeJumpHere(v, addr);
  86956. /* Make sure all the indices are constructed correctly.
  86957. */
  86958. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  86959. Table *pTab = sqliteHashData(x);
  86960. Index *pIdx;
  86961. int loopTop;
  86962. if( pTab->pIndex==0 ) continue;
  86963. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  86964. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  86965. sqlite3VdbeJumpHere(v, addr);
  86966. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  86967. sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
  86968. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  86969. sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
  86970. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  86971. int jmp2;
  86972. int r1;
  86973. static const VdbeOpList idxErr[] = {
  86974. { OP_AddImm, 1, -1, 0},
  86975. { OP_String8, 0, 3, 0}, /* 1 */
  86976. { OP_Rowid, 1, 4, 0},
  86977. { OP_String8, 0, 5, 0}, /* 3 */
  86978. { OP_String8, 0, 6, 0}, /* 4 */
  86979. { OP_Concat, 4, 3, 3},
  86980. { OP_Concat, 5, 3, 3},
  86981. { OP_Concat, 6, 3, 3},
  86982. { OP_ResultRow, 3, 1, 0},
  86983. { OP_IfPos, 1, 0, 0}, /* 9 */
  86984. { OP_Halt, 0, 0, 0},
  86985. };
  86986. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
  86987. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  86988. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  86989. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  86990. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  86991. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  86992. sqlite3VdbeJumpHere(v, addr+9);
  86993. sqlite3VdbeJumpHere(v, jmp2);
  86994. }
  86995. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  86996. sqlite3VdbeJumpHere(v, loopTop);
  86997. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  86998. static const VdbeOpList cntIdx[] = {
  86999. { OP_Integer, 0, 3, 0},
  87000. { OP_Rewind, 0, 0, 0}, /* 1 */
  87001. { OP_AddImm, 3, 1, 0},
  87002. { OP_Next, 0, 0, 0}, /* 3 */
  87003. { OP_Eq, 2, 0, 3}, /* 4 */
  87004. { OP_AddImm, 1, -1, 0},
  87005. { OP_String8, 0, 2, 0}, /* 6 */
  87006. { OP_String8, 0, 3, 0}, /* 7 */
  87007. { OP_Concat, 3, 2, 2},
  87008. { OP_ResultRow, 2, 1, 0},
  87009. };
  87010. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
  87011. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  87012. sqlite3VdbeJumpHere(v, addr);
  87013. addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  87014. sqlite3VdbeChangeP1(v, addr+1, j+2);
  87015. sqlite3VdbeChangeP2(v, addr+1, addr+4);
  87016. sqlite3VdbeChangeP1(v, addr+3, j+2);
  87017. sqlite3VdbeChangeP2(v, addr+3, addr+2);
  87018. sqlite3VdbeJumpHere(v, addr+4);
  87019. sqlite3VdbeChangeP4(v, addr+6,
  87020. "wrong # of entries in index ", P4_STATIC);
  87021. sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
  87022. }
  87023. }
  87024. }
  87025. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  87026. sqlite3VdbeChangeP2(v, addr, -mxErr);
  87027. sqlite3VdbeJumpHere(v, addr+1);
  87028. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  87029. }else
  87030. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  87031. #ifndef SQLITE_OMIT_UTF16
  87032. /*
  87033. ** PRAGMA encoding
  87034. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  87035. **
  87036. ** In its first form, this pragma returns the encoding of the main
  87037. ** database. If the database is not initialized, it is initialized now.
  87038. **
  87039. ** The second form of this pragma is a no-op if the main database file
  87040. ** has not already been initialized. In this case it sets the default
  87041. ** encoding that will be used for the main database file if a new file
  87042. ** is created. If an existing main database file is opened, then the
  87043. ** default text encoding for the existing database is used.
  87044. **
  87045. ** In all cases new databases created using the ATTACH command are
  87046. ** created to use the same default text encoding as the main database. If
  87047. ** the main database has not been initialized and/or created when ATTACH
  87048. ** is executed, this is done before the ATTACH operation.
  87049. **
  87050. ** In the second form this pragma sets the text encoding to be used in
  87051. ** new database files created using this database handle. It is only
  87052. ** useful if invoked immediately after the main database i
  87053. */
  87054. if( sqlite3StrICmp(zLeft, "encoding")==0 ){
  87055. static const struct EncName {
  87056. char *zName;
  87057. u8 enc;
  87058. } encnames[] = {
  87059. { "UTF8", SQLITE_UTF8 },
  87060. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  87061. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  87062. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  87063. { "UTF16le", SQLITE_UTF16LE },
  87064. { "UTF16be", SQLITE_UTF16BE },
  87065. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  87066. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  87067. { 0, 0 }
  87068. };
  87069. const struct EncName *pEnc;
  87070. if( !zRight ){ /* "PRAGMA encoding" */
  87071. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  87072. sqlite3VdbeSetNumCols(v, 1);
  87073. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  87074. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  87075. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  87076. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  87077. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  87078. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  87079. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  87080. }else{ /* "PRAGMA encoding = XXX" */
  87081. /* Only change the value of sqlite.enc if the database handle is not
  87082. ** initialized. If the main database exists, the new sqlite.enc value
  87083. ** will be overwritten when the schema is next loaded. If it does not
  87084. ** already exists, it will be created to use the new encoding value.
  87085. */
  87086. if(
  87087. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  87088. DbHasProperty(db, 0, DB_Empty)
  87089. ){
  87090. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  87091. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  87092. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  87093. break;
  87094. }
  87095. }
  87096. if( !pEnc->zName ){
  87097. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  87098. }
  87099. }
  87100. }
  87101. }else
  87102. #endif /* SQLITE_OMIT_UTF16 */
  87103. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  87104. /*
  87105. ** PRAGMA [database.]schema_version
  87106. ** PRAGMA [database.]schema_version = <integer>
  87107. **
  87108. ** PRAGMA [database.]user_version
  87109. ** PRAGMA [database.]user_version = <integer>
  87110. **
  87111. ** The pragma's schema_version and user_version are used to set or get
  87112. ** the value of the schema-version and user-version, respectively. Both
  87113. ** the schema-version and the user-version are 32-bit signed integers
  87114. ** stored in the database header.
  87115. **
  87116. ** The schema-cookie is usually only manipulated internally by SQLite. It
  87117. ** is incremented by SQLite whenever the database schema is modified (by
  87118. ** creating or dropping a table or index). The schema version is used by
  87119. ** SQLite each time a query is executed to ensure that the internal cache
  87120. ** of the schema used when compiling the SQL query matches the schema of
  87121. ** the database against which the compiled query is actually executed.
  87122. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  87123. ** the schema-version is potentially dangerous and may lead to program
  87124. ** crashes or database corruption. Use with caution!
  87125. **
  87126. ** The user-version is not used internally by SQLite. It may be used by
  87127. ** applications for any purpose.
  87128. */
  87129. if( sqlite3StrICmp(zLeft, "schema_version")==0
  87130. || sqlite3StrICmp(zLeft, "user_version")==0
  87131. || sqlite3StrICmp(zLeft, "freelist_count")==0
  87132. ){
  87133. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  87134. sqlite3VdbeUsesBtree(v, iDb);
  87135. switch( zLeft[0] ){
  87136. case 'f': case 'F':
  87137. iCookie = BTREE_FREE_PAGE_COUNT;
  87138. break;
  87139. case 's': case 'S':
  87140. iCookie = BTREE_SCHEMA_VERSION;
  87141. break;
  87142. default:
  87143. iCookie = BTREE_USER_VERSION;
  87144. break;
  87145. }
  87146. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  87147. /* Write the specified cookie value */
  87148. static const VdbeOpList setCookie[] = {
  87149. { OP_Transaction, 0, 1, 0}, /* 0 */
  87150. { OP_Integer, 0, 1, 0}, /* 1 */
  87151. { OP_SetCookie, 0, 0, 1}, /* 2 */
  87152. };
  87153. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  87154. sqlite3VdbeChangeP1(v, addr, iDb);
  87155. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  87156. sqlite3VdbeChangeP1(v, addr+2, iDb);
  87157. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  87158. }else{
  87159. /* Read the specified cookie value */
  87160. static const VdbeOpList readCookie[] = {
  87161. { OP_Transaction, 0, 0, 0}, /* 0 */
  87162. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  87163. { OP_ResultRow, 1, 1, 0}
  87164. };
  87165. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  87166. sqlite3VdbeChangeP1(v, addr, iDb);
  87167. sqlite3VdbeChangeP1(v, addr+1, iDb);
  87168. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  87169. sqlite3VdbeSetNumCols(v, 1);
  87170. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  87171. }
  87172. }else
  87173. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  87174. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  87175. /*
  87176. ** PRAGMA compile_options
  87177. **
  87178. ** Return the names of all compile-time options used in this build,
  87179. ** one option per row.
  87180. */
  87181. if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
  87182. int i = 0;
  87183. const char *zOpt;
  87184. sqlite3VdbeSetNumCols(v, 1);
  87185. pParse->nMem = 1;
  87186. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  87187. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  87188. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  87189. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  87190. }
  87191. }else
  87192. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  87193. #ifndef SQLITE_OMIT_WAL
  87194. /*
  87195. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  87196. **
  87197. ** Checkpoint the database.
  87198. */
  87199. if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
  87200. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  87201. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  87202. if( zRight ){
  87203. if( sqlite3StrICmp(zRight, "full")==0 ){
  87204. eMode = SQLITE_CHECKPOINT_FULL;
  87205. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  87206. eMode = SQLITE_CHECKPOINT_RESTART;
  87207. }
  87208. }
  87209. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  87210. sqlite3VdbeSetNumCols(v, 3);
  87211. pParse->nMem = 3;
  87212. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  87213. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  87214. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  87215. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  87216. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  87217. }else
  87218. /*
  87219. ** PRAGMA wal_autocheckpoint
  87220. ** PRAGMA wal_autocheckpoint = N
  87221. **
  87222. ** Configure a database connection to automatically checkpoint a database
  87223. ** after accumulating N frames in the log. Or query for the current value
  87224. ** of N.
  87225. */
  87226. if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
  87227. if( zRight ){
  87228. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  87229. }
  87230. returnSingleInt(pParse, "wal_autocheckpoint",
  87231. db->xWalCallback==sqlite3WalDefaultHook ?
  87232. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  87233. }else
  87234. #endif
  87235. /*
  87236. ** PRAGMA shrink_memory
  87237. **
  87238. ** This pragma attempts to free as much memory as possible from the
  87239. ** current database connection.
  87240. */
  87241. if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
  87242. sqlite3_db_release_memory(db);
  87243. }else
  87244. /*
  87245. ** PRAGMA busy_timeout
  87246. ** PRAGMA busy_timeout = N
  87247. **
  87248. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  87249. ** if one is set. If no busy handler or a different busy handler is set
  87250. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  87251. ** disables the timeout.
  87252. */
  87253. if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
  87254. if( zRight ){
  87255. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  87256. }
  87257. returnSingleInt(pParse, "timeout", db->busyTimeout);
  87258. }else
  87259. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  87260. /*
  87261. ** Report the current state of file logs for all databases
  87262. */
  87263. if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  87264. static const char *const azLockName[] = {
  87265. "unlocked", "shared", "reserved", "pending", "exclusive"
  87266. };
  87267. int i;
  87268. sqlite3VdbeSetNumCols(v, 2);
  87269. pParse->nMem = 2;
  87270. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  87271. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  87272. for(i=0; i<db->nDb; i++){
  87273. Btree *pBt;
  87274. const char *zState = "unknown";
  87275. int j;
  87276. if( db->aDb[i].zName==0 ) continue;
  87277. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  87278. pBt = db->aDb[i].pBt;
  87279. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  87280. zState = "closed";
  87281. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  87282. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  87283. zState = azLockName[j];
  87284. }
  87285. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  87286. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  87287. }
  87288. }else
  87289. #endif
  87290. #ifdef SQLITE_HAS_CODEC
  87291. if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
  87292. sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  87293. }else
  87294. if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
  87295. sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  87296. }else
  87297. if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
  87298. sqlite3StrICmp(zLeft, "hexrekey")==0) ){
  87299. int i, h1, h2;
  87300. char zKey[40];
  87301. for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
  87302. h1 += 9*(1&(h1>>6));
  87303. h2 += 9*(1&(h2>>6));
  87304. zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
  87305. }
  87306. if( (zLeft[3] & 0xf)==0xb ){
  87307. sqlite3_key(db, zKey, i/2);
  87308. }else{
  87309. sqlite3_rekey(db, zKey, i/2);
  87310. }
  87311. }else
  87312. #endif
  87313. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  87314. if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
  87315. #ifdef SQLITE_HAS_CODEC
  87316. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  87317. sqlite3_activate_see(&zRight[4]);
  87318. }
  87319. #endif
  87320. #ifdef SQLITE_ENABLE_CEROD
  87321. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  87322. sqlite3_activate_cerod(&zRight[6]);
  87323. }
  87324. #endif
  87325. }else
  87326. #endif
  87327. {/* Empty ELSE clause */}
  87328. /*
  87329. ** Reset the safety level, in case the fullfsync flag or synchronous
  87330. ** setting changed.
  87331. */
  87332. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87333. if( db->autoCommit ){
  87334. sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
  87335. (db->flags&SQLITE_FullFSync)!=0,
  87336. (db->flags&SQLITE_CkptFullFSync)!=0);
  87337. }
  87338. #endif
  87339. pragma_out:
  87340. sqlite3DbFree(db, zLeft);
  87341. sqlite3DbFree(db, zRight);
  87342. }
  87343. #endif /* SQLITE_OMIT_PRAGMA */
  87344. /************** End of pragma.c **********************************************/
  87345. /************** Begin file prepare.c *****************************************/
  87346. /*
  87347. ** 2005 May 25
  87348. **
  87349. ** The author disclaims copyright to this source code. In place of
  87350. ** a legal notice, here is a blessing:
  87351. **
  87352. ** May you do good and not evil.
  87353. ** May you find forgiveness for yourself and forgive others.
  87354. ** May you share freely, never taking more than you give.
  87355. **
  87356. *************************************************************************
  87357. ** This file contains the implementation of the sqlite3_prepare()
  87358. ** interface, and routines that contribute to loading the database schema
  87359. ** from disk.
  87360. */
  87361. /*
  87362. ** Fill the InitData structure with an error message that indicates
  87363. ** that the database is corrupt.
  87364. */
  87365. static void corruptSchema(
  87366. InitData *pData, /* Initialization context */
  87367. const char *zObj, /* Object being parsed at the point of error */
  87368. const char *zExtra /* Error information */
  87369. ){
  87370. sqlite3 *db = pData->db;
  87371. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  87372. if( zObj==0 ) zObj = "?";
  87373. sqlite3SetString(pData->pzErrMsg, db,
  87374. "malformed database schema (%s)", zObj);
  87375. if( zExtra ){
  87376. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  87377. "%s - %s", *pData->pzErrMsg, zExtra);
  87378. }
  87379. }
  87380. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  87381. }
  87382. /*
  87383. ** This is the callback routine for the code that initializes the
  87384. ** database. See sqlite3Init() below for additional information.
  87385. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  87386. **
  87387. ** Each callback contains the following information:
  87388. **
  87389. ** argv[0] = name of thing being created
  87390. ** argv[1] = root page number for table or index. 0 for trigger or view.
  87391. ** argv[2] = SQL text for the CREATE statement.
  87392. **
  87393. */
  87394. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  87395. InitData *pData = (InitData*)pInit;
  87396. sqlite3 *db = pData->db;
  87397. int iDb = pData->iDb;
  87398. assert( argc==3 );
  87399. UNUSED_PARAMETER2(NotUsed, argc);
  87400. assert( sqlite3_mutex_held(db->mutex) );
  87401. DbClearProperty(db, iDb, DB_Empty);
  87402. if( db->mallocFailed ){
  87403. corruptSchema(pData, argv[0], 0);
  87404. return 1;
  87405. }
  87406. assert( iDb>=0 && iDb<db->nDb );
  87407. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  87408. if( argv[1]==0 ){
  87409. corruptSchema(pData, argv[0], 0);
  87410. }else if( argv[2] && argv[2][0] ){
  87411. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  87412. ** But because db->init.busy is set to 1, no VDBE code is generated
  87413. ** or executed. All the parser does is build the internal data
  87414. ** structures that describe the table, index, or view.
  87415. */
  87416. int rc;
  87417. sqlite3_stmt *pStmt;
  87418. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  87419. assert( db->init.busy );
  87420. db->init.iDb = iDb;
  87421. db->init.newTnum = sqlite3Atoi(argv[1]);
  87422. db->init.orphanTrigger = 0;
  87423. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  87424. rc = db->errCode;
  87425. assert( (rc&0xFF)==(rcp&0xFF) );
  87426. db->init.iDb = 0;
  87427. if( SQLITE_OK!=rc ){
  87428. if( db->init.orphanTrigger ){
  87429. assert( iDb==1 );
  87430. }else{
  87431. pData->rc = rc;
  87432. if( rc==SQLITE_NOMEM ){
  87433. db->mallocFailed = 1;
  87434. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  87435. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  87436. }
  87437. }
  87438. }
  87439. sqlite3_finalize(pStmt);
  87440. }else if( argv[0]==0 ){
  87441. corruptSchema(pData, 0, 0);
  87442. }else{
  87443. /* If the SQL column is blank it means this is an index that
  87444. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  87445. ** constraint for a CREATE TABLE. The index should have already
  87446. ** been created when we processed the CREATE TABLE. All we have
  87447. ** to do here is record the root page number for that index.
  87448. */
  87449. Index *pIndex;
  87450. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  87451. if( pIndex==0 ){
  87452. /* This can occur if there exists an index on a TEMP table which
  87453. ** has the same name as another index on a permanent index. Since
  87454. ** the permanent table is hidden by the TEMP table, we can also
  87455. ** safely ignore the index on the permanent table.
  87456. */
  87457. /* Do Nothing */;
  87458. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  87459. corruptSchema(pData, argv[0], "invalid rootpage");
  87460. }
  87461. }
  87462. return 0;
  87463. }
  87464. /*
  87465. ** Attempt to read the database schema and initialize internal
  87466. ** data structures for a single database file. The index of the
  87467. ** database file is given by iDb. iDb==0 is used for the main
  87468. ** database. iDb==1 should never be used. iDb>=2 is used for
  87469. ** auxiliary databases. Return one of the SQLITE_ error codes to
  87470. ** indicate success or failure.
  87471. */
  87472. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  87473. int rc;
  87474. int i;
  87475. #ifndef SQLITE_OMIT_DEPRECATED
  87476. int size;
  87477. #endif
  87478. Table *pTab;
  87479. Db *pDb;
  87480. char const *azArg[4];
  87481. int meta[5];
  87482. InitData initData;
  87483. char const *zMasterSchema;
  87484. char const *zMasterName;
  87485. int openedTransaction = 0;
  87486. /*
  87487. ** The master database table has a structure like this
  87488. */
  87489. static const char master_schema[] =
  87490. "CREATE TABLE sqlite_master(\n"
  87491. " type text,\n"
  87492. " name text,\n"
  87493. " tbl_name text,\n"
  87494. " rootpage integer,\n"
  87495. " sql text\n"
  87496. ")"
  87497. ;
  87498. #ifndef SQLITE_OMIT_TEMPDB
  87499. static const char temp_master_schema[] =
  87500. "CREATE TEMP TABLE sqlite_temp_master(\n"
  87501. " type text,\n"
  87502. " name text,\n"
  87503. " tbl_name text,\n"
  87504. " rootpage integer,\n"
  87505. " sql text\n"
  87506. ")"
  87507. ;
  87508. #else
  87509. #define temp_master_schema 0
  87510. #endif
  87511. assert( iDb>=0 && iDb<db->nDb );
  87512. assert( db->aDb[iDb].pSchema );
  87513. assert( sqlite3_mutex_held(db->mutex) );
  87514. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  87515. /* zMasterSchema and zInitScript are set to point at the master schema
  87516. ** and initialisation script appropriate for the database being
  87517. ** initialised. zMasterName is the name of the master table.
  87518. */
  87519. if( !OMIT_TEMPDB && iDb==1 ){
  87520. zMasterSchema = temp_master_schema;
  87521. }else{
  87522. zMasterSchema = master_schema;
  87523. }
  87524. zMasterName = SCHEMA_TABLE(iDb);
  87525. /* Construct the schema tables. */
  87526. azArg[0] = zMasterName;
  87527. azArg[1] = "1";
  87528. azArg[2] = zMasterSchema;
  87529. azArg[3] = 0;
  87530. initData.db = db;
  87531. initData.iDb = iDb;
  87532. initData.rc = SQLITE_OK;
  87533. initData.pzErrMsg = pzErrMsg;
  87534. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  87535. if( initData.rc ){
  87536. rc = initData.rc;
  87537. goto error_out;
  87538. }
  87539. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  87540. if( ALWAYS(pTab) ){
  87541. pTab->tabFlags |= TF_Readonly;
  87542. }
  87543. /* Create a cursor to hold the database open
  87544. */
  87545. pDb = &db->aDb[iDb];
  87546. if( pDb->pBt==0 ){
  87547. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  87548. DbSetProperty(db, 1, DB_SchemaLoaded);
  87549. }
  87550. return SQLITE_OK;
  87551. }
  87552. /* If there is not already a read-only (or read-write) transaction opened
  87553. ** on the b-tree database, open one now. If a transaction is opened, it
  87554. ** will be closed before this function returns. */
  87555. sqlite3BtreeEnter(pDb->pBt);
  87556. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  87557. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  87558. if( rc!=SQLITE_OK ){
  87559. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  87560. goto initone_error_out;
  87561. }
  87562. openedTransaction = 1;
  87563. }
  87564. /* Get the database meta information.
  87565. **
  87566. ** Meta values are as follows:
  87567. ** meta[0] Schema cookie. Changes with each schema change.
  87568. ** meta[1] File format of schema layer.
  87569. ** meta[2] Size of the page cache.
  87570. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  87571. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  87572. ** meta[5] User version
  87573. ** meta[6] Incremental vacuum mode
  87574. ** meta[7] unused
  87575. ** meta[8] unused
  87576. ** meta[9] unused
  87577. **
  87578. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  87579. ** the possible values of meta[4].
  87580. */
  87581. for(i=0; i<ArraySize(meta); i++){
  87582. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  87583. }
  87584. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  87585. /* If opening a non-empty database, check the text encoding. For the
  87586. ** main database, set sqlite3.enc to the encoding of the main database.
  87587. ** For an attached db, it is an error if the encoding is not the same
  87588. ** as sqlite3.enc.
  87589. */
  87590. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  87591. if( iDb==0 ){
  87592. u8 encoding;
  87593. /* If opening the main database, set ENC(db). */
  87594. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  87595. if( encoding==0 ) encoding = SQLITE_UTF8;
  87596. ENC(db) = encoding;
  87597. }else{
  87598. /* If opening an attached database, the encoding much match ENC(db) */
  87599. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  87600. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  87601. " text encoding as main database");
  87602. rc = SQLITE_ERROR;
  87603. goto initone_error_out;
  87604. }
  87605. }
  87606. }else{
  87607. DbSetProperty(db, iDb, DB_Empty);
  87608. }
  87609. pDb->pSchema->enc = ENC(db);
  87610. if( pDb->pSchema->cache_size==0 ){
  87611. #ifndef SQLITE_OMIT_DEPRECATED
  87612. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  87613. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  87614. pDb->pSchema->cache_size = size;
  87615. #else
  87616. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  87617. #endif
  87618. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  87619. }
  87620. /*
  87621. ** file_format==1 Version 3.0.0.
  87622. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  87623. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  87624. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  87625. */
  87626. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  87627. if( pDb->pSchema->file_format==0 ){
  87628. pDb->pSchema->file_format = 1;
  87629. }
  87630. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  87631. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  87632. rc = SQLITE_ERROR;
  87633. goto initone_error_out;
  87634. }
  87635. /* Ticket #2804: When we open a database in the newer file format,
  87636. ** clear the legacy_file_format pragma flag so that a VACUUM will
  87637. ** not downgrade the database and thus invalidate any descending
  87638. ** indices that the user might have created.
  87639. */
  87640. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  87641. db->flags &= ~SQLITE_LegacyFileFmt;
  87642. }
  87643. /* Read the schema information out of the schema tables
  87644. */
  87645. assert( db->init.busy );
  87646. {
  87647. char *zSql;
  87648. zSql = sqlite3MPrintf(db,
  87649. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  87650. db->aDb[iDb].zName, zMasterName);
  87651. #ifndef SQLITE_OMIT_AUTHORIZATION
  87652. {
  87653. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  87654. xAuth = db->xAuth;
  87655. db->xAuth = 0;
  87656. #endif
  87657. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  87658. #ifndef SQLITE_OMIT_AUTHORIZATION
  87659. db->xAuth = xAuth;
  87660. }
  87661. #endif
  87662. if( rc==SQLITE_OK ) rc = initData.rc;
  87663. sqlite3DbFree(db, zSql);
  87664. #ifndef SQLITE_OMIT_ANALYZE
  87665. if( rc==SQLITE_OK ){
  87666. sqlite3AnalysisLoad(db, iDb);
  87667. }
  87668. #endif
  87669. }
  87670. if( db->mallocFailed ){
  87671. rc = SQLITE_NOMEM;
  87672. sqlite3ResetAllSchemasOfConnection(db);
  87673. }
  87674. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  87675. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  87676. ** the schema loaded, even if errors occurred. In this situation the
  87677. ** current sqlite3_prepare() operation will fail, but the following one
  87678. ** will attempt to compile the supplied statement against whatever subset
  87679. ** of the schema was loaded before the error occurred. The primary
  87680. ** purpose of this is to allow access to the sqlite_master table
  87681. ** even when its contents have been corrupted.
  87682. */
  87683. DbSetProperty(db, iDb, DB_SchemaLoaded);
  87684. rc = SQLITE_OK;
  87685. }
  87686. /* Jump here for an error that occurs after successfully allocating
  87687. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  87688. ** before that point, jump to error_out.
  87689. */
  87690. initone_error_out:
  87691. if( openedTransaction ){
  87692. sqlite3BtreeCommit(pDb->pBt);
  87693. }
  87694. sqlite3BtreeLeave(pDb->pBt);
  87695. error_out:
  87696. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  87697. db->mallocFailed = 1;
  87698. }
  87699. return rc;
  87700. }
  87701. /*
  87702. ** Initialize all database files - the main database file, the file
  87703. ** used to store temporary tables, and any additional database files
  87704. ** created using ATTACH statements. Return a success code. If an
  87705. ** error occurs, write an error message into *pzErrMsg.
  87706. **
  87707. ** After a database is initialized, the DB_SchemaLoaded bit is set
  87708. ** bit is set in the flags field of the Db structure. If the database
  87709. ** file was of zero-length, then the DB_Empty flag is also set.
  87710. */
  87711. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  87712. int i, rc;
  87713. int commit_internal = !(db->flags&SQLITE_InternChanges);
  87714. assert( sqlite3_mutex_held(db->mutex) );
  87715. rc = SQLITE_OK;
  87716. db->init.busy = 1;
  87717. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  87718. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  87719. rc = sqlite3InitOne(db, i, pzErrMsg);
  87720. if( rc ){
  87721. sqlite3ResetOneSchema(db, i);
  87722. }
  87723. }
  87724. /* Once all the other databases have been initialised, load the schema
  87725. ** for the TEMP database. This is loaded last, as the TEMP database
  87726. ** schema may contain references to objects in other databases.
  87727. */
  87728. #ifndef SQLITE_OMIT_TEMPDB
  87729. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  87730. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  87731. rc = sqlite3InitOne(db, 1, pzErrMsg);
  87732. if( rc ){
  87733. sqlite3ResetOneSchema(db, 1);
  87734. }
  87735. }
  87736. #endif
  87737. db->init.busy = 0;
  87738. if( rc==SQLITE_OK && commit_internal ){
  87739. sqlite3CommitInternalChanges(db);
  87740. }
  87741. return rc;
  87742. }
  87743. /*
  87744. ** This routine is a no-op if the database schema is already initialised.
  87745. ** Otherwise, the schema is loaded. An error code is returned.
  87746. */
  87747. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  87748. int rc = SQLITE_OK;
  87749. sqlite3 *db = pParse->db;
  87750. assert( sqlite3_mutex_held(db->mutex) );
  87751. if( !db->init.busy ){
  87752. rc = sqlite3Init(db, &pParse->zErrMsg);
  87753. }
  87754. if( rc!=SQLITE_OK ){
  87755. pParse->rc = rc;
  87756. pParse->nErr++;
  87757. }
  87758. return rc;
  87759. }
  87760. /*
  87761. ** Check schema cookies in all databases. If any cookie is out
  87762. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  87763. ** make no changes to pParse->rc.
  87764. */
  87765. static void schemaIsValid(Parse *pParse){
  87766. sqlite3 *db = pParse->db;
  87767. int iDb;
  87768. int rc;
  87769. int cookie;
  87770. assert( pParse->checkSchema );
  87771. assert( sqlite3_mutex_held(db->mutex) );
  87772. for(iDb=0; iDb<db->nDb; iDb++){
  87773. int openedTransaction = 0; /* True if a transaction is opened */
  87774. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  87775. if( pBt==0 ) continue;
  87776. /* If there is not already a read-only (or read-write) transaction opened
  87777. ** on the b-tree database, open one now. If a transaction is opened, it
  87778. ** will be closed immediately after reading the meta-value. */
  87779. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  87780. rc = sqlite3BtreeBeginTrans(pBt, 0);
  87781. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  87782. db->mallocFailed = 1;
  87783. }
  87784. if( rc!=SQLITE_OK ) return;
  87785. openedTransaction = 1;
  87786. }
  87787. /* Read the schema cookie from the database. If it does not match the
  87788. ** value stored as part of the in-memory schema representation,
  87789. ** set Parse.rc to SQLITE_SCHEMA. */
  87790. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  87791. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87792. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  87793. sqlite3ResetOneSchema(db, iDb);
  87794. pParse->rc = SQLITE_SCHEMA;
  87795. }
  87796. /* Close the transaction, if one was opened. */
  87797. if( openedTransaction ){
  87798. sqlite3BtreeCommit(pBt);
  87799. }
  87800. }
  87801. }
  87802. /*
  87803. ** Convert a schema pointer into the iDb index that indicates
  87804. ** which database file in db->aDb[] the schema refers to.
  87805. **
  87806. ** If the same database is attached more than once, the first
  87807. ** attached database is returned.
  87808. */
  87809. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  87810. int i = -1000000;
  87811. /* If pSchema is NULL, then return -1000000. This happens when code in
  87812. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  87813. ** created by a sub-select). In this case the return value of this
  87814. ** function should never be used.
  87815. **
  87816. ** We return -1000000 instead of the more usual -1 simply because using
  87817. ** -1000000 as the incorrect index into db->aDb[] is much
  87818. ** more likely to cause a segfault than -1 (of course there are assert()
  87819. ** statements too, but it never hurts to play the odds).
  87820. */
  87821. assert( sqlite3_mutex_held(db->mutex) );
  87822. if( pSchema ){
  87823. for(i=0; ALWAYS(i<db->nDb); i++){
  87824. if( db->aDb[i].pSchema==pSchema ){
  87825. break;
  87826. }
  87827. }
  87828. assert( i>=0 && i<db->nDb );
  87829. }
  87830. return i;
  87831. }
  87832. /*
  87833. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  87834. */
  87835. static int sqlite3Prepare(
  87836. sqlite3 *db, /* Database handle. */
  87837. const char *zSql, /* UTF-8 encoded SQL statement. */
  87838. int nBytes, /* Length of zSql in bytes. */
  87839. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  87840. Vdbe *pReprepare, /* VM being reprepared */
  87841. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  87842. const char **pzTail /* OUT: End of parsed string */
  87843. ){
  87844. Parse *pParse; /* Parsing context */
  87845. char *zErrMsg = 0; /* Error message */
  87846. int rc = SQLITE_OK; /* Result code */
  87847. int i; /* Loop counter */
  87848. /* Allocate the parsing context */
  87849. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  87850. if( pParse==0 ){
  87851. rc = SQLITE_NOMEM;
  87852. goto end_prepare;
  87853. }
  87854. pParse->pReprepare = pReprepare;
  87855. assert( ppStmt && *ppStmt==0 );
  87856. assert( !db->mallocFailed );
  87857. assert( sqlite3_mutex_held(db->mutex) );
  87858. /* Check to verify that it is possible to get a read lock on all
  87859. ** database schemas. The inability to get a read lock indicates that
  87860. ** some other database connection is holding a write-lock, which in
  87861. ** turn means that the other connection has made uncommitted changes
  87862. ** to the schema.
  87863. **
  87864. ** Were we to proceed and prepare the statement against the uncommitted
  87865. ** schema changes and if those schema changes are subsequently rolled
  87866. ** back and different changes are made in their place, then when this
  87867. ** prepared statement goes to run the schema cookie would fail to detect
  87868. ** the schema change. Disaster would follow.
  87869. **
  87870. ** This thread is currently holding mutexes on all Btrees (because
  87871. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  87872. ** is not possible for another thread to start a new schema change
  87873. ** while this routine is running. Hence, we do not need to hold
  87874. ** locks on the schema, we just need to make sure nobody else is
  87875. ** holding them.
  87876. **
  87877. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  87878. ** but it does *not* override schema lock detection, so this all still
  87879. ** works even if READ_UNCOMMITTED is set.
  87880. */
  87881. for(i=0; i<db->nDb; i++) {
  87882. Btree *pBt = db->aDb[i].pBt;
  87883. if( pBt ){
  87884. assert( sqlite3BtreeHoldsMutex(pBt) );
  87885. rc = sqlite3BtreeSchemaLocked(pBt);
  87886. if( rc ){
  87887. const char *zDb = db->aDb[i].zName;
  87888. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  87889. testcase( db->flags & SQLITE_ReadUncommitted );
  87890. goto end_prepare;
  87891. }
  87892. }
  87893. }
  87894. sqlite3VtabUnlockList(db);
  87895. pParse->db = db;
  87896. pParse->nQueryLoop = (double)1;
  87897. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  87898. char *zSqlCopy;
  87899. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  87900. testcase( nBytes==mxLen );
  87901. testcase( nBytes==mxLen+1 );
  87902. if( nBytes>mxLen ){
  87903. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  87904. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  87905. goto end_prepare;
  87906. }
  87907. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  87908. if( zSqlCopy ){
  87909. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  87910. sqlite3DbFree(db, zSqlCopy);
  87911. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  87912. }else{
  87913. pParse->zTail = &zSql[nBytes];
  87914. }
  87915. }else{
  87916. sqlite3RunParser(pParse, zSql, &zErrMsg);
  87917. }
  87918. assert( 1==(int)pParse->nQueryLoop );
  87919. if( db->mallocFailed ){
  87920. pParse->rc = SQLITE_NOMEM;
  87921. }
  87922. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  87923. if( pParse->checkSchema ){
  87924. schemaIsValid(pParse);
  87925. }
  87926. if( db->mallocFailed ){
  87927. pParse->rc = SQLITE_NOMEM;
  87928. }
  87929. if( pzTail ){
  87930. *pzTail = pParse->zTail;
  87931. }
  87932. rc = pParse->rc;
  87933. #ifndef SQLITE_OMIT_EXPLAIN
  87934. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  87935. static const char * const azColName[] = {
  87936. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  87937. "selectid", "order", "from", "detail"
  87938. };
  87939. int iFirst, mx;
  87940. if( pParse->explain==2 ){
  87941. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  87942. iFirst = 8;
  87943. mx = 12;
  87944. }else{
  87945. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  87946. iFirst = 0;
  87947. mx = 8;
  87948. }
  87949. for(i=iFirst; i<mx; i++){
  87950. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  87951. azColName[i], SQLITE_STATIC);
  87952. }
  87953. }
  87954. #endif
  87955. assert( db->init.busy==0 || saveSqlFlag==0 );
  87956. if( db->init.busy==0 ){
  87957. Vdbe *pVdbe = pParse->pVdbe;
  87958. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  87959. }
  87960. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  87961. sqlite3VdbeFinalize(pParse->pVdbe);
  87962. assert(!(*ppStmt));
  87963. }else{
  87964. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  87965. }
  87966. if( zErrMsg ){
  87967. sqlite3Error(db, rc, "%s", zErrMsg);
  87968. sqlite3DbFree(db, zErrMsg);
  87969. }else{
  87970. sqlite3Error(db, rc, 0);
  87971. }
  87972. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  87973. while( pParse->pTriggerPrg ){
  87974. TriggerPrg *pT = pParse->pTriggerPrg;
  87975. pParse->pTriggerPrg = pT->pNext;
  87976. sqlite3DbFree(db, pT);
  87977. }
  87978. end_prepare:
  87979. sqlite3StackFree(db, pParse);
  87980. rc = sqlite3ApiExit(db, rc);
  87981. assert( (rc&db->errMask)==rc );
  87982. return rc;
  87983. }
  87984. static int sqlite3LockAndPrepare(
  87985. sqlite3 *db, /* Database handle. */
  87986. const char *zSql, /* UTF-8 encoded SQL statement. */
  87987. int nBytes, /* Length of zSql in bytes. */
  87988. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  87989. Vdbe *pOld, /* VM being reprepared */
  87990. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  87991. const char **pzTail /* OUT: End of parsed string */
  87992. ){
  87993. int rc;
  87994. assert( ppStmt!=0 );
  87995. *ppStmt = 0;
  87996. if( !sqlite3SafetyCheckOk(db) ){
  87997. return SQLITE_MISUSE_BKPT;
  87998. }
  87999. sqlite3_mutex_enter(db->mutex);
  88000. sqlite3BtreeEnterAll(db);
  88001. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  88002. if( rc==SQLITE_SCHEMA ){
  88003. sqlite3_finalize(*ppStmt);
  88004. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  88005. }
  88006. sqlite3BtreeLeaveAll(db);
  88007. sqlite3_mutex_leave(db->mutex);
  88008. assert( rc==SQLITE_OK || *ppStmt==0 );
  88009. return rc;
  88010. }
  88011. /*
  88012. ** Rerun the compilation of a statement after a schema change.
  88013. **
  88014. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  88015. ** if the statement cannot be recompiled because another connection has
  88016. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  88017. ** occurs, return SQLITE_SCHEMA.
  88018. */
  88019. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  88020. int rc;
  88021. sqlite3_stmt *pNew;
  88022. const char *zSql;
  88023. sqlite3 *db;
  88024. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  88025. zSql = sqlite3_sql((sqlite3_stmt *)p);
  88026. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  88027. db = sqlite3VdbeDb(p);
  88028. assert( sqlite3_mutex_held(db->mutex) );
  88029. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  88030. if( rc ){
  88031. if( rc==SQLITE_NOMEM ){
  88032. db->mallocFailed = 1;
  88033. }
  88034. assert( pNew==0 );
  88035. return rc;
  88036. }else{
  88037. assert( pNew!=0 );
  88038. }
  88039. sqlite3VdbeSwap((Vdbe*)pNew, p);
  88040. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  88041. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  88042. sqlite3VdbeFinalize((Vdbe*)pNew);
  88043. return SQLITE_OK;
  88044. }
  88045. /*
  88046. ** Two versions of the official API. Legacy and new use. In the legacy
  88047. ** version, the original SQL text is not saved in the prepared statement
  88048. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  88049. ** sqlite3_step(). In the new version, the original SQL text is retained
  88050. ** and the statement is automatically recompiled if an schema change
  88051. ** occurs.
  88052. */
  88053. SQLITE_API int sqlite3_prepare(
  88054. sqlite3 *db, /* Database handle. */
  88055. const char *zSql, /* UTF-8 encoded SQL statement. */
  88056. int nBytes, /* Length of zSql in bytes. */
  88057. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  88058. const char **pzTail /* OUT: End of parsed string */
  88059. ){
  88060. int rc;
  88061. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  88062. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  88063. return rc;
  88064. }
  88065. SQLITE_API int sqlite3_prepare_v2(
  88066. sqlite3 *db, /* Database handle. */
  88067. const char *zSql, /* UTF-8 encoded SQL statement. */
  88068. int nBytes, /* Length of zSql in bytes. */
  88069. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  88070. const char **pzTail /* OUT: End of parsed string */
  88071. ){
  88072. int rc;
  88073. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  88074. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  88075. return rc;
  88076. }
  88077. #ifndef SQLITE_OMIT_UTF16
  88078. /*
  88079. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  88080. */
  88081. static int sqlite3Prepare16(
  88082. sqlite3 *db, /* Database handle. */
  88083. const void *zSql, /* UTF-16 encoded SQL statement. */
  88084. int nBytes, /* Length of zSql in bytes. */
  88085. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  88086. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  88087. const void **pzTail /* OUT: End of parsed string */
  88088. ){
  88089. /* This function currently works by first transforming the UTF-16
  88090. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  88091. ** tricky bit is figuring out the pointer to return in *pzTail.
  88092. */
  88093. char *zSql8;
  88094. const char *zTail8 = 0;
  88095. int rc = SQLITE_OK;
  88096. assert( ppStmt );
  88097. *ppStmt = 0;
  88098. if( !sqlite3SafetyCheckOk(db) ){
  88099. return SQLITE_MISUSE_BKPT;
  88100. }
  88101. sqlite3_mutex_enter(db->mutex);
  88102. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  88103. if( zSql8 ){
  88104. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  88105. }
  88106. if( zTail8 && pzTail ){
  88107. /* If sqlite3_prepare returns a tail pointer, we calculate the
  88108. ** equivalent pointer into the UTF-16 string by counting the unicode
  88109. ** characters between zSql8 and zTail8, and then returning a pointer
  88110. ** the same number of characters into the UTF-16 string.
  88111. */
  88112. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  88113. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  88114. }
  88115. sqlite3DbFree(db, zSql8);
  88116. rc = sqlite3ApiExit(db, rc);
  88117. sqlite3_mutex_leave(db->mutex);
  88118. return rc;
  88119. }
  88120. /*
  88121. ** Two versions of the official API. Legacy and new use. In the legacy
  88122. ** version, the original SQL text is not saved in the prepared statement
  88123. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  88124. ** sqlite3_step(). In the new version, the original SQL text is retained
  88125. ** and the statement is automatically recompiled if an schema change
  88126. ** occurs.
  88127. */
  88128. SQLITE_API int sqlite3_prepare16(
  88129. sqlite3 *db, /* Database handle. */
  88130. const void *zSql, /* UTF-16 encoded SQL statement. */
  88131. int nBytes, /* Length of zSql in bytes. */
  88132. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  88133. const void **pzTail /* OUT: End of parsed string */
  88134. ){
  88135. int rc;
  88136. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  88137. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  88138. return rc;
  88139. }
  88140. SQLITE_API int sqlite3_prepare16_v2(
  88141. sqlite3 *db, /* Database handle. */
  88142. const void *zSql, /* UTF-16 encoded SQL statement. */
  88143. int nBytes, /* Length of zSql in bytes. */
  88144. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  88145. const void **pzTail /* OUT: End of parsed string */
  88146. ){
  88147. int rc;
  88148. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  88149. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  88150. return rc;
  88151. }
  88152. #endif /* SQLITE_OMIT_UTF16 */
  88153. /************** End of prepare.c *********************************************/
  88154. /************** Begin file select.c ******************************************/
  88155. /*
  88156. ** 2001 September 15
  88157. **
  88158. ** The author disclaims copyright to this source code. In place of
  88159. ** a legal notice, here is a blessing:
  88160. **
  88161. ** May you do good and not evil.
  88162. ** May you find forgiveness for yourself and forgive others.
  88163. ** May you share freely, never taking more than you give.
  88164. **
  88165. *************************************************************************
  88166. ** This file contains C code routines that are called by the parser
  88167. ** to handle SELECT statements in SQLite.
  88168. */
  88169. /*
  88170. ** Delete all the content of a Select structure but do not deallocate
  88171. ** the select structure itself.
  88172. */
  88173. static void clearSelect(sqlite3 *db, Select *p){
  88174. sqlite3ExprListDelete(db, p->pEList);
  88175. sqlite3SrcListDelete(db, p->pSrc);
  88176. sqlite3ExprDelete(db, p->pWhere);
  88177. sqlite3ExprListDelete(db, p->pGroupBy);
  88178. sqlite3ExprDelete(db, p->pHaving);
  88179. sqlite3ExprListDelete(db, p->pOrderBy);
  88180. sqlite3SelectDelete(db, p->pPrior);
  88181. sqlite3ExprDelete(db, p->pLimit);
  88182. sqlite3ExprDelete(db, p->pOffset);
  88183. }
  88184. /*
  88185. ** Initialize a SelectDest structure.
  88186. */
  88187. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  88188. pDest->eDest = (u8)eDest;
  88189. pDest->iSDParm = iParm;
  88190. pDest->affSdst = 0;
  88191. pDest->iSdst = 0;
  88192. pDest->nSdst = 0;
  88193. }
  88194. /*
  88195. ** Allocate a new Select structure and return a pointer to that
  88196. ** structure.
  88197. */
  88198. SQLITE_PRIVATE Select *sqlite3SelectNew(
  88199. Parse *pParse, /* Parsing context */
  88200. ExprList *pEList, /* which columns to include in the result */
  88201. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  88202. Expr *pWhere, /* the WHERE clause */
  88203. ExprList *pGroupBy, /* the GROUP BY clause */
  88204. Expr *pHaving, /* the HAVING clause */
  88205. ExprList *pOrderBy, /* the ORDER BY clause */
  88206. int isDistinct, /* true if the DISTINCT keyword is present */
  88207. Expr *pLimit, /* LIMIT value. NULL means not used */
  88208. Expr *pOffset /* OFFSET value. NULL means no offset */
  88209. ){
  88210. Select *pNew;
  88211. Select standin;
  88212. sqlite3 *db = pParse->db;
  88213. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  88214. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  88215. if( pNew==0 ){
  88216. assert( db->mallocFailed );
  88217. pNew = &standin;
  88218. memset(pNew, 0, sizeof(*pNew));
  88219. }
  88220. if( pEList==0 ){
  88221. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  88222. }
  88223. pNew->pEList = pEList;
  88224. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  88225. pNew->pSrc = pSrc;
  88226. pNew->pWhere = pWhere;
  88227. pNew->pGroupBy = pGroupBy;
  88228. pNew->pHaving = pHaving;
  88229. pNew->pOrderBy = pOrderBy;
  88230. pNew->selFlags = isDistinct ? SF_Distinct : 0;
  88231. pNew->op = TK_SELECT;
  88232. pNew->pLimit = pLimit;
  88233. pNew->pOffset = pOffset;
  88234. assert( pOffset==0 || pLimit!=0 );
  88235. pNew->addrOpenEphm[0] = -1;
  88236. pNew->addrOpenEphm[1] = -1;
  88237. pNew->addrOpenEphm[2] = -1;
  88238. if( db->mallocFailed ) {
  88239. clearSelect(db, pNew);
  88240. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  88241. pNew = 0;
  88242. }else{
  88243. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  88244. }
  88245. assert( pNew!=&standin );
  88246. return pNew;
  88247. }
  88248. /*
  88249. ** Delete the given Select structure and all of its substructures.
  88250. */
  88251. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  88252. if( p ){
  88253. clearSelect(db, p);
  88254. sqlite3DbFree(db, p);
  88255. }
  88256. }
  88257. /*
  88258. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  88259. ** type of join. Return an integer constant that expresses that type
  88260. ** in terms of the following bit values:
  88261. **
  88262. ** JT_INNER
  88263. ** JT_CROSS
  88264. ** JT_OUTER
  88265. ** JT_NATURAL
  88266. ** JT_LEFT
  88267. ** JT_RIGHT
  88268. **
  88269. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  88270. **
  88271. ** If an illegal or unsupported join type is seen, then still return
  88272. ** a join type, but put an error in the pParse structure.
  88273. */
  88274. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  88275. int jointype = 0;
  88276. Token *apAll[3];
  88277. Token *p;
  88278. /* 0123456789 123456789 123456789 123 */
  88279. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  88280. static const struct {
  88281. u8 i; /* Beginning of keyword text in zKeyText[] */
  88282. u8 nChar; /* Length of the keyword in characters */
  88283. u8 code; /* Join type mask */
  88284. } aKeyword[] = {
  88285. /* natural */ { 0, 7, JT_NATURAL },
  88286. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  88287. /* outer */ { 10, 5, JT_OUTER },
  88288. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  88289. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  88290. /* inner */ { 23, 5, JT_INNER },
  88291. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  88292. };
  88293. int i, j;
  88294. apAll[0] = pA;
  88295. apAll[1] = pB;
  88296. apAll[2] = pC;
  88297. for(i=0; i<3 && apAll[i]; i++){
  88298. p = apAll[i];
  88299. for(j=0; j<ArraySize(aKeyword); j++){
  88300. if( p->n==aKeyword[j].nChar
  88301. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  88302. jointype |= aKeyword[j].code;
  88303. break;
  88304. }
  88305. }
  88306. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  88307. if( j>=ArraySize(aKeyword) ){
  88308. jointype |= JT_ERROR;
  88309. break;
  88310. }
  88311. }
  88312. if(
  88313. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  88314. (jointype & JT_ERROR)!=0
  88315. ){
  88316. const char *zSp = " ";
  88317. assert( pB!=0 );
  88318. if( pC==0 ){ zSp++; }
  88319. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  88320. "%T %T%s%T", pA, pB, zSp, pC);
  88321. jointype = JT_INNER;
  88322. }else if( (jointype & JT_OUTER)!=0
  88323. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  88324. sqlite3ErrorMsg(pParse,
  88325. "RIGHT and FULL OUTER JOINs are not currently supported");
  88326. jointype = JT_INNER;
  88327. }
  88328. return jointype;
  88329. }
  88330. /*
  88331. ** Return the index of a column in a table. Return -1 if the column
  88332. ** is not contained in the table.
  88333. */
  88334. static int columnIndex(Table *pTab, const char *zCol){
  88335. int i;
  88336. for(i=0; i<pTab->nCol; i++){
  88337. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  88338. }
  88339. return -1;
  88340. }
  88341. /*
  88342. ** Search the first N tables in pSrc, from left to right, looking for a
  88343. ** table that has a column named zCol.
  88344. **
  88345. ** When found, set *piTab and *piCol to the table index and column index
  88346. ** of the matching column and return TRUE.
  88347. **
  88348. ** If not found, return FALSE.
  88349. */
  88350. static int tableAndColumnIndex(
  88351. SrcList *pSrc, /* Array of tables to search */
  88352. int N, /* Number of tables in pSrc->a[] to search */
  88353. const char *zCol, /* Name of the column we are looking for */
  88354. int *piTab, /* Write index of pSrc->a[] here */
  88355. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  88356. ){
  88357. int i; /* For looping over tables in pSrc */
  88358. int iCol; /* Index of column matching zCol */
  88359. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  88360. for(i=0; i<N; i++){
  88361. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  88362. if( iCol>=0 ){
  88363. if( piTab ){
  88364. *piTab = i;
  88365. *piCol = iCol;
  88366. }
  88367. return 1;
  88368. }
  88369. }
  88370. return 0;
  88371. }
  88372. /*
  88373. ** This function is used to add terms implied by JOIN syntax to the
  88374. ** WHERE clause expression of a SELECT statement. The new term, which
  88375. ** is ANDed with the existing WHERE clause, is of the form:
  88376. **
  88377. ** (tab1.col1 = tab2.col2)
  88378. **
  88379. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  88380. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  88381. ** column iColRight of tab2.
  88382. */
  88383. static void addWhereTerm(
  88384. Parse *pParse, /* Parsing context */
  88385. SrcList *pSrc, /* List of tables in FROM clause */
  88386. int iLeft, /* Index of first table to join in pSrc */
  88387. int iColLeft, /* Index of column in first table */
  88388. int iRight, /* Index of second table in pSrc */
  88389. int iColRight, /* Index of column in second table */
  88390. int isOuterJoin, /* True if this is an OUTER join */
  88391. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  88392. ){
  88393. sqlite3 *db = pParse->db;
  88394. Expr *pE1;
  88395. Expr *pE2;
  88396. Expr *pEq;
  88397. assert( iLeft<iRight );
  88398. assert( pSrc->nSrc>iRight );
  88399. assert( pSrc->a[iLeft].pTab );
  88400. assert( pSrc->a[iRight].pTab );
  88401. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  88402. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  88403. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  88404. if( pEq && isOuterJoin ){
  88405. ExprSetProperty(pEq, EP_FromJoin);
  88406. assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
  88407. ExprSetIrreducible(pEq);
  88408. pEq->iRightJoinTable = (i16)pE2->iTable;
  88409. }
  88410. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  88411. }
  88412. /*
  88413. ** Set the EP_FromJoin property on all terms of the given expression.
  88414. ** And set the Expr.iRightJoinTable to iTable for every term in the
  88415. ** expression.
  88416. **
  88417. ** The EP_FromJoin property is used on terms of an expression to tell
  88418. ** the LEFT OUTER JOIN processing logic that this term is part of the
  88419. ** join restriction specified in the ON or USING clause and not a part
  88420. ** of the more general WHERE clause. These terms are moved over to the
  88421. ** WHERE clause during join processing but we need to remember that they
  88422. ** originated in the ON or USING clause.
  88423. **
  88424. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  88425. ** expression depends on table iRightJoinTable even if that table is not
  88426. ** explicitly mentioned in the expression. That information is needed
  88427. ** for cases like this:
  88428. **
  88429. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  88430. **
  88431. ** The where clause needs to defer the handling of the t1.x=5
  88432. ** term until after the t2 loop of the join. In that way, a
  88433. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  88434. ** defer the handling of t1.x=5, it will be processed immediately
  88435. ** after the t1 loop and rows with t1.x!=5 will never appear in
  88436. ** the output, which is incorrect.
  88437. */
  88438. static void setJoinExpr(Expr *p, int iTable){
  88439. while( p ){
  88440. ExprSetProperty(p, EP_FromJoin);
  88441. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  88442. ExprSetIrreducible(p);
  88443. p->iRightJoinTable = (i16)iTable;
  88444. setJoinExpr(p->pLeft, iTable);
  88445. p = p->pRight;
  88446. }
  88447. }
  88448. /*
  88449. ** This routine processes the join information for a SELECT statement.
  88450. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  88451. ** NATURAL joins also create extra WHERE clause terms.
  88452. **
  88453. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  88454. ** The left most table is the first entry in Select.pSrc. The right-most
  88455. ** table is the last entry. The join operator is held in the entry to
  88456. ** the left. Thus entry 0 contains the join operator for the join between
  88457. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  88458. ** also attached to the left entry.
  88459. **
  88460. ** This routine returns the number of errors encountered.
  88461. */
  88462. static int sqliteProcessJoin(Parse *pParse, Select *p){
  88463. SrcList *pSrc; /* All tables in the FROM clause */
  88464. int i, j; /* Loop counters */
  88465. struct SrcList_item *pLeft; /* Left table being joined */
  88466. struct SrcList_item *pRight; /* Right table being joined */
  88467. pSrc = p->pSrc;
  88468. pLeft = &pSrc->a[0];
  88469. pRight = &pLeft[1];
  88470. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  88471. Table *pLeftTab = pLeft->pTab;
  88472. Table *pRightTab = pRight->pTab;
  88473. int isOuter;
  88474. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  88475. isOuter = (pRight->jointype & JT_OUTER)!=0;
  88476. /* When the NATURAL keyword is present, add WHERE clause terms for
  88477. ** every column that the two tables have in common.
  88478. */
  88479. if( pRight->jointype & JT_NATURAL ){
  88480. if( pRight->pOn || pRight->pUsing ){
  88481. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  88482. "an ON or USING clause", 0);
  88483. return 1;
  88484. }
  88485. for(j=0; j<pRightTab->nCol; j++){
  88486. char *zName; /* Name of column in the right table */
  88487. int iLeft; /* Matching left table */
  88488. int iLeftCol; /* Matching column in the left table */
  88489. zName = pRightTab->aCol[j].zName;
  88490. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  88491. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  88492. isOuter, &p->pWhere);
  88493. }
  88494. }
  88495. }
  88496. /* Disallow both ON and USING clauses in the same join
  88497. */
  88498. if( pRight->pOn && pRight->pUsing ){
  88499. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  88500. "clauses in the same join");
  88501. return 1;
  88502. }
  88503. /* Add the ON clause to the end of the WHERE clause, connected by
  88504. ** an AND operator.
  88505. */
  88506. if( pRight->pOn ){
  88507. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  88508. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  88509. pRight->pOn = 0;
  88510. }
  88511. /* Create extra terms on the WHERE clause for each column named
  88512. ** in the USING clause. Example: If the two tables to be joined are
  88513. ** A and B and the USING clause names X, Y, and Z, then add this
  88514. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  88515. ** Report an error if any column mentioned in the USING clause is
  88516. ** not contained in both tables to be joined.
  88517. */
  88518. if( pRight->pUsing ){
  88519. IdList *pList = pRight->pUsing;
  88520. for(j=0; j<pList->nId; j++){
  88521. char *zName; /* Name of the term in the USING clause */
  88522. int iLeft; /* Table on the left with matching column name */
  88523. int iLeftCol; /* Column number of matching column on the left */
  88524. int iRightCol; /* Column number of matching column on the right */
  88525. zName = pList->a[j].zName;
  88526. iRightCol = columnIndex(pRightTab, zName);
  88527. if( iRightCol<0
  88528. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  88529. ){
  88530. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  88531. "not present in both tables", zName);
  88532. return 1;
  88533. }
  88534. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  88535. isOuter, &p->pWhere);
  88536. }
  88537. }
  88538. }
  88539. return 0;
  88540. }
  88541. /*
  88542. ** Insert code into "v" that will push the record on the top of the
  88543. ** stack into the sorter.
  88544. */
  88545. static void pushOntoSorter(
  88546. Parse *pParse, /* Parser context */
  88547. ExprList *pOrderBy, /* The ORDER BY clause */
  88548. Select *pSelect, /* The whole SELECT statement */
  88549. int regData /* Register holding data to be sorted */
  88550. ){
  88551. Vdbe *v = pParse->pVdbe;
  88552. int nExpr = pOrderBy->nExpr;
  88553. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  88554. int regRecord = sqlite3GetTempReg(pParse);
  88555. int op;
  88556. sqlite3ExprCacheClear(pParse);
  88557. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  88558. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  88559. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  88560. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  88561. if( pSelect->selFlags & SF_UseSorter ){
  88562. op = OP_SorterInsert;
  88563. }else{
  88564. op = OP_IdxInsert;
  88565. }
  88566. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  88567. sqlite3ReleaseTempReg(pParse, regRecord);
  88568. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  88569. if( pSelect->iLimit ){
  88570. int addr1, addr2;
  88571. int iLimit;
  88572. if( pSelect->iOffset ){
  88573. iLimit = pSelect->iOffset+1;
  88574. }else{
  88575. iLimit = pSelect->iLimit;
  88576. }
  88577. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  88578. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  88579. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  88580. sqlite3VdbeJumpHere(v, addr1);
  88581. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  88582. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  88583. sqlite3VdbeJumpHere(v, addr2);
  88584. }
  88585. }
  88586. /*
  88587. ** Add code to implement the OFFSET
  88588. */
  88589. static void codeOffset(
  88590. Vdbe *v, /* Generate code into this VM */
  88591. Select *p, /* The SELECT statement being coded */
  88592. int iContinue /* Jump here to skip the current record */
  88593. ){
  88594. if( p->iOffset && iContinue!=0 ){
  88595. int addr;
  88596. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  88597. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  88598. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  88599. VdbeComment((v, "skip OFFSET records"));
  88600. sqlite3VdbeJumpHere(v, addr);
  88601. }
  88602. }
  88603. /*
  88604. ** Add code that will check to make sure the N registers starting at iMem
  88605. ** form a distinct entry. iTab is a sorting index that holds previously
  88606. ** seen combinations of the N values. A new entry is made in iTab
  88607. ** if the current N values are new.
  88608. **
  88609. ** A jump to addrRepeat is made and the N+1 values are popped from the
  88610. ** stack if the top N elements are not distinct.
  88611. */
  88612. static void codeDistinct(
  88613. Parse *pParse, /* Parsing and code generating context */
  88614. int iTab, /* A sorting index used to test for distinctness */
  88615. int addrRepeat, /* Jump to here if not distinct */
  88616. int N, /* Number of elements */
  88617. int iMem /* First element */
  88618. ){
  88619. Vdbe *v;
  88620. int r1;
  88621. v = pParse->pVdbe;
  88622. r1 = sqlite3GetTempReg(pParse);
  88623. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  88624. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  88625. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  88626. sqlite3ReleaseTempReg(pParse, r1);
  88627. }
  88628. #ifndef SQLITE_OMIT_SUBQUERY
  88629. /*
  88630. ** Generate an error message when a SELECT is used within a subexpression
  88631. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  88632. ** column. We do this in a subroutine because the error used to occur
  88633. ** in multiple places. (The error only occurs in one place now, but we
  88634. ** retain the subroutine to minimize code disruption.)
  88635. */
  88636. static int checkForMultiColumnSelectError(
  88637. Parse *pParse, /* Parse context. */
  88638. SelectDest *pDest, /* Destination of SELECT results */
  88639. int nExpr /* Number of result columns returned by SELECT */
  88640. ){
  88641. int eDest = pDest->eDest;
  88642. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  88643. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  88644. "a SELECT that is part of an expression");
  88645. return 1;
  88646. }else{
  88647. return 0;
  88648. }
  88649. }
  88650. #endif
  88651. /*
  88652. ** An instance of the following object is used to record information about
  88653. ** how to process the DISTINCT keyword, to simplify passing that information
  88654. ** into the selectInnerLoop() routine.
  88655. */
  88656. typedef struct DistinctCtx DistinctCtx;
  88657. struct DistinctCtx {
  88658. u8 isTnct; /* True if the DISTINCT keyword is present */
  88659. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  88660. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  88661. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  88662. };
  88663. /*
  88664. ** This routine generates the code for the inside of the inner loop
  88665. ** of a SELECT.
  88666. **
  88667. ** If srcTab and nColumn are both zero, then the pEList expressions
  88668. ** are evaluated in order to get the data for this row. If nColumn>0
  88669. ** then data is pulled from srcTab and pEList is used only to get the
  88670. ** datatypes for each column.
  88671. */
  88672. static void selectInnerLoop(
  88673. Parse *pParse, /* The parser context */
  88674. Select *p, /* The complete select statement being coded */
  88675. ExprList *pEList, /* List of values being extracted */
  88676. int srcTab, /* Pull data from this table */
  88677. int nColumn, /* Number of columns in the source table */
  88678. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  88679. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  88680. SelectDest *pDest, /* How to dispose of the results */
  88681. int iContinue, /* Jump here to continue with next row */
  88682. int iBreak /* Jump here to break out of the inner loop */
  88683. ){
  88684. Vdbe *v = pParse->pVdbe;
  88685. int i;
  88686. int hasDistinct; /* True if the DISTINCT keyword is present */
  88687. int regResult; /* Start of memory holding result set */
  88688. int eDest = pDest->eDest; /* How to dispose of results */
  88689. int iParm = pDest->iSDParm; /* First argument to disposal method */
  88690. int nResultCol; /* Number of result columns */
  88691. assert( v );
  88692. if( NEVER(v==0) ) return;
  88693. assert( pEList!=0 );
  88694. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  88695. if( pOrderBy==0 && !hasDistinct ){
  88696. codeOffset(v, p, iContinue);
  88697. }
  88698. /* Pull the requested columns.
  88699. */
  88700. if( nColumn>0 ){
  88701. nResultCol = nColumn;
  88702. }else{
  88703. nResultCol = pEList->nExpr;
  88704. }
  88705. if( pDest->iSdst==0 ){
  88706. pDest->iSdst = pParse->nMem+1;
  88707. pDest->nSdst = nResultCol;
  88708. pParse->nMem += nResultCol;
  88709. }else{
  88710. assert( pDest->nSdst==nResultCol );
  88711. }
  88712. regResult = pDest->iSdst;
  88713. if( nColumn>0 ){
  88714. for(i=0; i<nColumn; i++){
  88715. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  88716. }
  88717. }else if( eDest!=SRT_Exists ){
  88718. /* If the destination is an EXISTS(...) expression, the actual
  88719. ** values returned by the SELECT are not required.
  88720. */
  88721. sqlite3ExprCacheClear(pParse);
  88722. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  88723. }
  88724. nColumn = nResultCol;
  88725. /* If the DISTINCT keyword was present on the SELECT statement
  88726. ** and this row has been seen before, then do not make this row
  88727. ** part of the result.
  88728. */
  88729. if( hasDistinct ){
  88730. assert( pEList!=0 );
  88731. assert( pEList->nExpr==nColumn );
  88732. switch( pDistinct->eTnctType ){
  88733. case WHERE_DISTINCT_ORDERED: {
  88734. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  88735. int iJump; /* Jump destination */
  88736. int regPrev; /* Previous row content */
  88737. /* Allocate space for the previous row */
  88738. regPrev = pParse->nMem+1;
  88739. pParse->nMem += nColumn;
  88740. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  88741. ** sets the MEM_Cleared bit on the first register of the
  88742. ** previous value. This will cause the OP_Ne below to always
  88743. ** fail on the first iteration of the loop even if the first
  88744. ** row is all NULLs.
  88745. */
  88746. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  88747. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  88748. pOp->opcode = OP_Null;
  88749. pOp->p1 = 1;
  88750. pOp->p2 = regPrev;
  88751. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  88752. for(i=0; i<nColumn; i++){
  88753. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  88754. if( i<nColumn-1 ){
  88755. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  88756. }else{
  88757. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  88758. }
  88759. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  88760. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  88761. }
  88762. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  88763. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  88764. break;
  88765. }
  88766. case WHERE_DISTINCT_UNIQUE: {
  88767. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  88768. break;
  88769. }
  88770. default: {
  88771. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  88772. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  88773. break;
  88774. }
  88775. }
  88776. if( pOrderBy==0 ){
  88777. codeOffset(v, p, iContinue);
  88778. }
  88779. }
  88780. switch( eDest ){
  88781. /* In this mode, write each query result to the key of the temporary
  88782. ** table iParm.
  88783. */
  88784. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  88785. case SRT_Union: {
  88786. int r1;
  88787. r1 = sqlite3GetTempReg(pParse);
  88788. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  88789. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  88790. sqlite3ReleaseTempReg(pParse, r1);
  88791. break;
  88792. }
  88793. /* Construct a record from the query result, but instead of
  88794. ** saving that record, use it as a key to delete elements from
  88795. ** the temporary table iParm.
  88796. */
  88797. case SRT_Except: {
  88798. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  88799. break;
  88800. }
  88801. #endif
  88802. /* Store the result as data using a unique key.
  88803. */
  88804. case SRT_Table:
  88805. case SRT_EphemTab: {
  88806. int r1 = sqlite3GetTempReg(pParse);
  88807. testcase( eDest==SRT_Table );
  88808. testcase( eDest==SRT_EphemTab );
  88809. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  88810. if( pOrderBy ){
  88811. pushOntoSorter(pParse, pOrderBy, p, r1);
  88812. }else{
  88813. int r2 = sqlite3GetTempReg(pParse);
  88814. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  88815. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  88816. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  88817. sqlite3ReleaseTempReg(pParse, r2);
  88818. }
  88819. sqlite3ReleaseTempReg(pParse, r1);
  88820. break;
  88821. }
  88822. #ifndef SQLITE_OMIT_SUBQUERY
  88823. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  88824. ** then there should be a single item on the stack. Write this
  88825. ** item into the set table with bogus data.
  88826. */
  88827. case SRT_Set: {
  88828. assert( nColumn==1 );
  88829. pDest->affSdst =
  88830. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  88831. if( pOrderBy ){
  88832. /* At first glance you would think we could optimize out the
  88833. ** ORDER BY in this case since the order of entries in the set
  88834. ** does not matter. But there might be a LIMIT clause, in which
  88835. ** case the order does matter */
  88836. pushOntoSorter(pParse, pOrderBy, p, regResult);
  88837. }else{
  88838. int r1 = sqlite3GetTempReg(pParse);
  88839. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  88840. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  88841. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  88842. sqlite3ReleaseTempReg(pParse, r1);
  88843. }
  88844. break;
  88845. }
  88846. /* If any row exist in the result set, record that fact and abort.
  88847. */
  88848. case SRT_Exists: {
  88849. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  88850. /* The LIMIT clause will terminate the loop for us */
  88851. break;
  88852. }
  88853. /* If this is a scalar select that is part of an expression, then
  88854. ** store the results in the appropriate memory cell and break out
  88855. ** of the scan loop.
  88856. */
  88857. case SRT_Mem: {
  88858. assert( nColumn==1 );
  88859. if( pOrderBy ){
  88860. pushOntoSorter(pParse, pOrderBy, p, regResult);
  88861. }else{
  88862. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  88863. /* The LIMIT clause will jump out of the loop for us */
  88864. }
  88865. break;
  88866. }
  88867. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  88868. /* Send the data to the callback function or to a subroutine. In the
  88869. ** case of a subroutine, the subroutine itself is responsible for
  88870. ** popping the data from the stack.
  88871. */
  88872. case SRT_Coroutine:
  88873. case SRT_Output: {
  88874. testcase( eDest==SRT_Coroutine );
  88875. testcase( eDest==SRT_Output );
  88876. if( pOrderBy ){
  88877. int r1 = sqlite3GetTempReg(pParse);
  88878. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  88879. pushOntoSorter(pParse, pOrderBy, p, r1);
  88880. sqlite3ReleaseTempReg(pParse, r1);
  88881. }else if( eDest==SRT_Coroutine ){
  88882. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  88883. }else{
  88884. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  88885. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  88886. }
  88887. break;
  88888. }
  88889. #if !defined(SQLITE_OMIT_TRIGGER)
  88890. /* Discard the results. This is used for SELECT statements inside
  88891. ** the body of a TRIGGER. The purpose of such selects is to call
  88892. ** user-defined functions that have side effects. We do not care
  88893. ** about the actual results of the select.
  88894. */
  88895. default: {
  88896. assert( eDest==SRT_Discard );
  88897. break;
  88898. }
  88899. #endif
  88900. }
  88901. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  88902. ** there is a sorter, in which case the sorter has already limited
  88903. ** the output for us.
  88904. */
  88905. if( pOrderBy==0 && p->iLimit ){
  88906. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  88907. }
  88908. }
  88909. /*
  88910. ** Given an expression list, generate a KeyInfo structure that records
  88911. ** the collating sequence for each expression in that expression list.
  88912. **
  88913. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  88914. ** KeyInfo structure is appropriate for initializing a virtual index to
  88915. ** implement that clause. If the ExprList is the result set of a SELECT
  88916. ** then the KeyInfo structure is appropriate for initializing a virtual
  88917. ** index to implement a DISTINCT test.
  88918. **
  88919. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  88920. ** function is responsible for seeing that this structure is eventually
  88921. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  88922. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  88923. */
  88924. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  88925. sqlite3 *db = pParse->db;
  88926. int nExpr;
  88927. KeyInfo *pInfo;
  88928. struct ExprList_item *pItem;
  88929. int i;
  88930. nExpr = pList->nExpr;
  88931. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  88932. if( pInfo ){
  88933. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  88934. pInfo->nField = (u16)nExpr;
  88935. pInfo->enc = ENC(db);
  88936. pInfo->db = db;
  88937. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  88938. CollSeq *pColl;
  88939. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  88940. if( !pColl ){
  88941. pColl = db->pDfltColl;
  88942. }
  88943. pInfo->aColl[i] = pColl;
  88944. pInfo->aSortOrder[i] = pItem->sortOrder;
  88945. }
  88946. }
  88947. return pInfo;
  88948. }
  88949. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  88950. /*
  88951. ** Name of the connection operator, used for error messages.
  88952. */
  88953. static const char *selectOpName(int id){
  88954. char *z;
  88955. switch( id ){
  88956. case TK_ALL: z = "UNION ALL"; break;
  88957. case TK_INTERSECT: z = "INTERSECT"; break;
  88958. case TK_EXCEPT: z = "EXCEPT"; break;
  88959. default: z = "UNION"; break;
  88960. }
  88961. return z;
  88962. }
  88963. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  88964. #ifndef SQLITE_OMIT_EXPLAIN
  88965. /*
  88966. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  88967. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  88968. ** where the caption is of the form:
  88969. **
  88970. ** "USE TEMP B-TREE FOR xxx"
  88971. **
  88972. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  88973. ** is determined by the zUsage argument.
  88974. */
  88975. static void explainTempTable(Parse *pParse, const char *zUsage){
  88976. if( pParse->explain==2 ){
  88977. Vdbe *v = pParse->pVdbe;
  88978. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  88979. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  88980. }
  88981. }
  88982. /*
  88983. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  88984. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  88985. ** in sqlite3Select() to assign values to structure member variables that
  88986. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  88987. ** code with #ifndef directives.
  88988. */
  88989. # define explainSetInteger(a, b) a = b
  88990. #else
  88991. /* No-op versions of the explainXXX() functions and macros. */
  88992. # define explainTempTable(y,z)
  88993. # define explainSetInteger(y,z)
  88994. #endif
  88995. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  88996. /*
  88997. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  88998. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  88999. ** where the caption is of one of the two forms:
  89000. **
  89001. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  89002. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  89003. **
  89004. ** where iSub1 and iSub2 are the integers passed as the corresponding
  89005. ** function parameters, and op is the text representation of the parameter
  89006. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  89007. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  89008. ** false, or the second form if it is true.
  89009. */
  89010. static void explainComposite(
  89011. Parse *pParse, /* Parse context */
  89012. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  89013. int iSub1, /* Subquery id 1 */
  89014. int iSub2, /* Subquery id 2 */
  89015. int bUseTmp /* True if a temp table was used */
  89016. ){
  89017. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  89018. if( pParse->explain==2 ){
  89019. Vdbe *v = pParse->pVdbe;
  89020. char *zMsg = sqlite3MPrintf(
  89021. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  89022. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  89023. );
  89024. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  89025. }
  89026. }
  89027. #else
  89028. /* No-op versions of the explainXXX() functions and macros. */
  89029. # define explainComposite(v,w,x,y,z)
  89030. #endif
  89031. /*
  89032. ** If the inner loop was generated using a non-null pOrderBy argument,
  89033. ** then the results were placed in a sorter. After the loop is terminated
  89034. ** we need to run the sorter and output the results. The following
  89035. ** routine generates the code needed to do that.
  89036. */
  89037. static void generateSortTail(
  89038. Parse *pParse, /* Parsing context */
  89039. Select *p, /* The SELECT statement */
  89040. Vdbe *v, /* Generate code into this VDBE */
  89041. int nColumn, /* Number of columns of data */
  89042. SelectDest *pDest /* Write the sorted results here */
  89043. ){
  89044. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  89045. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  89046. int addr;
  89047. int iTab;
  89048. int pseudoTab = 0;
  89049. ExprList *pOrderBy = p->pOrderBy;
  89050. int eDest = pDest->eDest;
  89051. int iParm = pDest->iSDParm;
  89052. int regRow;
  89053. int regRowid;
  89054. iTab = pOrderBy->iECursor;
  89055. regRow = sqlite3GetTempReg(pParse);
  89056. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  89057. pseudoTab = pParse->nTab++;
  89058. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  89059. regRowid = 0;
  89060. }else{
  89061. regRowid = sqlite3GetTempReg(pParse);
  89062. }
  89063. if( p->selFlags & SF_UseSorter ){
  89064. int regSortOut = ++pParse->nMem;
  89065. int ptab2 = pParse->nTab++;
  89066. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  89067. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  89068. codeOffset(v, p, addrContinue);
  89069. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  89070. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  89071. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  89072. }else{
  89073. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  89074. codeOffset(v, p, addrContinue);
  89075. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  89076. }
  89077. switch( eDest ){
  89078. case SRT_Table:
  89079. case SRT_EphemTab: {
  89080. testcase( eDest==SRT_Table );
  89081. testcase( eDest==SRT_EphemTab );
  89082. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  89083. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  89084. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  89085. break;
  89086. }
  89087. #ifndef SQLITE_OMIT_SUBQUERY
  89088. case SRT_Set: {
  89089. assert( nColumn==1 );
  89090. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  89091. &pDest->affSdst, 1);
  89092. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  89093. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  89094. break;
  89095. }
  89096. case SRT_Mem: {
  89097. assert( nColumn==1 );
  89098. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  89099. /* The LIMIT clause will terminate the loop for us */
  89100. break;
  89101. }
  89102. #endif
  89103. default: {
  89104. int i;
  89105. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  89106. testcase( eDest==SRT_Output );
  89107. testcase( eDest==SRT_Coroutine );
  89108. for(i=0; i<nColumn; i++){
  89109. assert( regRow!=pDest->iSdst+i );
  89110. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  89111. if( i==0 ){
  89112. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  89113. }
  89114. }
  89115. if( eDest==SRT_Output ){
  89116. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  89117. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  89118. }else{
  89119. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  89120. }
  89121. break;
  89122. }
  89123. }
  89124. sqlite3ReleaseTempReg(pParse, regRow);
  89125. sqlite3ReleaseTempReg(pParse, regRowid);
  89126. /* The bottom of the loop
  89127. */
  89128. sqlite3VdbeResolveLabel(v, addrContinue);
  89129. if( p->selFlags & SF_UseSorter ){
  89130. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  89131. }else{
  89132. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  89133. }
  89134. sqlite3VdbeResolveLabel(v, addrBreak);
  89135. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  89136. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  89137. }
  89138. }
  89139. /*
  89140. ** Return a pointer to a string containing the 'declaration type' of the
  89141. ** expression pExpr. The string may be treated as static by the caller.
  89142. **
  89143. ** The declaration type is the exact datatype definition extracted from the
  89144. ** original CREATE TABLE statement if the expression is a column. The
  89145. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  89146. ** is considered a column can be complex in the presence of subqueries. The
  89147. ** result-set expression in all of the following SELECT statements is
  89148. ** considered a column by this function.
  89149. **
  89150. ** SELECT col FROM tbl;
  89151. ** SELECT (SELECT col FROM tbl;
  89152. ** SELECT (SELECT col FROM tbl);
  89153. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  89154. **
  89155. ** The declaration type for any expression other than a column is NULL.
  89156. */
  89157. static const char *columnType(
  89158. NameContext *pNC,
  89159. Expr *pExpr,
  89160. const char **pzOriginDb,
  89161. const char **pzOriginTab,
  89162. const char **pzOriginCol
  89163. ){
  89164. char const *zType = 0;
  89165. char const *zOriginDb = 0;
  89166. char const *zOriginTab = 0;
  89167. char const *zOriginCol = 0;
  89168. int j;
  89169. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  89170. switch( pExpr->op ){
  89171. case TK_AGG_COLUMN:
  89172. case TK_COLUMN: {
  89173. /* The expression is a column. Locate the table the column is being
  89174. ** extracted from in NameContext.pSrcList. This table may be real
  89175. ** database table or a subquery.
  89176. */
  89177. Table *pTab = 0; /* Table structure column is extracted from */
  89178. Select *pS = 0; /* Select the column is extracted from */
  89179. int iCol = pExpr->iColumn; /* Index of column in pTab */
  89180. testcase( pExpr->op==TK_AGG_COLUMN );
  89181. testcase( pExpr->op==TK_COLUMN );
  89182. while( pNC && !pTab ){
  89183. SrcList *pTabList = pNC->pSrcList;
  89184. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  89185. if( j<pTabList->nSrc ){
  89186. pTab = pTabList->a[j].pTab;
  89187. pS = pTabList->a[j].pSelect;
  89188. }else{
  89189. pNC = pNC->pNext;
  89190. }
  89191. }
  89192. if( pTab==0 ){
  89193. /* At one time, code such as "SELECT new.x" within a trigger would
  89194. ** cause this condition to run. Since then, we have restructured how
  89195. ** trigger code is generated and so this condition is no longer
  89196. ** possible. However, it can still be true for statements like
  89197. ** the following:
  89198. **
  89199. ** CREATE TABLE t1(col INTEGER);
  89200. ** SELECT (SELECT t1.col) FROM FROM t1;
  89201. **
  89202. ** when columnType() is called on the expression "t1.col" in the
  89203. ** sub-select. In this case, set the column type to NULL, even
  89204. ** though it should really be "INTEGER".
  89205. **
  89206. ** This is not a problem, as the column type of "t1.col" is never
  89207. ** used. When columnType() is called on the expression
  89208. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  89209. ** branch below. */
  89210. break;
  89211. }
  89212. assert( pTab && pExpr->pTab==pTab );
  89213. if( pS ){
  89214. /* The "table" is actually a sub-select or a view in the FROM clause
  89215. ** of the SELECT statement. Return the declaration type and origin
  89216. ** data for the result-set column of the sub-select.
  89217. */
  89218. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  89219. /* If iCol is less than zero, then the expression requests the
  89220. ** rowid of the sub-select or view. This expression is legal (see
  89221. ** test case misc2.2.2) - it always evaluates to NULL.
  89222. */
  89223. NameContext sNC;
  89224. Expr *p = pS->pEList->a[iCol].pExpr;
  89225. sNC.pSrcList = pS->pSrc;
  89226. sNC.pNext = pNC;
  89227. sNC.pParse = pNC->pParse;
  89228. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  89229. }
  89230. }else if( ALWAYS(pTab->pSchema) ){
  89231. /* A real table */
  89232. assert( !pS );
  89233. if( iCol<0 ) iCol = pTab->iPKey;
  89234. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  89235. if( iCol<0 ){
  89236. zType = "INTEGER";
  89237. zOriginCol = "rowid";
  89238. }else{
  89239. zType = pTab->aCol[iCol].zType;
  89240. zOriginCol = pTab->aCol[iCol].zName;
  89241. }
  89242. zOriginTab = pTab->zName;
  89243. if( pNC->pParse ){
  89244. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  89245. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  89246. }
  89247. }
  89248. break;
  89249. }
  89250. #ifndef SQLITE_OMIT_SUBQUERY
  89251. case TK_SELECT: {
  89252. /* The expression is a sub-select. Return the declaration type and
  89253. ** origin info for the single column in the result set of the SELECT
  89254. ** statement.
  89255. */
  89256. NameContext sNC;
  89257. Select *pS = pExpr->x.pSelect;
  89258. Expr *p = pS->pEList->a[0].pExpr;
  89259. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  89260. sNC.pSrcList = pS->pSrc;
  89261. sNC.pNext = pNC;
  89262. sNC.pParse = pNC->pParse;
  89263. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  89264. break;
  89265. }
  89266. #endif
  89267. }
  89268. if( pzOriginDb ){
  89269. assert( pzOriginTab && pzOriginCol );
  89270. *pzOriginDb = zOriginDb;
  89271. *pzOriginTab = zOriginTab;
  89272. *pzOriginCol = zOriginCol;
  89273. }
  89274. return zType;
  89275. }
  89276. /*
  89277. ** Generate code that will tell the VDBE the declaration types of columns
  89278. ** in the result set.
  89279. */
  89280. static void generateColumnTypes(
  89281. Parse *pParse, /* Parser context */
  89282. SrcList *pTabList, /* List of tables */
  89283. ExprList *pEList /* Expressions defining the result set */
  89284. ){
  89285. #ifndef SQLITE_OMIT_DECLTYPE
  89286. Vdbe *v = pParse->pVdbe;
  89287. int i;
  89288. NameContext sNC;
  89289. sNC.pSrcList = pTabList;
  89290. sNC.pParse = pParse;
  89291. for(i=0; i<pEList->nExpr; i++){
  89292. Expr *p = pEList->a[i].pExpr;
  89293. const char *zType;
  89294. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  89295. const char *zOrigDb = 0;
  89296. const char *zOrigTab = 0;
  89297. const char *zOrigCol = 0;
  89298. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  89299. /* The vdbe must make its own copy of the column-type and other
  89300. ** column specific strings, in case the schema is reset before this
  89301. ** virtual machine is deleted.
  89302. */
  89303. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  89304. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  89305. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  89306. #else
  89307. zType = columnType(&sNC, p, 0, 0, 0);
  89308. #endif
  89309. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  89310. }
  89311. #endif /* SQLITE_OMIT_DECLTYPE */
  89312. }
  89313. /*
  89314. ** Generate code that will tell the VDBE the names of columns
  89315. ** in the result set. This information is used to provide the
  89316. ** azCol[] values in the callback.
  89317. */
  89318. static void generateColumnNames(
  89319. Parse *pParse, /* Parser context */
  89320. SrcList *pTabList, /* List of tables */
  89321. ExprList *pEList /* Expressions defining the result set */
  89322. ){
  89323. Vdbe *v = pParse->pVdbe;
  89324. int i, j;
  89325. sqlite3 *db = pParse->db;
  89326. int fullNames, shortNames;
  89327. #ifndef SQLITE_OMIT_EXPLAIN
  89328. /* If this is an EXPLAIN, skip this step */
  89329. if( pParse->explain ){
  89330. return;
  89331. }
  89332. #endif
  89333. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  89334. pParse->colNamesSet = 1;
  89335. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  89336. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  89337. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  89338. for(i=0; i<pEList->nExpr; i++){
  89339. Expr *p;
  89340. p = pEList->a[i].pExpr;
  89341. if( NEVER(p==0) ) continue;
  89342. if( pEList->a[i].zName ){
  89343. char *zName = pEList->a[i].zName;
  89344. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  89345. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  89346. Table *pTab;
  89347. char *zCol;
  89348. int iCol = p->iColumn;
  89349. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  89350. if( pTabList->a[j].iCursor==p->iTable ) break;
  89351. }
  89352. assert( j<pTabList->nSrc );
  89353. pTab = pTabList->a[j].pTab;
  89354. if( iCol<0 ) iCol = pTab->iPKey;
  89355. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  89356. if( iCol<0 ){
  89357. zCol = "rowid";
  89358. }else{
  89359. zCol = pTab->aCol[iCol].zName;
  89360. }
  89361. if( !shortNames && !fullNames ){
  89362. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  89363. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  89364. }else if( fullNames ){
  89365. char *zName = 0;
  89366. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  89367. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  89368. }else{
  89369. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  89370. }
  89371. }else{
  89372. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  89373. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  89374. }
  89375. }
  89376. generateColumnTypes(pParse, pTabList, pEList);
  89377. }
  89378. /*
  89379. ** Given a an expression list (which is really the list of expressions
  89380. ** that form the result set of a SELECT statement) compute appropriate
  89381. ** column names for a table that would hold the expression list.
  89382. **
  89383. ** All column names will be unique.
  89384. **
  89385. ** Only the column names are computed. Column.zType, Column.zColl,
  89386. ** and other fields of Column are zeroed.
  89387. **
  89388. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  89389. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  89390. */
  89391. static int selectColumnsFromExprList(
  89392. Parse *pParse, /* Parsing context */
  89393. ExprList *pEList, /* Expr list from which to derive column names */
  89394. i16 *pnCol, /* Write the number of columns here */
  89395. Column **paCol /* Write the new column list here */
  89396. ){
  89397. sqlite3 *db = pParse->db; /* Database connection */
  89398. int i, j; /* Loop counters */
  89399. int cnt; /* Index added to make the name unique */
  89400. Column *aCol, *pCol; /* For looping over result columns */
  89401. int nCol; /* Number of columns in the result set */
  89402. Expr *p; /* Expression for a single result column */
  89403. char *zName; /* Column name */
  89404. int nName; /* Size of name in zName[] */
  89405. if( pEList ){
  89406. nCol = pEList->nExpr;
  89407. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  89408. testcase( aCol==0 );
  89409. }else{
  89410. nCol = 0;
  89411. aCol = 0;
  89412. }
  89413. *pnCol = nCol;
  89414. *paCol = aCol;
  89415. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  89416. /* Get an appropriate name for the column
  89417. */
  89418. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  89419. assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
  89420. || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
  89421. if( (zName = pEList->a[i].zName)!=0 ){
  89422. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  89423. zName = sqlite3DbStrDup(db, zName);
  89424. }else{
  89425. Expr *pColExpr = p; /* The expression that is the result column name */
  89426. Table *pTab; /* Table associated with this expression */
  89427. while( pColExpr->op==TK_DOT ){
  89428. pColExpr = pColExpr->pRight;
  89429. assert( pColExpr!=0 );
  89430. }
  89431. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  89432. /* For columns use the column name name */
  89433. int iCol = pColExpr->iColumn;
  89434. pTab = pColExpr->pTab;
  89435. if( iCol<0 ) iCol = pTab->iPKey;
  89436. zName = sqlite3MPrintf(db, "%s",
  89437. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  89438. }else if( pColExpr->op==TK_ID ){
  89439. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  89440. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  89441. }else{
  89442. /* Use the original text of the column expression as its name */
  89443. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  89444. }
  89445. }
  89446. if( db->mallocFailed ){
  89447. sqlite3DbFree(db, zName);
  89448. break;
  89449. }
  89450. /* Make sure the column name is unique. If the name is not unique,
  89451. ** append a integer to the name so that it becomes unique.
  89452. */
  89453. nName = sqlite3Strlen30(zName);
  89454. for(j=cnt=0; j<i; j++){
  89455. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  89456. char *zNewName;
  89457. zName[nName] = 0;
  89458. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  89459. sqlite3DbFree(db, zName);
  89460. zName = zNewName;
  89461. j = -1;
  89462. if( zName==0 ) break;
  89463. }
  89464. }
  89465. pCol->zName = zName;
  89466. }
  89467. if( db->mallocFailed ){
  89468. for(j=0; j<i; j++){
  89469. sqlite3DbFree(db, aCol[j].zName);
  89470. }
  89471. sqlite3DbFree(db, aCol);
  89472. *paCol = 0;
  89473. *pnCol = 0;
  89474. return SQLITE_NOMEM;
  89475. }
  89476. return SQLITE_OK;
  89477. }
  89478. /*
  89479. ** Add type and collation information to a column list based on
  89480. ** a SELECT statement.
  89481. **
  89482. ** The column list presumably came from selectColumnNamesFromExprList().
  89483. ** The column list has only names, not types or collations. This
  89484. ** routine goes through and adds the types and collations.
  89485. **
  89486. ** This routine requires that all identifiers in the SELECT
  89487. ** statement be resolved.
  89488. */
  89489. static void selectAddColumnTypeAndCollation(
  89490. Parse *pParse, /* Parsing contexts */
  89491. int nCol, /* Number of columns */
  89492. Column *aCol, /* List of columns */
  89493. Select *pSelect /* SELECT used to determine types and collations */
  89494. ){
  89495. sqlite3 *db = pParse->db;
  89496. NameContext sNC;
  89497. Column *pCol;
  89498. CollSeq *pColl;
  89499. int i;
  89500. Expr *p;
  89501. struct ExprList_item *a;
  89502. assert( pSelect!=0 );
  89503. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  89504. assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  89505. if( db->mallocFailed ) return;
  89506. memset(&sNC, 0, sizeof(sNC));
  89507. sNC.pSrcList = pSelect->pSrc;
  89508. a = pSelect->pEList->a;
  89509. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  89510. p = a[i].pExpr;
  89511. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  89512. pCol->affinity = sqlite3ExprAffinity(p);
  89513. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  89514. pColl = sqlite3ExprCollSeq(pParse, p);
  89515. if( pColl ){
  89516. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  89517. }
  89518. }
  89519. }
  89520. /*
  89521. ** Given a SELECT statement, generate a Table structure that describes
  89522. ** the result set of that SELECT.
  89523. */
  89524. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  89525. Table *pTab;
  89526. sqlite3 *db = pParse->db;
  89527. int savedFlags;
  89528. savedFlags = db->flags;
  89529. db->flags &= ~SQLITE_FullColNames;
  89530. db->flags |= SQLITE_ShortColNames;
  89531. sqlite3SelectPrep(pParse, pSelect, 0);
  89532. if( pParse->nErr ) return 0;
  89533. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  89534. db->flags = savedFlags;
  89535. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  89536. if( pTab==0 ){
  89537. return 0;
  89538. }
  89539. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  89540. ** is disabled */
  89541. assert( db->lookaside.bEnabled==0 );
  89542. pTab->nRef = 1;
  89543. pTab->zName = 0;
  89544. pTab->nRowEst = 1000000;
  89545. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  89546. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  89547. pTab->iPKey = -1;
  89548. if( db->mallocFailed ){
  89549. sqlite3DeleteTable(db, pTab);
  89550. return 0;
  89551. }
  89552. return pTab;
  89553. }
  89554. /*
  89555. ** Get a VDBE for the given parser context. Create a new one if necessary.
  89556. ** If an error occurs, return NULL and leave a message in pParse.
  89557. */
  89558. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  89559. Vdbe *v = pParse->pVdbe;
  89560. if( v==0 ){
  89561. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  89562. #ifndef SQLITE_OMIT_TRACE
  89563. if( v ){
  89564. sqlite3VdbeAddOp0(v, OP_Trace);
  89565. }
  89566. #endif
  89567. }
  89568. return v;
  89569. }
  89570. /*
  89571. ** Compute the iLimit and iOffset fields of the SELECT based on the
  89572. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  89573. ** that appear in the original SQL statement after the LIMIT and OFFSET
  89574. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  89575. ** are the integer memory register numbers for counters used to compute
  89576. ** the limit and offset. If there is no limit and/or offset, then
  89577. ** iLimit and iOffset are negative.
  89578. **
  89579. ** This routine changes the values of iLimit and iOffset only if
  89580. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  89581. ** iOffset should have been preset to appropriate default values
  89582. ** (usually but not always -1) prior to calling this routine.
  89583. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  89584. ** redefined. The UNION ALL operator uses this property to force
  89585. ** the reuse of the same limit and offset registers across multiple
  89586. ** SELECT statements.
  89587. */
  89588. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  89589. Vdbe *v = 0;
  89590. int iLimit = 0;
  89591. int iOffset;
  89592. int addr1, n;
  89593. if( p->iLimit ) return;
  89594. /*
  89595. ** "LIMIT -1" always shows all rows. There is some
  89596. ** contraversy about what the correct behavior should be.
  89597. ** The current implementation interprets "LIMIT 0" to mean
  89598. ** no rows.
  89599. */
  89600. sqlite3ExprCacheClear(pParse);
  89601. assert( p->pOffset==0 || p->pLimit!=0 );
  89602. if( p->pLimit ){
  89603. p->iLimit = iLimit = ++pParse->nMem;
  89604. v = sqlite3GetVdbe(pParse);
  89605. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  89606. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  89607. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  89608. VdbeComment((v, "LIMIT counter"));
  89609. if( n==0 ){
  89610. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  89611. }else{
  89612. if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
  89613. }
  89614. }else{
  89615. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  89616. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  89617. VdbeComment((v, "LIMIT counter"));
  89618. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  89619. }
  89620. if( p->pOffset ){
  89621. p->iOffset = iOffset = ++pParse->nMem;
  89622. pParse->nMem++; /* Allocate an extra register for limit+offset */
  89623. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  89624. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  89625. VdbeComment((v, "OFFSET counter"));
  89626. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  89627. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  89628. sqlite3VdbeJumpHere(v, addr1);
  89629. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  89630. VdbeComment((v, "LIMIT+OFFSET"));
  89631. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  89632. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  89633. sqlite3VdbeJumpHere(v, addr1);
  89634. }
  89635. }
  89636. }
  89637. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  89638. /*
  89639. ** Return the appropriate collating sequence for the iCol-th column of
  89640. ** the result set for the compound-select statement "p". Return NULL if
  89641. ** the column has no default collating sequence.
  89642. **
  89643. ** The collating sequence for the compound select is taken from the
  89644. ** left-most term of the select that has a collating sequence.
  89645. */
  89646. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  89647. CollSeq *pRet;
  89648. if( p->pPrior ){
  89649. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  89650. }else{
  89651. pRet = 0;
  89652. }
  89653. assert( iCol>=0 );
  89654. if( pRet==0 && iCol<p->pEList->nExpr ){
  89655. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  89656. }
  89657. return pRet;
  89658. }
  89659. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  89660. /* Forward reference */
  89661. static int multiSelectOrderBy(
  89662. Parse *pParse, /* Parsing context */
  89663. Select *p, /* The right-most of SELECTs to be coded */
  89664. SelectDest *pDest /* What to do with query results */
  89665. );
  89666. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  89667. /*
  89668. ** This routine is called to process a compound query form from
  89669. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  89670. ** INTERSECT
  89671. **
  89672. ** "p" points to the right-most of the two queries. the query on the
  89673. ** left is p->pPrior. The left query could also be a compound query
  89674. ** in which case this routine will be called recursively.
  89675. **
  89676. ** The results of the total query are to be written into a destination
  89677. ** of type eDest with parameter iParm.
  89678. **
  89679. ** Example 1: Consider a three-way compound SQL statement.
  89680. **
  89681. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  89682. **
  89683. ** This statement is parsed up as follows:
  89684. **
  89685. ** SELECT c FROM t3
  89686. ** |
  89687. ** `-----> SELECT b FROM t2
  89688. ** |
  89689. ** `------> SELECT a FROM t1
  89690. **
  89691. ** The arrows in the diagram above represent the Select.pPrior pointer.
  89692. ** So if this routine is called with p equal to the t3 query, then
  89693. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  89694. **
  89695. ** Notice that because of the way SQLite parses compound SELECTs, the
  89696. ** individual selects always group from left to right.
  89697. */
  89698. static int multiSelect(
  89699. Parse *pParse, /* Parsing context */
  89700. Select *p, /* The right-most of SELECTs to be coded */
  89701. SelectDest *pDest /* What to do with query results */
  89702. ){
  89703. int rc = SQLITE_OK; /* Success code from a subroutine */
  89704. Select *pPrior; /* Another SELECT immediately to our left */
  89705. Vdbe *v; /* Generate code to this VDBE */
  89706. SelectDest dest; /* Alternative data destination */
  89707. Select *pDelete = 0; /* Chain of simple selects to delete */
  89708. sqlite3 *db; /* Database connection */
  89709. #ifndef SQLITE_OMIT_EXPLAIN
  89710. int iSub1; /* EQP id of left-hand query */
  89711. int iSub2; /* EQP id of right-hand query */
  89712. #endif
  89713. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  89714. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  89715. */
  89716. assert( p && p->pPrior ); /* Calling function guarantees this much */
  89717. db = pParse->db;
  89718. pPrior = p->pPrior;
  89719. assert( pPrior->pRightmost!=pPrior );
  89720. assert( pPrior->pRightmost==p->pRightmost );
  89721. dest = *pDest;
  89722. if( pPrior->pOrderBy ){
  89723. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  89724. selectOpName(p->op));
  89725. rc = 1;
  89726. goto multi_select_end;
  89727. }
  89728. if( pPrior->pLimit ){
  89729. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  89730. selectOpName(p->op));
  89731. rc = 1;
  89732. goto multi_select_end;
  89733. }
  89734. v = sqlite3GetVdbe(pParse);
  89735. assert( v!=0 ); /* The VDBE already created by calling function */
  89736. /* Create the destination temporary table if necessary
  89737. */
  89738. if( dest.eDest==SRT_EphemTab ){
  89739. assert( p->pEList );
  89740. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  89741. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  89742. dest.eDest = SRT_Table;
  89743. }
  89744. /* Make sure all SELECTs in the statement have the same number of elements
  89745. ** in their result sets.
  89746. */
  89747. assert( p->pEList && pPrior->pEList );
  89748. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  89749. if( p->selFlags & SF_Values ){
  89750. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  89751. }else{
  89752. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  89753. " do not have the same number of result columns", selectOpName(p->op));
  89754. }
  89755. rc = 1;
  89756. goto multi_select_end;
  89757. }
  89758. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  89759. */
  89760. if( p->pOrderBy ){
  89761. return multiSelectOrderBy(pParse, p, pDest);
  89762. }
  89763. /* Generate code for the left and right SELECT statements.
  89764. */
  89765. switch( p->op ){
  89766. case TK_ALL: {
  89767. int addr = 0;
  89768. int nLimit;
  89769. assert( !pPrior->pLimit );
  89770. pPrior->pLimit = p->pLimit;
  89771. pPrior->pOffset = p->pOffset;
  89772. explainSetInteger(iSub1, pParse->iNextSelectId);
  89773. rc = sqlite3Select(pParse, pPrior, &dest);
  89774. p->pLimit = 0;
  89775. p->pOffset = 0;
  89776. if( rc ){
  89777. goto multi_select_end;
  89778. }
  89779. p->pPrior = 0;
  89780. p->iLimit = pPrior->iLimit;
  89781. p->iOffset = pPrior->iOffset;
  89782. if( p->iLimit ){
  89783. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  89784. VdbeComment((v, "Jump ahead if LIMIT reached"));
  89785. }
  89786. explainSetInteger(iSub2, pParse->iNextSelectId);
  89787. rc = sqlite3Select(pParse, p, &dest);
  89788. testcase( rc!=SQLITE_OK );
  89789. pDelete = p->pPrior;
  89790. p->pPrior = pPrior;
  89791. p->nSelectRow += pPrior->nSelectRow;
  89792. if( pPrior->pLimit
  89793. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  89794. && p->nSelectRow > (double)nLimit
  89795. ){
  89796. p->nSelectRow = (double)nLimit;
  89797. }
  89798. if( addr ){
  89799. sqlite3VdbeJumpHere(v, addr);
  89800. }
  89801. break;
  89802. }
  89803. case TK_EXCEPT:
  89804. case TK_UNION: {
  89805. int unionTab; /* Cursor number of the temporary table holding result */
  89806. u8 op = 0; /* One of the SRT_ operations to apply to self */
  89807. int priorOp; /* The SRT_ operation to apply to prior selects */
  89808. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  89809. int addr;
  89810. SelectDest uniondest;
  89811. testcase( p->op==TK_EXCEPT );
  89812. testcase( p->op==TK_UNION );
  89813. priorOp = SRT_Union;
  89814. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  89815. /* We can reuse a temporary table generated by a SELECT to our
  89816. ** right.
  89817. */
  89818. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  89819. ** of a 3-way or more compound */
  89820. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  89821. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  89822. unionTab = dest.iSDParm;
  89823. }else{
  89824. /* We will need to create our own temporary table to hold the
  89825. ** intermediate results.
  89826. */
  89827. unionTab = pParse->nTab++;
  89828. assert( p->pOrderBy==0 );
  89829. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  89830. assert( p->addrOpenEphm[0] == -1 );
  89831. p->addrOpenEphm[0] = addr;
  89832. p->pRightmost->selFlags |= SF_UsesEphemeral;
  89833. assert( p->pEList );
  89834. }
  89835. /* Code the SELECT statements to our left
  89836. */
  89837. assert( !pPrior->pOrderBy );
  89838. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  89839. explainSetInteger(iSub1, pParse->iNextSelectId);
  89840. rc = sqlite3Select(pParse, pPrior, &uniondest);
  89841. if( rc ){
  89842. goto multi_select_end;
  89843. }
  89844. /* Code the current SELECT statement
  89845. */
  89846. if( p->op==TK_EXCEPT ){
  89847. op = SRT_Except;
  89848. }else{
  89849. assert( p->op==TK_UNION );
  89850. op = SRT_Union;
  89851. }
  89852. p->pPrior = 0;
  89853. pLimit = p->pLimit;
  89854. p->pLimit = 0;
  89855. pOffset = p->pOffset;
  89856. p->pOffset = 0;
  89857. uniondest.eDest = op;
  89858. explainSetInteger(iSub2, pParse->iNextSelectId);
  89859. rc = sqlite3Select(pParse, p, &uniondest);
  89860. testcase( rc!=SQLITE_OK );
  89861. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  89862. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  89863. sqlite3ExprListDelete(db, p->pOrderBy);
  89864. pDelete = p->pPrior;
  89865. p->pPrior = pPrior;
  89866. p->pOrderBy = 0;
  89867. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  89868. sqlite3ExprDelete(db, p->pLimit);
  89869. p->pLimit = pLimit;
  89870. p->pOffset = pOffset;
  89871. p->iLimit = 0;
  89872. p->iOffset = 0;
  89873. /* Convert the data in the temporary table into whatever form
  89874. ** it is that we currently need.
  89875. */
  89876. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  89877. if( dest.eDest!=priorOp ){
  89878. int iCont, iBreak, iStart;
  89879. assert( p->pEList );
  89880. if( dest.eDest==SRT_Output ){
  89881. Select *pFirst = p;
  89882. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  89883. generateColumnNames(pParse, 0, pFirst->pEList);
  89884. }
  89885. iBreak = sqlite3VdbeMakeLabel(v);
  89886. iCont = sqlite3VdbeMakeLabel(v);
  89887. computeLimitRegisters(pParse, p, iBreak);
  89888. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  89889. iStart = sqlite3VdbeCurrentAddr(v);
  89890. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  89891. 0, 0, &dest, iCont, iBreak);
  89892. sqlite3VdbeResolveLabel(v, iCont);
  89893. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  89894. sqlite3VdbeResolveLabel(v, iBreak);
  89895. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  89896. }
  89897. break;
  89898. }
  89899. default: assert( p->op==TK_INTERSECT ); {
  89900. int tab1, tab2;
  89901. int iCont, iBreak, iStart;
  89902. Expr *pLimit, *pOffset;
  89903. int addr;
  89904. SelectDest intersectdest;
  89905. int r1;
  89906. /* INTERSECT is different from the others since it requires
  89907. ** two temporary tables. Hence it has its own case. Begin
  89908. ** by allocating the tables we will need.
  89909. */
  89910. tab1 = pParse->nTab++;
  89911. tab2 = pParse->nTab++;
  89912. assert( p->pOrderBy==0 );
  89913. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  89914. assert( p->addrOpenEphm[0] == -1 );
  89915. p->addrOpenEphm[0] = addr;
  89916. p->pRightmost->selFlags |= SF_UsesEphemeral;
  89917. assert( p->pEList );
  89918. /* Code the SELECTs to our left into temporary table "tab1".
  89919. */
  89920. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  89921. explainSetInteger(iSub1, pParse->iNextSelectId);
  89922. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  89923. if( rc ){
  89924. goto multi_select_end;
  89925. }
  89926. /* Code the current SELECT into temporary table "tab2"
  89927. */
  89928. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  89929. assert( p->addrOpenEphm[1] == -1 );
  89930. p->addrOpenEphm[1] = addr;
  89931. p->pPrior = 0;
  89932. pLimit = p->pLimit;
  89933. p->pLimit = 0;
  89934. pOffset = p->pOffset;
  89935. p->pOffset = 0;
  89936. intersectdest.iSDParm = tab2;
  89937. explainSetInteger(iSub2, pParse->iNextSelectId);
  89938. rc = sqlite3Select(pParse, p, &intersectdest);
  89939. testcase( rc!=SQLITE_OK );
  89940. pDelete = p->pPrior;
  89941. p->pPrior = pPrior;
  89942. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  89943. sqlite3ExprDelete(db, p->pLimit);
  89944. p->pLimit = pLimit;
  89945. p->pOffset = pOffset;
  89946. /* Generate code to take the intersection of the two temporary
  89947. ** tables.
  89948. */
  89949. assert( p->pEList );
  89950. if( dest.eDest==SRT_Output ){
  89951. Select *pFirst = p;
  89952. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  89953. generateColumnNames(pParse, 0, pFirst->pEList);
  89954. }
  89955. iBreak = sqlite3VdbeMakeLabel(v);
  89956. iCont = sqlite3VdbeMakeLabel(v);
  89957. computeLimitRegisters(pParse, p, iBreak);
  89958. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  89959. r1 = sqlite3GetTempReg(pParse);
  89960. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  89961. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  89962. sqlite3ReleaseTempReg(pParse, r1);
  89963. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  89964. 0, 0, &dest, iCont, iBreak);
  89965. sqlite3VdbeResolveLabel(v, iCont);
  89966. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  89967. sqlite3VdbeResolveLabel(v, iBreak);
  89968. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  89969. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  89970. break;
  89971. }
  89972. }
  89973. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  89974. /* Compute collating sequences used by
  89975. ** temporary tables needed to implement the compound select.
  89976. ** Attach the KeyInfo structure to all temporary tables.
  89977. **
  89978. ** This section is run by the right-most SELECT statement only.
  89979. ** SELECT statements to the left always skip this part. The right-most
  89980. ** SELECT might also skip this part if it has no ORDER BY clause and
  89981. ** no temp tables are required.
  89982. */
  89983. if( p->selFlags & SF_UsesEphemeral ){
  89984. int i; /* Loop counter */
  89985. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  89986. Select *pLoop; /* For looping through SELECT statements */
  89987. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  89988. int nCol; /* Number of columns in result set */
  89989. assert( p->pRightmost==p );
  89990. nCol = p->pEList->nExpr;
  89991. pKeyInfo = sqlite3DbMallocZero(db,
  89992. sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  89993. if( !pKeyInfo ){
  89994. rc = SQLITE_NOMEM;
  89995. goto multi_select_end;
  89996. }
  89997. pKeyInfo->enc = ENC(db);
  89998. pKeyInfo->nField = (u16)nCol;
  89999. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  90000. *apColl = multiSelectCollSeq(pParse, p, i);
  90001. if( 0==*apColl ){
  90002. *apColl = db->pDfltColl;
  90003. }
  90004. }
  90005. pKeyInfo->aSortOrder = (u8*)apColl;
  90006. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  90007. for(i=0; i<2; i++){
  90008. int addr = pLoop->addrOpenEphm[i];
  90009. if( addr<0 ){
  90010. /* If [0] is unused then [1] is also unused. So we can
  90011. ** always safely abort as soon as the first unused slot is found */
  90012. assert( pLoop->addrOpenEphm[1]<0 );
  90013. break;
  90014. }
  90015. sqlite3VdbeChangeP2(v, addr, nCol);
  90016. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  90017. pLoop->addrOpenEphm[i] = -1;
  90018. }
  90019. }
  90020. sqlite3DbFree(db, pKeyInfo);
  90021. }
  90022. multi_select_end:
  90023. pDest->iSdst = dest.iSdst;
  90024. pDest->nSdst = dest.nSdst;
  90025. sqlite3SelectDelete(db, pDelete);
  90026. return rc;
  90027. }
  90028. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  90029. /*
  90030. ** Code an output subroutine for a coroutine implementation of a
  90031. ** SELECT statment.
  90032. **
  90033. ** The data to be output is contained in pIn->iSdst. There are
  90034. ** pIn->nSdst columns to be output. pDest is where the output should
  90035. ** be sent.
  90036. **
  90037. ** regReturn is the number of the register holding the subroutine
  90038. ** return address.
  90039. **
  90040. ** If regPrev>0 then it is the first register in a vector that
  90041. ** records the previous output. mem[regPrev] is a flag that is false
  90042. ** if there has been no previous output. If regPrev>0 then code is
  90043. ** generated to suppress duplicates. pKeyInfo is used for comparing
  90044. ** keys.
  90045. **
  90046. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  90047. ** iBreak.
  90048. */
  90049. static int generateOutputSubroutine(
  90050. Parse *pParse, /* Parsing context */
  90051. Select *p, /* The SELECT statement */
  90052. SelectDest *pIn, /* Coroutine supplying data */
  90053. SelectDest *pDest, /* Where to send the data */
  90054. int regReturn, /* The return address register */
  90055. int regPrev, /* Previous result register. No uniqueness if 0 */
  90056. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  90057. int p4type, /* The p4 type for pKeyInfo */
  90058. int iBreak /* Jump here if we hit the LIMIT */
  90059. ){
  90060. Vdbe *v = pParse->pVdbe;
  90061. int iContinue;
  90062. int addr;
  90063. addr = sqlite3VdbeCurrentAddr(v);
  90064. iContinue = sqlite3VdbeMakeLabel(v);
  90065. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  90066. */
  90067. if( regPrev ){
  90068. int j1, j2;
  90069. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  90070. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  90071. (char*)pKeyInfo, p4type);
  90072. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  90073. sqlite3VdbeJumpHere(v, j1);
  90074. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  90075. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  90076. }
  90077. if( pParse->db->mallocFailed ) return 0;
  90078. /* Suppress the first OFFSET entries if there is an OFFSET clause
  90079. */
  90080. codeOffset(v, p, iContinue);
  90081. switch( pDest->eDest ){
  90082. /* Store the result as data using a unique key.
  90083. */
  90084. case SRT_Table:
  90085. case SRT_EphemTab: {
  90086. int r1 = sqlite3GetTempReg(pParse);
  90087. int r2 = sqlite3GetTempReg(pParse);
  90088. testcase( pDest->eDest==SRT_Table );
  90089. testcase( pDest->eDest==SRT_EphemTab );
  90090. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  90091. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  90092. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  90093. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  90094. sqlite3ReleaseTempReg(pParse, r2);
  90095. sqlite3ReleaseTempReg(pParse, r1);
  90096. break;
  90097. }
  90098. #ifndef SQLITE_OMIT_SUBQUERY
  90099. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  90100. ** then there should be a single item on the stack. Write this
  90101. ** item into the set table with bogus data.
  90102. */
  90103. case SRT_Set: {
  90104. int r1;
  90105. assert( pIn->nSdst==1 );
  90106. pDest->affSdst =
  90107. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  90108. r1 = sqlite3GetTempReg(pParse);
  90109. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  90110. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  90111. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  90112. sqlite3ReleaseTempReg(pParse, r1);
  90113. break;
  90114. }
  90115. #if 0 /* Never occurs on an ORDER BY query */
  90116. /* If any row exist in the result set, record that fact and abort.
  90117. */
  90118. case SRT_Exists: {
  90119. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  90120. /* The LIMIT clause will terminate the loop for us */
  90121. break;
  90122. }
  90123. #endif
  90124. /* If this is a scalar select that is part of an expression, then
  90125. ** store the results in the appropriate memory cell and break out
  90126. ** of the scan loop.
  90127. */
  90128. case SRT_Mem: {
  90129. assert( pIn->nSdst==1 );
  90130. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  90131. /* The LIMIT clause will jump out of the loop for us */
  90132. break;
  90133. }
  90134. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  90135. /* The results are stored in a sequence of registers
  90136. ** starting at pDest->iSdst. Then the co-routine yields.
  90137. */
  90138. case SRT_Coroutine: {
  90139. if( pDest->iSdst==0 ){
  90140. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  90141. pDest->nSdst = pIn->nSdst;
  90142. }
  90143. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  90144. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  90145. break;
  90146. }
  90147. /* If none of the above, then the result destination must be
  90148. ** SRT_Output. This routine is never called with any other
  90149. ** destination other than the ones handled above or SRT_Output.
  90150. **
  90151. ** For SRT_Output, results are stored in a sequence of registers.
  90152. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  90153. ** return the next row of result.
  90154. */
  90155. default: {
  90156. assert( pDest->eDest==SRT_Output );
  90157. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  90158. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  90159. break;
  90160. }
  90161. }
  90162. /* Jump to the end of the loop if the LIMIT is reached.
  90163. */
  90164. if( p->iLimit ){
  90165. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  90166. }
  90167. /* Generate the subroutine return
  90168. */
  90169. sqlite3VdbeResolveLabel(v, iContinue);
  90170. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  90171. return addr;
  90172. }
  90173. /*
  90174. ** Alternative compound select code generator for cases when there
  90175. ** is an ORDER BY clause.
  90176. **
  90177. ** We assume a query of the following form:
  90178. **
  90179. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  90180. **
  90181. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  90182. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  90183. ** co-routines. Then run the co-routines in parallel and merge the results
  90184. ** into the output. In addition to the two coroutines (called selectA and
  90185. ** selectB) there are 7 subroutines:
  90186. **
  90187. ** outA: Move the output of the selectA coroutine into the output
  90188. ** of the compound query.
  90189. **
  90190. ** outB: Move the output of the selectB coroutine into the output
  90191. ** of the compound query. (Only generated for UNION and
  90192. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  90193. ** appears only in B.)
  90194. **
  90195. ** AltB: Called when there is data from both coroutines and A<B.
  90196. **
  90197. ** AeqB: Called when there is data from both coroutines and A==B.
  90198. **
  90199. ** AgtB: Called when there is data from both coroutines and A>B.
  90200. **
  90201. ** EofA: Called when data is exhausted from selectA.
  90202. **
  90203. ** EofB: Called when data is exhausted from selectB.
  90204. **
  90205. ** The implementation of the latter five subroutines depend on which
  90206. ** <operator> is used:
  90207. **
  90208. **
  90209. ** UNION ALL UNION EXCEPT INTERSECT
  90210. ** ------------- ----------------- -------------- -----------------
  90211. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  90212. **
  90213. ** AeqB: outA, nextA nextA nextA outA, nextA
  90214. **
  90215. ** AgtB: outB, nextB outB, nextB nextB nextB
  90216. **
  90217. ** EofA: outB, nextB outB, nextB halt halt
  90218. **
  90219. ** EofB: outA, nextA outA, nextA outA, nextA halt
  90220. **
  90221. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  90222. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  90223. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  90224. ** following nextX causes a jump to the end of the select processing.
  90225. **
  90226. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  90227. ** within the output subroutine. The regPrev register set holds the previously
  90228. ** output value. A comparison is made against this value and the output
  90229. ** is skipped if the next results would be the same as the previous.
  90230. **
  90231. ** The implementation plan is to implement the two coroutines and seven
  90232. ** subroutines first, then put the control logic at the bottom. Like this:
  90233. **
  90234. ** goto Init
  90235. ** coA: coroutine for left query (A)
  90236. ** coB: coroutine for right query (B)
  90237. ** outA: output one row of A
  90238. ** outB: output one row of B (UNION and UNION ALL only)
  90239. ** EofA: ...
  90240. ** EofB: ...
  90241. ** AltB: ...
  90242. ** AeqB: ...
  90243. ** AgtB: ...
  90244. ** Init: initialize coroutine registers
  90245. ** yield coA
  90246. ** if eof(A) goto EofA
  90247. ** yield coB
  90248. ** if eof(B) goto EofB
  90249. ** Cmpr: Compare A, B
  90250. ** Jump AltB, AeqB, AgtB
  90251. ** End: ...
  90252. **
  90253. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  90254. ** actually called using Gosub and they do not Return. EofA and EofB loop
  90255. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  90256. ** and AgtB jump to either L2 or to one of EofA or EofB.
  90257. */
  90258. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  90259. static int multiSelectOrderBy(
  90260. Parse *pParse, /* Parsing context */
  90261. Select *p, /* The right-most of SELECTs to be coded */
  90262. SelectDest *pDest /* What to do with query results */
  90263. ){
  90264. int i, j; /* Loop counters */
  90265. Select *pPrior; /* Another SELECT immediately to our left */
  90266. Vdbe *v; /* Generate code to this VDBE */
  90267. SelectDest destA; /* Destination for coroutine A */
  90268. SelectDest destB; /* Destination for coroutine B */
  90269. int regAddrA; /* Address register for select-A coroutine */
  90270. int regEofA; /* Flag to indicate when select-A is complete */
  90271. int regAddrB; /* Address register for select-B coroutine */
  90272. int regEofB; /* Flag to indicate when select-B is complete */
  90273. int addrSelectA; /* Address of the select-A coroutine */
  90274. int addrSelectB; /* Address of the select-B coroutine */
  90275. int regOutA; /* Address register for the output-A subroutine */
  90276. int regOutB; /* Address register for the output-B subroutine */
  90277. int addrOutA; /* Address of the output-A subroutine */
  90278. int addrOutB = 0; /* Address of the output-B subroutine */
  90279. int addrEofA; /* Address of the select-A-exhausted subroutine */
  90280. int addrEofB; /* Address of the select-B-exhausted subroutine */
  90281. int addrAltB; /* Address of the A<B subroutine */
  90282. int addrAeqB; /* Address of the A==B subroutine */
  90283. int addrAgtB; /* Address of the A>B subroutine */
  90284. int regLimitA; /* Limit register for select-A */
  90285. int regLimitB; /* Limit register for select-A */
  90286. int regPrev; /* A range of registers to hold previous output */
  90287. int savedLimit; /* Saved value of p->iLimit */
  90288. int savedOffset; /* Saved value of p->iOffset */
  90289. int labelCmpr; /* Label for the start of the merge algorithm */
  90290. int labelEnd; /* Label for the end of the overall SELECT stmt */
  90291. int j1; /* Jump instructions that get retargetted */
  90292. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  90293. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  90294. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  90295. sqlite3 *db; /* Database connection */
  90296. ExprList *pOrderBy; /* The ORDER BY clause */
  90297. int nOrderBy; /* Number of terms in the ORDER BY clause */
  90298. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  90299. #ifndef SQLITE_OMIT_EXPLAIN
  90300. int iSub1; /* EQP id of left-hand query */
  90301. int iSub2; /* EQP id of right-hand query */
  90302. #endif
  90303. assert( p->pOrderBy!=0 );
  90304. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  90305. db = pParse->db;
  90306. v = pParse->pVdbe;
  90307. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  90308. labelEnd = sqlite3VdbeMakeLabel(v);
  90309. labelCmpr = sqlite3VdbeMakeLabel(v);
  90310. /* Patch up the ORDER BY clause
  90311. */
  90312. op = p->op;
  90313. pPrior = p->pPrior;
  90314. assert( pPrior->pOrderBy==0 );
  90315. pOrderBy = p->pOrderBy;
  90316. assert( pOrderBy );
  90317. nOrderBy = pOrderBy->nExpr;
  90318. /* For operators other than UNION ALL we have to make sure that
  90319. ** the ORDER BY clause covers every term of the result set. Add
  90320. ** terms to the ORDER BY clause as necessary.
  90321. */
  90322. if( op!=TK_ALL ){
  90323. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  90324. struct ExprList_item *pItem;
  90325. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  90326. assert( pItem->iOrderByCol>0 );
  90327. if( pItem->iOrderByCol==i ) break;
  90328. }
  90329. if( j==nOrderBy ){
  90330. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  90331. if( pNew==0 ) return SQLITE_NOMEM;
  90332. pNew->flags |= EP_IntValue;
  90333. pNew->u.iValue = i;
  90334. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  90335. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  90336. }
  90337. }
  90338. }
  90339. /* Compute the comparison permutation and keyinfo that is used with
  90340. ** the permutation used to determine if the next
  90341. ** row of results comes from selectA or selectB. Also add explicit
  90342. ** collations to the ORDER BY clause terms so that when the subqueries
  90343. ** to the right and the left are evaluated, they use the correct
  90344. ** collation.
  90345. */
  90346. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  90347. if( aPermute ){
  90348. struct ExprList_item *pItem;
  90349. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  90350. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  90351. aPermute[i] = pItem->iOrderByCol - 1;
  90352. }
  90353. pKeyMerge =
  90354. sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  90355. if( pKeyMerge ){
  90356. pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  90357. pKeyMerge->nField = (u16)nOrderBy;
  90358. pKeyMerge->enc = ENC(db);
  90359. for(i=0; i<nOrderBy; i++){
  90360. CollSeq *pColl;
  90361. Expr *pTerm = pOrderBy->a[i].pExpr;
  90362. if( pTerm->flags & EP_Collate ){
  90363. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  90364. }else{
  90365. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  90366. if( pColl==0 ) pColl = db->pDfltColl;
  90367. pOrderBy->a[i].pExpr =
  90368. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  90369. }
  90370. pKeyMerge->aColl[i] = pColl;
  90371. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  90372. }
  90373. }
  90374. }else{
  90375. pKeyMerge = 0;
  90376. }
  90377. /* Reattach the ORDER BY clause to the query.
  90378. */
  90379. p->pOrderBy = pOrderBy;
  90380. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  90381. /* Allocate a range of temporary registers and the KeyInfo needed
  90382. ** for the logic that removes duplicate result rows when the
  90383. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  90384. */
  90385. if( op==TK_ALL ){
  90386. regPrev = 0;
  90387. }else{
  90388. int nExpr = p->pEList->nExpr;
  90389. assert( nOrderBy>=nExpr || db->mallocFailed );
  90390. regPrev = sqlite3GetTempRange(pParse, nExpr+1);
  90391. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  90392. pKeyDup = sqlite3DbMallocZero(db,
  90393. sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  90394. if( pKeyDup ){
  90395. pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  90396. pKeyDup->nField = (u16)nExpr;
  90397. pKeyDup->enc = ENC(db);
  90398. for(i=0; i<nExpr; i++){
  90399. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  90400. pKeyDup->aSortOrder[i] = 0;
  90401. }
  90402. }
  90403. }
  90404. /* Separate the left and the right query from one another
  90405. */
  90406. p->pPrior = 0;
  90407. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  90408. if( pPrior->pPrior==0 ){
  90409. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  90410. }
  90411. /* Compute the limit registers */
  90412. computeLimitRegisters(pParse, p, labelEnd);
  90413. if( p->iLimit && op==TK_ALL ){
  90414. regLimitA = ++pParse->nMem;
  90415. regLimitB = ++pParse->nMem;
  90416. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  90417. regLimitA);
  90418. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  90419. }else{
  90420. regLimitA = regLimitB = 0;
  90421. }
  90422. sqlite3ExprDelete(db, p->pLimit);
  90423. p->pLimit = 0;
  90424. sqlite3ExprDelete(db, p->pOffset);
  90425. p->pOffset = 0;
  90426. regAddrA = ++pParse->nMem;
  90427. regEofA = ++pParse->nMem;
  90428. regAddrB = ++pParse->nMem;
  90429. regEofB = ++pParse->nMem;
  90430. regOutA = ++pParse->nMem;
  90431. regOutB = ++pParse->nMem;
  90432. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  90433. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  90434. /* Jump past the various subroutines and coroutines to the main
  90435. ** merge loop
  90436. */
  90437. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  90438. addrSelectA = sqlite3VdbeCurrentAddr(v);
  90439. /* Generate a coroutine to evaluate the SELECT statement to the
  90440. ** left of the compound operator - the "A" select.
  90441. */
  90442. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  90443. pPrior->iLimit = regLimitA;
  90444. explainSetInteger(iSub1, pParse->iNextSelectId);
  90445. sqlite3Select(pParse, pPrior, &destA);
  90446. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  90447. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  90448. VdbeNoopComment((v, "End coroutine for left SELECT"));
  90449. /* Generate a coroutine to evaluate the SELECT statement on
  90450. ** the right - the "B" select
  90451. */
  90452. addrSelectB = sqlite3VdbeCurrentAddr(v);
  90453. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  90454. savedLimit = p->iLimit;
  90455. savedOffset = p->iOffset;
  90456. p->iLimit = regLimitB;
  90457. p->iOffset = 0;
  90458. explainSetInteger(iSub2, pParse->iNextSelectId);
  90459. sqlite3Select(pParse, p, &destB);
  90460. p->iLimit = savedLimit;
  90461. p->iOffset = savedOffset;
  90462. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  90463. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  90464. VdbeNoopComment((v, "End coroutine for right SELECT"));
  90465. /* Generate a subroutine that outputs the current row of the A
  90466. ** select as the next output row of the compound select.
  90467. */
  90468. VdbeNoopComment((v, "Output routine for A"));
  90469. addrOutA = generateOutputSubroutine(pParse,
  90470. p, &destA, pDest, regOutA,
  90471. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  90472. /* Generate a subroutine that outputs the current row of the B
  90473. ** select as the next output row of the compound select.
  90474. */
  90475. if( op==TK_ALL || op==TK_UNION ){
  90476. VdbeNoopComment((v, "Output routine for B"));
  90477. addrOutB = generateOutputSubroutine(pParse,
  90478. p, &destB, pDest, regOutB,
  90479. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  90480. }
  90481. /* Generate a subroutine to run when the results from select A
  90482. ** are exhausted and only data in select B remains.
  90483. */
  90484. VdbeNoopComment((v, "eof-A subroutine"));
  90485. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  90486. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  90487. }else{
  90488. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  90489. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  90490. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  90491. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  90492. p->nSelectRow += pPrior->nSelectRow;
  90493. }
  90494. /* Generate a subroutine to run when the results from select B
  90495. ** are exhausted and only data in select A remains.
  90496. */
  90497. if( op==TK_INTERSECT ){
  90498. addrEofB = addrEofA;
  90499. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  90500. }else{
  90501. VdbeNoopComment((v, "eof-B subroutine"));
  90502. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  90503. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  90504. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  90505. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  90506. }
  90507. /* Generate code to handle the case of A<B
  90508. */
  90509. VdbeNoopComment((v, "A-lt-B subroutine"));
  90510. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  90511. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  90512. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  90513. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  90514. /* Generate code to handle the case of A==B
  90515. */
  90516. if( op==TK_ALL ){
  90517. addrAeqB = addrAltB;
  90518. }else if( op==TK_INTERSECT ){
  90519. addrAeqB = addrAltB;
  90520. addrAltB++;
  90521. }else{
  90522. VdbeNoopComment((v, "A-eq-B subroutine"));
  90523. addrAeqB =
  90524. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  90525. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  90526. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  90527. }
  90528. /* Generate code to handle the case of A>B
  90529. */
  90530. VdbeNoopComment((v, "A-gt-B subroutine"));
  90531. addrAgtB = sqlite3VdbeCurrentAddr(v);
  90532. if( op==TK_ALL || op==TK_UNION ){
  90533. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  90534. }
  90535. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  90536. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  90537. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  90538. /* This code runs once to initialize everything.
  90539. */
  90540. sqlite3VdbeJumpHere(v, j1);
  90541. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  90542. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  90543. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  90544. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  90545. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  90546. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  90547. /* Implement the main merge loop
  90548. */
  90549. sqlite3VdbeResolveLabel(v, labelCmpr);
  90550. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  90551. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  90552. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  90553. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  90554. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  90555. /* Release temporary registers
  90556. */
  90557. if( regPrev ){
  90558. sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  90559. }
  90560. /* Jump to the this point in order to terminate the query.
  90561. */
  90562. sqlite3VdbeResolveLabel(v, labelEnd);
  90563. /* Set the number of output columns
  90564. */
  90565. if( pDest->eDest==SRT_Output ){
  90566. Select *pFirst = pPrior;
  90567. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  90568. generateColumnNames(pParse, 0, pFirst->pEList);
  90569. }
  90570. /* Reassembly the compound query so that it will be freed correctly
  90571. ** by the calling function */
  90572. if( p->pPrior ){
  90573. sqlite3SelectDelete(db, p->pPrior);
  90574. }
  90575. p->pPrior = pPrior;
  90576. /*** TBD: Insert subroutine calls to close cursors on incomplete
  90577. **** subqueries ****/
  90578. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  90579. return SQLITE_OK;
  90580. }
  90581. #endif
  90582. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  90583. /* Forward Declarations */
  90584. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  90585. static void substSelect(sqlite3*, Select *, int, ExprList *);
  90586. /*
  90587. ** Scan through the expression pExpr. Replace every reference to
  90588. ** a column in table number iTable with a copy of the iColumn-th
  90589. ** entry in pEList. (But leave references to the ROWID column
  90590. ** unchanged.)
  90591. **
  90592. ** This routine is part of the flattening procedure. A subquery
  90593. ** whose result set is defined by pEList appears as entry in the
  90594. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  90595. ** FORM clause entry is iTable. This routine make the necessary
  90596. ** changes to pExpr so that it refers directly to the source table
  90597. ** of the subquery rather the result set of the subquery.
  90598. */
  90599. static Expr *substExpr(
  90600. sqlite3 *db, /* Report malloc errors to this connection */
  90601. Expr *pExpr, /* Expr in which substitution occurs */
  90602. int iTable, /* Table to be substituted */
  90603. ExprList *pEList /* Substitute expressions */
  90604. ){
  90605. if( pExpr==0 ) return 0;
  90606. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  90607. if( pExpr->iColumn<0 ){
  90608. pExpr->op = TK_NULL;
  90609. }else{
  90610. Expr *pNew;
  90611. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  90612. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  90613. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  90614. sqlite3ExprDelete(db, pExpr);
  90615. pExpr = pNew;
  90616. }
  90617. }else{
  90618. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  90619. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  90620. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90621. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  90622. }else{
  90623. substExprList(db, pExpr->x.pList, iTable, pEList);
  90624. }
  90625. }
  90626. return pExpr;
  90627. }
  90628. static void substExprList(
  90629. sqlite3 *db, /* Report malloc errors here */
  90630. ExprList *pList, /* List to scan and in which to make substitutes */
  90631. int iTable, /* Table to be substituted */
  90632. ExprList *pEList /* Substitute values */
  90633. ){
  90634. int i;
  90635. if( pList==0 ) return;
  90636. for(i=0; i<pList->nExpr; i++){
  90637. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  90638. }
  90639. }
  90640. static void substSelect(
  90641. sqlite3 *db, /* Report malloc errors here */
  90642. Select *p, /* SELECT statement in which to make substitutions */
  90643. int iTable, /* Table to be replaced */
  90644. ExprList *pEList /* Substitute values */
  90645. ){
  90646. SrcList *pSrc;
  90647. struct SrcList_item *pItem;
  90648. int i;
  90649. if( !p ) return;
  90650. substExprList(db, p->pEList, iTable, pEList);
  90651. substExprList(db, p->pGroupBy, iTable, pEList);
  90652. substExprList(db, p->pOrderBy, iTable, pEList);
  90653. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  90654. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  90655. substSelect(db, p->pPrior, iTable, pEList);
  90656. pSrc = p->pSrc;
  90657. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  90658. if( ALWAYS(pSrc) ){
  90659. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  90660. substSelect(db, pItem->pSelect, iTable, pEList);
  90661. }
  90662. }
  90663. }
  90664. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  90665. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  90666. /*
  90667. ** This routine attempts to flatten subqueries as a performance optimization.
  90668. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  90669. **
  90670. ** To understand the concept of flattening, consider the following
  90671. ** query:
  90672. **
  90673. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  90674. **
  90675. ** The default way of implementing this query is to execute the
  90676. ** subquery first and store the results in a temporary table, then
  90677. ** run the outer query on that temporary table. This requires two
  90678. ** passes over the data. Furthermore, because the temporary table
  90679. ** has no indices, the WHERE clause on the outer query cannot be
  90680. ** optimized.
  90681. **
  90682. ** This routine attempts to rewrite queries such as the above into
  90683. ** a single flat select, like this:
  90684. **
  90685. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  90686. **
  90687. ** The code generated for this simpification gives the same result
  90688. ** but only has to scan the data once. And because indices might
  90689. ** exist on the table t1, a complete scan of the data might be
  90690. ** avoided.
  90691. **
  90692. ** Flattening is only attempted if all of the following are true:
  90693. **
  90694. ** (1) The subquery and the outer query do not both use aggregates.
  90695. **
  90696. ** (2) The subquery is not an aggregate or the outer query is not a join.
  90697. **
  90698. ** (3) The subquery is not the right operand of a left outer join
  90699. ** (Originally ticket #306. Strengthened by ticket #3300)
  90700. **
  90701. ** (4) The subquery is not DISTINCT.
  90702. **
  90703. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  90704. ** sub-queries that were excluded from this optimization. Restriction
  90705. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  90706. **
  90707. ** (6) The subquery does not use aggregates or the outer query is not
  90708. ** DISTINCT.
  90709. **
  90710. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  90711. ** A FROM clause, consider adding a FROM close with the special
  90712. ** table sqlite_once that consists of a single row containing a
  90713. ** single NULL.
  90714. **
  90715. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  90716. **
  90717. ** (9) The subquery does not use LIMIT or the outer query does not use
  90718. ** aggregates.
  90719. **
  90720. ** (10) The subquery does not use aggregates or the outer query does not
  90721. ** use LIMIT.
  90722. **
  90723. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  90724. **
  90725. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  90726. ** a separate restriction deriving from ticket #350.
  90727. **
  90728. ** (13) The subquery and outer query do not both use LIMIT.
  90729. **
  90730. ** (14) The subquery does not use OFFSET.
  90731. **
  90732. ** (15) The outer query is not part of a compound select or the
  90733. ** subquery does not have a LIMIT clause.
  90734. ** (See ticket #2339 and ticket [02a8e81d44]).
  90735. **
  90736. ** (16) The outer query is not an aggregate or the subquery does
  90737. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  90738. ** until we introduced the group_concat() function.
  90739. **
  90740. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  90741. ** compound clause made up entirely of non-aggregate queries, and
  90742. ** the parent query:
  90743. **
  90744. ** * is not itself part of a compound select,
  90745. ** * is not an aggregate or DISTINCT query, and
  90746. ** * is not a join
  90747. **
  90748. ** The parent and sub-query may contain WHERE clauses. Subject to
  90749. ** rules (11), (13) and (14), they may also contain ORDER BY,
  90750. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  90751. ** operator other than UNION ALL because all the other compound
  90752. ** operators have an implied DISTINCT which is disallowed by
  90753. ** restriction (4).
  90754. **
  90755. ** Also, each component of the sub-query must return the same number
  90756. ** of result columns. This is actually a requirement for any compound
  90757. ** SELECT statement, but all the code here does is make sure that no
  90758. ** such (illegal) sub-query is flattened. The caller will detect the
  90759. ** syntax error and return a detailed message.
  90760. **
  90761. ** (18) If the sub-query is a compound select, then all terms of the
  90762. ** ORDER by clause of the parent must be simple references to
  90763. ** columns of the sub-query.
  90764. **
  90765. ** (19) The subquery does not use LIMIT or the outer query does not
  90766. ** have a WHERE clause.
  90767. **
  90768. ** (20) If the sub-query is a compound select, then it must not use
  90769. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  90770. ** somewhat by saying that the terms of the ORDER BY clause must
  90771. ** appear as unmodified result columns in the outer query. But we
  90772. ** have other optimizations in mind to deal with that case.
  90773. **
  90774. ** (21) The subquery does not use LIMIT or the outer query is not
  90775. ** DISTINCT. (See ticket [752e1646fc]).
  90776. **
  90777. ** In this routine, the "p" parameter is a pointer to the outer query.
  90778. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  90779. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  90780. **
  90781. ** If flattening is not attempted, this routine is a no-op and returns 0.
  90782. ** If flattening is attempted this routine returns 1.
  90783. **
  90784. ** All of the expression analysis must occur on both the outer query and
  90785. ** the subquery before this routine runs.
  90786. */
  90787. static int flattenSubquery(
  90788. Parse *pParse, /* Parsing context */
  90789. Select *p, /* The parent or outer SELECT statement */
  90790. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  90791. int isAgg, /* True if outer SELECT uses aggregate functions */
  90792. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  90793. ){
  90794. const char *zSavedAuthContext = pParse->zAuthContext;
  90795. Select *pParent;
  90796. Select *pSub; /* The inner query or "subquery" */
  90797. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  90798. SrcList *pSrc; /* The FROM clause of the outer query */
  90799. SrcList *pSubSrc; /* The FROM clause of the subquery */
  90800. ExprList *pList; /* The result set of the outer query */
  90801. int iParent; /* VDBE cursor number of the pSub result set temp table */
  90802. int i; /* Loop counter */
  90803. Expr *pWhere; /* The WHERE clause */
  90804. struct SrcList_item *pSubitem; /* The subquery */
  90805. sqlite3 *db = pParse->db;
  90806. /* Check to see if flattening is permitted. Return 0 if not.
  90807. */
  90808. assert( p!=0 );
  90809. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  90810. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  90811. pSrc = p->pSrc;
  90812. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  90813. pSubitem = &pSrc->a[iFrom];
  90814. iParent = pSubitem->iCursor;
  90815. pSub = pSubitem->pSelect;
  90816. assert( pSub!=0 );
  90817. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  90818. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  90819. pSubSrc = pSub->pSrc;
  90820. assert( pSubSrc );
  90821. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  90822. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  90823. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  90824. ** became arbitrary expressions, we were forced to add restrictions (13)
  90825. ** and (14). */
  90826. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  90827. if( pSub->pOffset ) return 0; /* Restriction (14) */
  90828. if( p->pRightmost && pSub->pLimit ){
  90829. return 0; /* Restriction (15) */
  90830. }
  90831. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  90832. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  90833. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  90834. return 0; /* Restrictions (8)(9) */
  90835. }
  90836. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  90837. return 0; /* Restriction (6) */
  90838. }
  90839. if( p->pOrderBy && pSub->pOrderBy ){
  90840. return 0; /* Restriction (11) */
  90841. }
  90842. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  90843. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  90844. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  90845. return 0; /* Restriction (21) */
  90846. }
  90847. /* OBSOLETE COMMENT 1:
  90848. ** Restriction 3: If the subquery is a join, make sure the subquery is
  90849. ** not used as the right operand of an outer join. Examples of why this
  90850. ** is not allowed:
  90851. **
  90852. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  90853. **
  90854. ** If we flatten the above, we would get
  90855. **
  90856. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  90857. **
  90858. ** which is not at all the same thing.
  90859. **
  90860. ** OBSOLETE COMMENT 2:
  90861. ** Restriction 12: If the subquery is the right operand of a left outer
  90862. ** join, make sure the subquery has no WHERE clause.
  90863. ** An examples of why this is not allowed:
  90864. **
  90865. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  90866. **
  90867. ** If we flatten the above, we would get
  90868. **
  90869. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  90870. **
  90871. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  90872. ** effectively converts the OUTER JOIN into an INNER JOIN.
  90873. **
  90874. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  90875. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  90876. ** is fraught with danger. Best to avoid the whole thing. If the
  90877. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  90878. */
  90879. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  90880. return 0;
  90881. }
  90882. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  90883. ** use only the UNION ALL operator. And none of the simple select queries
  90884. ** that make up the compound SELECT are allowed to be aggregate or distinct
  90885. ** queries.
  90886. */
  90887. if( pSub->pPrior ){
  90888. if( pSub->pOrderBy ){
  90889. return 0; /* Restriction 20 */
  90890. }
  90891. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  90892. return 0;
  90893. }
  90894. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  90895. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  90896. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  90897. assert( pSub->pSrc!=0 );
  90898. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  90899. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  90900. || pSub1->pSrc->nSrc<1
  90901. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  90902. ){
  90903. return 0;
  90904. }
  90905. testcase( pSub1->pSrc->nSrc>1 );
  90906. }
  90907. /* Restriction 18. */
  90908. if( p->pOrderBy ){
  90909. int ii;
  90910. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  90911. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  90912. }
  90913. }
  90914. }
  90915. /***** If we reach this point, flattening is permitted. *****/
  90916. /* Authorize the subquery */
  90917. pParse->zAuthContext = pSubitem->zName;
  90918. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  90919. testcase( i==SQLITE_DENY );
  90920. pParse->zAuthContext = zSavedAuthContext;
  90921. /* If the sub-query is a compound SELECT statement, then (by restrictions
  90922. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  90923. ** be of the form:
  90924. **
  90925. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  90926. **
  90927. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  90928. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  90929. ** OFFSET clauses and joins them to the left-hand-side of the original
  90930. ** using UNION ALL operators. In this case N is the number of simple
  90931. ** select statements in the compound sub-query.
  90932. **
  90933. ** Example:
  90934. **
  90935. ** SELECT a+1 FROM (
  90936. ** SELECT x FROM tab
  90937. ** UNION ALL
  90938. ** SELECT y FROM tab
  90939. ** UNION ALL
  90940. ** SELECT abs(z*2) FROM tab2
  90941. ** ) WHERE a!=5 ORDER BY 1
  90942. **
  90943. ** Transformed into:
  90944. **
  90945. ** SELECT x+1 FROM tab WHERE x+1!=5
  90946. ** UNION ALL
  90947. ** SELECT y+1 FROM tab WHERE y+1!=5
  90948. ** UNION ALL
  90949. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  90950. ** ORDER BY 1
  90951. **
  90952. ** We call this the "compound-subquery flattening".
  90953. */
  90954. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  90955. Select *pNew;
  90956. ExprList *pOrderBy = p->pOrderBy;
  90957. Expr *pLimit = p->pLimit;
  90958. Select *pPrior = p->pPrior;
  90959. p->pOrderBy = 0;
  90960. p->pSrc = 0;
  90961. p->pPrior = 0;
  90962. p->pLimit = 0;
  90963. pNew = sqlite3SelectDup(db, p, 0);
  90964. p->pLimit = pLimit;
  90965. p->pOrderBy = pOrderBy;
  90966. p->pSrc = pSrc;
  90967. p->op = TK_ALL;
  90968. p->pRightmost = 0;
  90969. if( pNew==0 ){
  90970. pNew = pPrior;
  90971. }else{
  90972. pNew->pPrior = pPrior;
  90973. pNew->pRightmost = 0;
  90974. }
  90975. p->pPrior = pNew;
  90976. if( db->mallocFailed ) return 1;
  90977. }
  90978. /* Begin flattening the iFrom-th entry of the FROM clause
  90979. ** in the outer query.
  90980. */
  90981. pSub = pSub1 = pSubitem->pSelect;
  90982. /* Delete the transient table structure associated with the
  90983. ** subquery
  90984. */
  90985. sqlite3DbFree(db, pSubitem->zDatabase);
  90986. sqlite3DbFree(db, pSubitem->zName);
  90987. sqlite3DbFree(db, pSubitem->zAlias);
  90988. pSubitem->zDatabase = 0;
  90989. pSubitem->zName = 0;
  90990. pSubitem->zAlias = 0;
  90991. pSubitem->pSelect = 0;
  90992. /* Defer deleting the Table object associated with the
  90993. ** subquery until code generation is
  90994. ** complete, since there may still exist Expr.pTab entries that
  90995. ** refer to the subquery even after flattening. Ticket #3346.
  90996. **
  90997. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  90998. */
  90999. if( ALWAYS(pSubitem->pTab!=0) ){
  91000. Table *pTabToDel = pSubitem->pTab;
  91001. if( pTabToDel->nRef==1 ){
  91002. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91003. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  91004. pToplevel->pZombieTab = pTabToDel;
  91005. }else{
  91006. pTabToDel->nRef--;
  91007. }
  91008. pSubitem->pTab = 0;
  91009. }
  91010. /* The following loop runs once for each term in a compound-subquery
  91011. ** flattening (as described above). If we are doing a different kind
  91012. ** of flattening - a flattening other than a compound-subquery flattening -
  91013. ** then this loop only runs once.
  91014. **
  91015. ** This loop moves all of the FROM elements of the subquery into the
  91016. ** the FROM clause of the outer query. Before doing this, remember
  91017. ** the cursor number for the original outer query FROM element in
  91018. ** iParent. The iParent cursor will never be used. Subsequent code
  91019. ** will scan expressions looking for iParent references and replace
  91020. ** those references with expressions that resolve to the subquery FROM
  91021. ** elements we are now copying in.
  91022. */
  91023. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  91024. int nSubSrc;
  91025. u8 jointype = 0;
  91026. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  91027. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  91028. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  91029. if( pSrc ){
  91030. assert( pParent==p ); /* First time through the loop */
  91031. jointype = pSubitem->jointype;
  91032. }else{
  91033. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  91034. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  91035. if( pSrc==0 ){
  91036. assert( db->mallocFailed );
  91037. break;
  91038. }
  91039. }
  91040. /* The subquery uses a single slot of the FROM clause of the outer
  91041. ** query. If the subquery has more than one element in its FROM clause,
  91042. ** then expand the outer query to make space for it to hold all elements
  91043. ** of the subquery.
  91044. **
  91045. ** Example:
  91046. **
  91047. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  91048. **
  91049. ** The outer query has 3 slots in its FROM clause. One slot of the
  91050. ** outer query (the middle slot) is used by the subquery. The next
  91051. ** block of code will expand the out query to 4 slots. The middle
  91052. ** slot is expanded to two slots in order to make space for the
  91053. ** two elements in the FROM clause of the subquery.
  91054. */
  91055. if( nSubSrc>1 ){
  91056. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  91057. if( db->mallocFailed ){
  91058. break;
  91059. }
  91060. }
  91061. /* Transfer the FROM clause terms from the subquery into the
  91062. ** outer query.
  91063. */
  91064. for(i=0; i<nSubSrc; i++){
  91065. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  91066. pSrc->a[i+iFrom] = pSubSrc->a[i];
  91067. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  91068. }
  91069. pSrc->a[iFrom].jointype = jointype;
  91070. /* Now begin substituting subquery result set expressions for
  91071. ** references to the iParent in the outer query.
  91072. **
  91073. ** Example:
  91074. **
  91075. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  91076. ** \ \_____________ subquery __________/ /
  91077. ** \_____________________ outer query ______________________________/
  91078. **
  91079. ** We look at every expression in the outer query and every place we see
  91080. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  91081. */
  91082. pList = pParent->pEList;
  91083. for(i=0; i<pList->nExpr; i++){
  91084. if( pList->a[i].zName==0 ){
  91085. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  91086. sqlite3Dequote(zName);
  91087. pList->a[i].zName = zName;
  91088. }
  91089. }
  91090. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  91091. if( isAgg ){
  91092. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  91093. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  91094. }
  91095. if( pSub->pOrderBy ){
  91096. assert( pParent->pOrderBy==0 );
  91097. pParent->pOrderBy = pSub->pOrderBy;
  91098. pSub->pOrderBy = 0;
  91099. }else if( pParent->pOrderBy ){
  91100. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  91101. }
  91102. if( pSub->pWhere ){
  91103. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  91104. }else{
  91105. pWhere = 0;
  91106. }
  91107. if( subqueryIsAgg ){
  91108. assert( pParent->pHaving==0 );
  91109. pParent->pHaving = pParent->pWhere;
  91110. pParent->pWhere = pWhere;
  91111. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  91112. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  91113. sqlite3ExprDup(db, pSub->pHaving, 0));
  91114. assert( pParent->pGroupBy==0 );
  91115. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  91116. }else{
  91117. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  91118. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  91119. }
  91120. /* The flattened query is distinct if either the inner or the
  91121. ** outer query is distinct.
  91122. */
  91123. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  91124. /*
  91125. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  91126. **
  91127. ** One is tempted to try to add a and b to combine the limits. But this
  91128. ** does not work if either limit is negative.
  91129. */
  91130. if( pSub->pLimit ){
  91131. pParent->pLimit = pSub->pLimit;
  91132. pSub->pLimit = 0;
  91133. }
  91134. }
  91135. /* Finially, delete what is left of the subquery and return
  91136. ** success.
  91137. */
  91138. sqlite3SelectDelete(db, pSub1);
  91139. return 1;
  91140. }
  91141. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  91142. /*
  91143. ** Analyze the SELECT statement passed as an argument to see if it
  91144. ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
  91145. ** it is, or 0 otherwise. At present, a query is considered to be
  91146. ** a min()/max() query if:
  91147. **
  91148. ** 1. There is a single object in the FROM clause.
  91149. **
  91150. ** 2. There is a single expression in the result set, and it is
  91151. ** either min(x) or max(x), where x is a column reference.
  91152. */
  91153. static u8 minMaxQuery(Select *p){
  91154. Expr *pExpr;
  91155. ExprList *pEList = p->pEList;
  91156. if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  91157. pExpr = pEList->a[0].pExpr;
  91158. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  91159. if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
  91160. pEList = pExpr->x.pList;
  91161. if( pEList==0 || pEList->nExpr!=1 ) return 0;
  91162. if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  91163. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91164. if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
  91165. return WHERE_ORDERBY_MIN;
  91166. }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
  91167. return WHERE_ORDERBY_MAX;
  91168. }
  91169. return WHERE_ORDERBY_NORMAL;
  91170. }
  91171. /*
  91172. ** The select statement passed as the first argument is an aggregate query.
  91173. ** The second argment is the associated aggregate-info object. This
  91174. ** function tests if the SELECT is of the form:
  91175. **
  91176. ** SELECT count(*) FROM <tbl>
  91177. **
  91178. ** where table is a database table, not a sub-select or view. If the query
  91179. ** does match this pattern, then a pointer to the Table object representing
  91180. ** <tbl> is returned. Otherwise, 0 is returned.
  91181. */
  91182. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  91183. Table *pTab;
  91184. Expr *pExpr;
  91185. assert( !p->pGroupBy );
  91186. if( p->pWhere || p->pEList->nExpr!=1
  91187. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  91188. ){
  91189. return 0;
  91190. }
  91191. pTab = p->pSrc->a[0].pTab;
  91192. pExpr = p->pEList->a[0].pExpr;
  91193. assert( pTab && !pTab->pSelect && pExpr );
  91194. if( IsVirtual(pTab) ) return 0;
  91195. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  91196. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  91197. if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
  91198. if( pExpr->flags&EP_Distinct ) return 0;
  91199. return pTab;
  91200. }
  91201. /*
  91202. ** If the source-list item passed as an argument was augmented with an
  91203. ** INDEXED BY clause, then try to locate the specified index. If there
  91204. ** was such a clause and the named index cannot be found, return
  91205. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  91206. ** pFrom->pIndex and return SQLITE_OK.
  91207. */
  91208. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  91209. if( pFrom->pTab && pFrom->zIndex ){
  91210. Table *pTab = pFrom->pTab;
  91211. char *zIndex = pFrom->zIndex;
  91212. Index *pIdx;
  91213. for(pIdx=pTab->pIndex;
  91214. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  91215. pIdx=pIdx->pNext
  91216. );
  91217. if( !pIdx ){
  91218. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  91219. pParse->checkSchema = 1;
  91220. return SQLITE_ERROR;
  91221. }
  91222. pFrom->pIndex = pIdx;
  91223. }
  91224. return SQLITE_OK;
  91225. }
  91226. /*
  91227. ** This routine is a Walker callback for "expanding" a SELECT statement.
  91228. ** "Expanding" means to do the following:
  91229. **
  91230. ** (1) Make sure VDBE cursor numbers have been assigned to every
  91231. ** element of the FROM clause.
  91232. **
  91233. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  91234. ** defines FROM clause. When views appear in the FROM clause,
  91235. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  91236. ** that implements the view. A copy is made of the view's SELECT
  91237. ** statement so that we can freely modify or delete that statement
  91238. ** without worrying about messing up the presistent representation
  91239. ** of the view.
  91240. **
  91241. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  91242. ** on joins and the ON and USING clause of joins.
  91243. **
  91244. ** (4) Scan the list of columns in the result set (pEList) looking
  91245. ** for instances of the "*" operator or the TABLE.* operator.
  91246. ** If found, expand each "*" to be every column in every table
  91247. ** and TABLE.* to be every column in TABLE.
  91248. **
  91249. */
  91250. static int selectExpander(Walker *pWalker, Select *p){
  91251. Parse *pParse = pWalker->pParse;
  91252. int i, j, k;
  91253. SrcList *pTabList;
  91254. ExprList *pEList;
  91255. struct SrcList_item *pFrom;
  91256. sqlite3 *db = pParse->db;
  91257. if( db->mallocFailed ){
  91258. return WRC_Abort;
  91259. }
  91260. if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
  91261. return WRC_Prune;
  91262. }
  91263. p->selFlags |= SF_Expanded;
  91264. pTabList = p->pSrc;
  91265. pEList = p->pEList;
  91266. /* Make sure cursor numbers have been assigned to all entries in
  91267. ** the FROM clause of the SELECT statement.
  91268. */
  91269. sqlite3SrcListAssignCursors(pParse, pTabList);
  91270. /* Look up every table named in the FROM clause of the select. If
  91271. ** an entry of the FROM clause is a subquery instead of a table or view,
  91272. ** then create a transient table structure to describe the subquery.
  91273. */
  91274. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  91275. Table *pTab;
  91276. if( pFrom->pTab!=0 ){
  91277. /* This statement has already been prepared. There is no need
  91278. ** to go further. */
  91279. assert( i==0 );
  91280. return WRC_Prune;
  91281. }
  91282. if( pFrom->zName==0 ){
  91283. #ifndef SQLITE_OMIT_SUBQUERY
  91284. Select *pSel = pFrom->pSelect;
  91285. /* A sub-query in the FROM clause of a SELECT */
  91286. assert( pSel!=0 );
  91287. assert( pFrom->pTab==0 );
  91288. sqlite3WalkSelect(pWalker, pSel);
  91289. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  91290. if( pTab==0 ) return WRC_Abort;
  91291. pTab->nRef = 1;
  91292. pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  91293. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  91294. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  91295. pTab->iPKey = -1;
  91296. pTab->nRowEst = 1000000;
  91297. pTab->tabFlags |= TF_Ephemeral;
  91298. #endif
  91299. }else{
  91300. /* An ordinary table or view name in the FROM clause */
  91301. assert( pFrom->pTab==0 );
  91302. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  91303. if( pTab==0 ) return WRC_Abort;
  91304. pTab->nRef++;
  91305. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  91306. if( pTab->pSelect || IsVirtual(pTab) ){
  91307. /* We reach here if the named table is a really a view */
  91308. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  91309. assert( pFrom->pSelect==0 );
  91310. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  91311. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  91312. }
  91313. #endif
  91314. }
  91315. /* Locate the index named by the INDEXED BY clause, if any. */
  91316. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  91317. return WRC_Abort;
  91318. }
  91319. }
  91320. /* Process NATURAL keywords, and ON and USING clauses of joins.
  91321. */
  91322. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  91323. return WRC_Abort;
  91324. }
  91325. /* For every "*" that occurs in the column list, insert the names of
  91326. ** all columns in all tables. And for every TABLE.* insert the names
  91327. ** of all columns in TABLE. The parser inserted a special expression
  91328. ** with the TK_ALL operator for each "*" that it found in the column list.
  91329. ** The following code just has to locate the TK_ALL expressions and expand
  91330. ** each one to the list of all columns in all tables.
  91331. **
  91332. ** The first loop just checks to see if there are any "*" operators
  91333. ** that need expanding.
  91334. */
  91335. for(k=0; k<pEList->nExpr; k++){
  91336. Expr *pE = pEList->a[k].pExpr;
  91337. if( pE->op==TK_ALL ) break;
  91338. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  91339. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  91340. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  91341. }
  91342. if( k<pEList->nExpr ){
  91343. /*
  91344. ** If we get here it means the result set contains one or more "*"
  91345. ** operators that need to be expanded. Loop through each expression
  91346. ** in the result set and expand them one by one.
  91347. */
  91348. struct ExprList_item *a = pEList->a;
  91349. ExprList *pNew = 0;
  91350. int flags = pParse->db->flags;
  91351. int longNames = (flags & SQLITE_FullColNames)!=0
  91352. && (flags & SQLITE_ShortColNames)==0;
  91353. for(k=0; k<pEList->nExpr; k++){
  91354. Expr *pE = a[k].pExpr;
  91355. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  91356. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
  91357. /* This particular expression does not need to be expanded.
  91358. */
  91359. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  91360. if( pNew ){
  91361. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  91362. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  91363. a[k].zName = 0;
  91364. a[k].zSpan = 0;
  91365. }
  91366. a[k].pExpr = 0;
  91367. }else{
  91368. /* This expression is a "*" or a "TABLE.*" and needs to be
  91369. ** expanded. */
  91370. int tableSeen = 0; /* Set to 1 when TABLE matches */
  91371. char *zTName; /* text of name of TABLE */
  91372. if( pE->op==TK_DOT ){
  91373. assert( pE->pLeft!=0 );
  91374. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  91375. zTName = pE->pLeft->u.zToken;
  91376. }else{
  91377. zTName = 0;
  91378. }
  91379. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  91380. Table *pTab = pFrom->pTab;
  91381. char *zTabName = pFrom->zAlias;
  91382. if( zTabName==0 ){
  91383. zTabName = pTab->zName;
  91384. }
  91385. if( db->mallocFailed ) break;
  91386. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  91387. continue;
  91388. }
  91389. tableSeen = 1;
  91390. for(j=0; j<pTab->nCol; j++){
  91391. Expr *pExpr, *pRight;
  91392. char *zName = pTab->aCol[j].zName;
  91393. char *zColname; /* The computed column name */
  91394. char *zToFree; /* Malloced string that needs to be freed */
  91395. Token sColname; /* Computed column name as a token */
  91396. /* If a column is marked as 'hidden' (currently only possible
  91397. ** for virtual tables), do not include it in the expanded
  91398. ** result-set list.
  91399. */
  91400. if( IsHiddenColumn(&pTab->aCol[j]) ){
  91401. assert(IsVirtual(pTab));
  91402. continue;
  91403. }
  91404. if( i>0 && zTName==0 ){
  91405. if( (pFrom->jointype & JT_NATURAL)!=0
  91406. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  91407. ){
  91408. /* In a NATURAL join, omit the join columns from the
  91409. ** table to the right of the join */
  91410. continue;
  91411. }
  91412. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  91413. /* In a join with a USING clause, omit columns in the
  91414. ** using clause from the table on the right. */
  91415. continue;
  91416. }
  91417. }
  91418. pRight = sqlite3Expr(db, TK_ID, zName);
  91419. zColname = zName;
  91420. zToFree = 0;
  91421. if( longNames || pTabList->nSrc>1 ){
  91422. Expr *pLeft;
  91423. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  91424. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  91425. if( longNames ){
  91426. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  91427. zToFree = zColname;
  91428. }
  91429. }else{
  91430. pExpr = pRight;
  91431. }
  91432. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  91433. sColname.z = zColname;
  91434. sColname.n = sqlite3Strlen30(zColname);
  91435. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  91436. sqlite3DbFree(db, zToFree);
  91437. }
  91438. }
  91439. if( !tableSeen ){
  91440. if( zTName ){
  91441. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  91442. }else{
  91443. sqlite3ErrorMsg(pParse, "no tables specified");
  91444. }
  91445. }
  91446. }
  91447. }
  91448. sqlite3ExprListDelete(db, pEList);
  91449. p->pEList = pNew;
  91450. }
  91451. #if SQLITE_MAX_COLUMN
  91452. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  91453. sqlite3ErrorMsg(pParse, "too many columns in result set");
  91454. }
  91455. #endif
  91456. return WRC_Continue;
  91457. }
  91458. /*
  91459. ** No-op routine for the parse-tree walker.
  91460. **
  91461. ** When this routine is the Walker.xExprCallback then expression trees
  91462. ** are walked without any actions being taken at each node. Presumably,
  91463. ** when this routine is used for Walker.xExprCallback then
  91464. ** Walker.xSelectCallback is set to do something useful for every
  91465. ** subquery in the parser tree.
  91466. */
  91467. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  91468. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91469. return WRC_Continue;
  91470. }
  91471. /*
  91472. ** This routine "expands" a SELECT statement and all of its subqueries.
  91473. ** For additional information on what it means to "expand" a SELECT
  91474. ** statement, see the comment on the selectExpand worker callback above.
  91475. **
  91476. ** Expanding a SELECT statement is the first step in processing a
  91477. ** SELECT statement. The SELECT statement must be expanded before
  91478. ** name resolution is performed.
  91479. **
  91480. ** If anything goes wrong, an error message is written into pParse.
  91481. ** The calling function can detect the problem by looking at pParse->nErr
  91482. ** and/or pParse->db->mallocFailed.
  91483. */
  91484. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  91485. Walker w;
  91486. w.xSelectCallback = selectExpander;
  91487. w.xExprCallback = exprWalkNoop;
  91488. w.pParse = pParse;
  91489. sqlite3WalkSelect(&w, pSelect);
  91490. }
  91491. #ifndef SQLITE_OMIT_SUBQUERY
  91492. /*
  91493. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  91494. ** interface.
  91495. **
  91496. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  91497. ** information to the Table structure that represents the result set
  91498. ** of that subquery.
  91499. **
  91500. ** The Table structure that represents the result set was constructed
  91501. ** by selectExpander() but the type and collation information was omitted
  91502. ** at that point because identifiers had not yet been resolved. This
  91503. ** routine is called after identifier resolution.
  91504. */
  91505. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  91506. Parse *pParse;
  91507. int i;
  91508. SrcList *pTabList;
  91509. struct SrcList_item *pFrom;
  91510. assert( p->selFlags & SF_Resolved );
  91511. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  91512. p->selFlags |= SF_HasTypeInfo;
  91513. pParse = pWalker->pParse;
  91514. pTabList = p->pSrc;
  91515. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  91516. Table *pTab = pFrom->pTab;
  91517. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  91518. /* A sub-query in the FROM clause of a SELECT */
  91519. Select *pSel = pFrom->pSelect;
  91520. assert( pSel );
  91521. while( pSel->pPrior ) pSel = pSel->pPrior;
  91522. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  91523. }
  91524. }
  91525. }
  91526. return WRC_Continue;
  91527. }
  91528. #endif
  91529. /*
  91530. ** This routine adds datatype and collating sequence information to
  91531. ** the Table structures of all FROM-clause subqueries in a
  91532. ** SELECT statement.
  91533. **
  91534. ** Use this routine after name resolution.
  91535. */
  91536. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  91537. #ifndef SQLITE_OMIT_SUBQUERY
  91538. Walker w;
  91539. w.xSelectCallback = selectAddSubqueryTypeInfo;
  91540. w.xExprCallback = exprWalkNoop;
  91541. w.pParse = pParse;
  91542. sqlite3WalkSelect(&w, pSelect);
  91543. #endif
  91544. }
  91545. /*
  91546. ** This routine sets up a SELECT statement for processing. The
  91547. ** following is accomplished:
  91548. **
  91549. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  91550. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  91551. ** * ON and USING clauses are shifted into WHERE statements
  91552. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  91553. ** * Identifiers in expression are matched to tables.
  91554. **
  91555. ** This routine acts recursively on all subqueries within the SELECT.
  91556. */
  91557. SQLITE_PRIVATE void sqlite3SelectPrep(
  91558. Parse *pParse, /* The parser context */
  91559. Select *p, /* The SELECT statement being coded. */
  91560. NameContext *pOuterNC /* Name context for container */
  91561. ){
  91562. sqlite3 *db;
  91563. if( NEVER(p==0) ) return;
  91564. db = pParse->db;
  91565. if( p->selFlags & SF_HasTypeInfo ) return;
  91566. sqlite3SelectExpand(pParse, p);
  91567. if( pParse->nErr || db->mallocFailed ) return;
  91568. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  91569. if( pParse->nErr || db->mallocFailed ) return;
  91570. sqlite3SelectAddTypeInfo(pParse, p);
  91571. }
  91572. /*
  91573. ** Reset the aggregate accumulator.
  91574. **
  91575. ** The aggregate accumulator is a set of memory cells that hold
  91576. ** intermediate results while calculating an aggregate. This
  91577. ** routine generates code that stores NULLs in all of those memory
  91578. ** cells.
  91579. */
  91580. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  91581. Vdbe *v = pParse->pVdbe;
  91582. int i;
  91583. struct AggInfo_func *pFunc;
  91584. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  91585. return;
  91586. }
  91587. for(i=0; i<pAggInfo->nColumn; i++){
  91588. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  91589. }
  91590. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  91591. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  91592. if( pFunc->iDistinct>=0 ){
  91593. Expr *pE = pFunc->pExpr;
  91594. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  91595. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  91596. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  91597. "argument");
  91598. pFunc->iDistinct = -1;
  91599. }else{
  91600. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  91601. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  91602. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  91603. }
  91604. }
  91605. }
  91606. }
  91607. /*
  91608. ** Invoke the OP_AggFinalize opcode for every aggregate function
  91609. ** in the AggInfo structure.
  91610. */
  91611. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  91612. Vdbe *v = pParse->pVdbe;
  91613. int i;
  91614. struct AggInfo_func *pF;
  91615. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  91616. ExprList *pList = pF->pExpr->x.pList;
  91617. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  91618. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  91619. (void*)pF->pFunc, P4_FUNCDEF);
  91620. }
  91621. }
  91622. /*
  91623. ** Update the accumulator memory cells for an aggregate based on
  91624. ** the current cursor position.
  91625. */
  91626. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  91627. Vdbe *v = pParse->pVdbe;
  91628. int i;
  91629. int regHit = 0;
  91630. int addrHitTest = 0;
  91631. struct AggInfo_func *pF;
  91632. struct AggInfo_col *pC;
  91633. pAggInfo->directMode = 1;
  91634. sqlite3ExprCacheClear(pParse);
  91635. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  91636. int nArg;
  91637. int addrNext = 0;
  91638. int regAgg;
  91639. ExprList *pList = pF->pExpr->x.pList;
  91640. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  91641. if( pList ){
  91642. nArg = pList->nExpr;
  91643. regAgg = sqlite3GetTempRange(pParse, nArg);
  91644. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  91645. }else{
  91646. nArg = 0;
  91647. regAgg = 0;
  91648. }
  91649. if( pF->iDistinct>=0 ){
  91650. addrNext = sqlite3VdbeMakeLabel(v);
  91651. assert( nArg==1 );
  91652. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  91653. }
  91654. if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  91655. CollSeq *pColl = 0;
  91656. struct ExprList_item *pItem;
  91657. int j;
  91658. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  91659. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  91660. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  91661. }
  91662. if( !pColl ){
  91663. pColl = pParse->db->pDfltColl;
  91664. }
  91665. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  91666. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  91667. }
  91668. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  91669. (void*)pF->pFunc, P4_FUNCDEF);
  91670. sqlite3VdbeChangeP5(v, (u8)nArg);
  91671. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  91672. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  91673. if( addrNext ){
  91674. sqlite3VdbeResolveLabel(v, addrNext);
  91675. sqlite3ExprCacheClear(pParse);
  91676. }
  91677. }
  91678. /* Before populating the accumulator registers, clear the column cache.
  91679. ** Otherwise, if any of the required column values are already present
  91680. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  91681. ** to pC->iMem. But by the time the value is used, the original register
  91682. ** may have been used, invalidating the underlying buffer holding the
  91683. ** text or blob value. See ticket [883034dcb5].
  91684. **
  91685. ** Another solution would be to change the OP_SCopy used to copy cached
  91686. ** values to an OP_Copy.
  91687. */
  91688. if( regHit ){
  91689. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  91690. }
  91691. sqlite3ExprCacheClear(pParse);
  91692. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  91693. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  91694. }
  91695. pAggInfo->directMode = 0;
  91696. sqlite3ExprCacheClear(pParse);
  91697. if( addrHitTest ){
  91698. sqlite3VdbeJumpHere(v, addrHitTest);
  91699. }
  91700. }
  91701. /*
  91702. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  91703. ** count(*) query ("SELECT count(*) FROM pTab").
  91704. */
  91705. #ifndef SQLITE_OMIT_EXPLAIN
  91706. static void explainSimpleCount(
  91707. Parse *pParse, /* Parse context */
  91708. Table *pTab, /* Table being queried */
  91709. Index *pIdx /* Index used to optimize scan, or NULL */
  91710. ){
  91711. if( pParse->explain==2 ){
  91712. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
  91713. pTab->zName,
  91714. pIdx ? "USING COVERING INDEX " : "",
  91715. pIdx ? pIdx->zName : "",
  91716. pTab->nRowEst
  91717. );
  91718. sqlite3VdbeAddOp4(
  91719. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  91720. );
  91721. }
  91722. }
  91723. #else
  91724. # define explainSimpleCount(a,b,c)
  91725. #endif
  91726. /*
  91727. ** Generate code for the SELECT statement given in the p argument.
  91728. **
  91729. ** The results are distributed in various ways depending on the
  91730. ** contents of the SelectDest structure pointed to by argument pDest
  91731. ** as follows:
  91732. **
  91733. ** pDest->eDest Result
  91734. ** ------------ -------------------------------------------
  91735. ** SRT_Output Generate a row of output (using the OP_ResultRow
  91736. ** opcode) for each row in the result set.
  91737. **
  91738. ** SRT_Mem Only valid if the result is a single column.
  91739. ** Store the first column of the first result row
  91740. ** in register pDest->iSDParm then abandon the rest
  91741. ** of the query. This destination implies "LIMIT 1".
  91742. **
  91743. ** SRT_Set The result must be a single column. Store each
  91744. ** row of result as the key in table pDest->iSDParm.
  91745. ** Apply the affinity pDest->affSdst before storing
  91746. ** results. Used to implement "IN (SELECT ...)".
  91747. **
  91748. ** SRT_Union Store results as a key in a temporary table
  91749. ** identified by pDest->iSDParm.
  91750. **
  91751. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  91752. **
  91753. ** SRT_Table Store results in temporary table pDest->iSDParm.
  91754. ** This is like SRT_EphemTab except that the table
  91755. ** is assumed to already be open.
  91756. **
  91757. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  91758. ** the result there. The cursor is left open after
  91759. ** returning. This is like SRT_Table except that
  91760. ** this destination uses OP_OpenEphemeral to create
  91761. ** the table first.
  91762. **
  91763. ** SRT_Coroutine Generate a co-routine that returns a new row of
  91764. ** results each time it is invoked. The entry point
  91765. ** of the co-routine is stored in register pDest->iSDParm.
  91766. **
  91767. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  91768. ** set is not empty.
  91769. **
  91770. ** SRT_Discard Throw the results away. This is used by SELECT
  91771. ** statements within triggers whose only purpose is
  91772. ** the side-effects of functions.
  91773. **
  91774. ** This routine returns the number of errors. If any errors are
  91775. ** encountered, then an appropriate error message is left in
  91776. ** pParse->zErrMsg.
  91777. **
  91778. ** This routine does NOT free the Select structure passed in. The
  91779. ** calling function needs to do that.
  91780. */
  91781. SQLITE_PRIVATE int sqlite3Select(
  91782. Parse *pParse, /* The parser context */
  91783. Select *p, /* The SELECT statement being coded. */
  91784. SelectDest *pDest /* What to do with the query results */
  91785. ){
  91786. int i, j; /* Loop counters */
  91787. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  91788. Vdbe *v; /* The virtual machine under construction */
  91789. int isAgg; /* True for select lists like "count(*)" */
  91790. ExprList *pEList; /* List of columns to extract. */
  91791. SrcList *pTabList; /* List of tables to select from */
  91792. Expr *pWhere; /* The WHERE clause. May be NULL */
  91793. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  91794. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  91795. Expr *pHaving; /* The HAVING clause. May be NULL */
  91796. int rc = 1; /* Value to return from this function */
  91797. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  91798. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  91799. AggInfo sAggInfo; /* Information used by aggregate queries */
  91800. int iEnd; /* Address of the end of the query */
  91801. sqlite3 *db; /* The database connection */
  91802. #ifndef SQLITE_OMIT_EXPLAIN
  91803. int iRestoreSelectId = pParse->iSelectId;
  91804. pParse->iSelectId = pParse->iNextSelectId++;
  91805. #endif
  91806. db = pParse->db;
  91807. if( p==0 || db->mallocFailed || pParse->nErr ){
  91808. return 1;
  91809. }
  91810. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  91811. memset(&sAggInfo, 0, sizeof(sAggInfo));
  91812. if( IgnorableOrderby(pDest) ){
  91813. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  91814. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  91815. /* If ORDER BY makes no difference in the output then neither does
  91816. ** DISTINCT so it can be removed too. */
  91817. sqlite3ExprListDelete(db, p->pOrderBy);
  91818. p->pOrderBy = 0;
  91819. p->selFlags &= ~SF_Distinct;
  91820. }
  91821. sqlite3SelectPrep(pParse, p, 0);
  91822. pOrderBy = p->pOrderBy;
  91823. pTabList = p->pSrc;
  91824. pEList = p->pEList;
  91825. if( pParse->nErr || db->mallocFailed ){
  91826. goto select_end;
  91827. }
  91828. isAgg = (p->selFlags & SF_Aggregate)!=0;
  91829. assert( pEList!=0 );
  91830. /* Begin generating code.
  91831. */
  91832. v = sqlite3GetVdbe(pParse);
  91833. if( v==0 ) goto select_end;
  91834. /* If writing to memory or generating a set
  91835. ** only a single column may be output.
  91836. */
  91837. #ifndef SQLITE_OMIT_SUBQUERY
  91838. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  91839. goto select_end;
  91840. }
  91841. #endif
  91842. /* Generate code for all sub-queries in the FROM clause
  91843. */
  91844. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  91845. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  91846. struct SrcList_item *pItem = &pTabList->a[i];
  91847. SelectDest dest;
  91848. Select *pSub = pItem->pSelect;
  91849. int isAggSub;
  91850. if( pSub==0 ) continue;
  91851. /* Sometimes the code for a subquery will be generated more than
  91852. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  91853. ** for example. In that case, do not regenerate the code to manifest
  91854. ** a view or the co-routine to implement a view. The first instance
  91855. ** is sufficient, though the subroutine to manifest the view does need
  91856. ** to be invoked again. */
  91857. if( pItem->addrFillSub ){
  91858. if( pItem->viaCoroutine==0 ){
  91859. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  91860. }
  91861. continue;
  91862. }
  91863. /* Increment Parse.nHeight by the height of the largest expression
  91864. ** tree refered to by this, the parent select. The child select
  91865. ** may contain expression trees of at most
  91866. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  91867. ** more conservative than necessary, but much easier than enforcing
  91868. ** an exact limit.
  91869. */
  91870. pParse->nHeight += sqlite3SelectExprHeight(p);
  91871. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  91872. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  91873. /* This subquery can be absorbed into its parent. */
  91874. if( isAggSub ){
  91875. isAgg = 1;
  91876. p->selFlags |= SF_Aggregate;
  91877. }
  91878. i = -1;
  91879. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  91880. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  91881. ){
  91882. /* Implement a co-routine that will return a single row of the result
  91883. ** set on each invocation.
  91884. */
  91885. int addrTop;
  91886. int addrEof;
  91887. pItem->regReturn = ++pParse->nMem;
  91888. addrEof = ++pParse->nMem;
  91889. /* Before coding the OP_Goto to jump to the start of the main routine,
  91890. ** ensure that the jump to the verify-schema routine has already
  91891. ** been coded. Otherwise, the verify-schema would likely be coded as
  91892. ** part of the co-routine. If the main routine then accessed the
  91893. ** database before invoking the co-routine for the first time (for
  91894. ** example to initialize a LIMIT register from a sub-select), it would
  91895. ** be doing so without having verified the schema version and obtained
  91896. ** the required db locks. See ticket d6b36be38. */
  91897. sqlite3CodeVerifySchema(pParse, -1);
  91898. sqlite3VdbeAddOp0(v, OP_Goto);
  91899. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  91900. sqlite3VdbeChangeP5(v, 1);
  91901. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  91902. pItem->addrFillSub = addrTop;
  91903. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  91904. sqlite3VdbeChangeP5(v, 1);
  91905. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  91906. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  91907. sqlite3Select(pParse, pSub, &dest);
  91908. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  91909. pItem->viaCoroutine = 1;
  91910. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  91911. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  91912. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  91913. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  91914. VdbeComment((v, "end %s", pItem->pTab->zName));
  91915. sqlite3VdbeJumpHere(v, addrTop-1);
  91916. sqlite3ClearTempRegCache(pParse);
  91917. }else{
  91918. /* Generate a subroutine that will fill an ephemeral table with
  91919. ** the content of this subquery. pItem->addrFillSub will point
  91920. ** to the address of the generated subroutine. pItem->regReturn
  91921. ** is a register allocated to hold the subroutine return address
  91922. */
  91923. int topAddr;
  91924. int onceAddr = 0;
  91925. int retAddr;
  91926. assert( pItem->addrFillSub==0 );
  91927. pItem->regReturn = ++pParse->nMem;
  91928. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  91929. pItem->addrFillSub = topAddr+1;
  91930. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  91931. if( pItem->isCorrelated==0 ){
  91932. /* If the subquery is no correlated and if we are not inside of
  91933. ** a trigger, then we only need to compute the value of the subquery
  91934. ** once. */
  91935. onceAddr = sqlite3CodeOnce(pParse);
  91936. }
  91937. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  91938. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  91939. sqlite3Select(pParse, pSub, &dest);
  91940. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  91941. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  91942. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  91943. VdbeComment((v, "end %s", pItem->pTab->zName));
  91944. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  91945. sqlite3ClearTempRegCache(pParse);
  91946. }
  91947. if( /*pParse->nErr ||*/ db->mallocFailed ){
  91948. goto select_end;
  91949. }
  91950. pParse->nHeight -= sqlite3SelectExprHeight(p);
  91951. pTabList = p->pSrc;
  91952. if( !IgnorableOrderby(pDest) ){
  91953. pOrderBy = p->pOrderBy;
  91954. }
  91955. }
  91956. pEList = p->pEList;
  91957. #endif
  91958. pWhere = p->pWhere;
  91959. pGroupBy = p->pGroupBy;
  91960. pHaving = p->pHaving;
  91961. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  91962. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  91963. /* If there is are a sequence of queries, do the earlier ones first.
  91964. */
  91965. if( p->pPrior ){
  91966. if( p->pRightmost==0 ){
  91967. Select *pLoop, *pRight = 0;
  91968. int cnt = 0;
  91969. int mxSelect;
  91970. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  91971. pLoop->pRightmost = p;
  91972. pLoop->pNext = pRight;
  91973. pRight = pLoop;
  91974. }
  91975. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  91976. if( mxSelect && cnt>mxSelect ){
  91977. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  91978. goto select_end;
  91979. }
  91980. }
  91981. rc = multiSelect(pParse, p, pDest);
  91982. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  91983. return rc;
  91984. }
  91985. #endif
  91986. /* If there is both a GROUP BY and an ORDER BY clause and they are
  91987. ** identical, then disable the ORDER BY clause since the GROUP BY
  91988. ** will cause elements to come out in the correct order. This is
  91989. ** an optimization - the correct answer should result regardless.
  91990. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  91991. ** to disable this optimization for testing purposes.
  91992. */
  91993. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
  91994. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  91995. pOrderBy = 0;
  91996. }
  91997. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  91998. ** if the select-list is the same as the ORDER BY list, then this query
  91999. ** can be rewritten as a GROUP BY. In other words, this:
  92000. **
  92001. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  92002. **
  92003. ** is transformed to:
  92004. **
  92005. ** SELECT xyz FROM ... GROUP BY xyz
  92006. **
  92007. ** The second form is preferred as a single index (or temp-table) may be
  92008. ** used for both the ORDER BY and DISTINCT processing. As originally
  92009. ** written the query must use a temp-table for at least one of the ORDER
  92010. ** BY and DISTINCT, and an index or separate temp-table for the other.
  92011. */
  92012. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  92013. && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
  92014. ){
  92015. p->selFlags &= ~SF_Distinct;
  92016. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  92017. pGroupBy = p->pGroupBy;
  92018. pOrderBy = 0;
  92019. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  92020. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  92021. ** original setting of the SF_Distinct flag, not the current setting */
  92022. assert( sDistinct.isTnct );
  92023. }
  92024. /* If there is an ORDER BY clause, then this sorting
  92025. ** index might end up being unused if the data can be
  92026. ** extracted in pre-sorted order. If that is the case, then the
  92027. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  92028. ** we figure out that the sorting index is not needed. The addrSortIndex
  92029. ** variable is used to facilitate that change.
  92030. */
  92031. if( pOrderBy ){
  92032. KeyInfo *pKeyInfo;
  92033. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  92034. pOrderBy->iECursor = pParse->nTab++;
  92035. p->addrOpenEphm[2] = addrSortIndex =
  92036. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  92037. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  92038. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  92039. }else{
  92040. addrSortIndex = -1;
  92041. }
  92042. /* If the output is destined for a temporary table, open that table.
  92043. */
  92044. if( pDest->eDest==SRT_EphemTab ){
  92045. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  92046. }
  92047. /* Set the limiter.
  92048. */
  92049. iEnd = sqlite3VdbeMakeLabel(v);
  92050. p->nSelectRow = (double)LARGEST_INT64;
  92051. computeLimitRegisters(pParse, p, iEnd);
  92052. if( p->iLimit==0 && addrSortIndex>=0 ){
  92053. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  92054. p->selFlags |= SF_UseSorter;
  92055. }
  92056. /* Open a virtual index to use for the distinct set.
  92057. */
  92058. if( p->selFlags & SF_Distinct ){
  92059. sDistinct.tabTnct = pParse->nTab++;
  92060. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  92061. sDistinct.tabTnct, 0, 0,
  92062. (char*)keyInfoFromExprList(pParse, p->pEList),
  92063. P4_KEYINFO_HANDOFF);
  92064. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  92065. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  92066. }else{
  92067. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  92068. }
  92069. if( !isAgg && pGroupBy==0 ){
  92070. /* No aggregate functions and no GROUP BY clause */
  92071. ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
  92072. /* Begin the database scan. */
  92073. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
  92074. if( pWInfo==0 ) goto select_end;
  92075. if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
  92076. if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
  92077. if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
  92078. /* If sorting index that was created by a prior OP_OpenEphemeral
  92079. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  92080. ** into an OP_Noop.
  92081. */
  92082. if( addrSortIndex>=0 && pOrderBy==0 ){
  92083. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  92084. p->addrOpenEphm[2] = -1;
  92085. }
  92086. /* Use the standard inner loop. */
  92087. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  92088. pWInfo->iContinue, pWInfo->iBreak);
  92089. /* End the database scan loop.
  92090. */
  92091. sqlite3WhereEnd(pWInfo);
  92092. }else{
  92093. /* This case when there exist aggregate functions or a GROUP BY clause
  92094. ** or both */
  92095. NameContext sNC; /* Name context for processing aggregate information */
  92096. int iAMem; /* First Mem address for storing current GROUP BY */
  92097. int iBMem; /* First Mem address for previous GROUP BY */
  92098. int iUseFlag; /* Mem address holding flag indicating that at least
  92099. ** one row of the input to the aggregator has been
  92100. ** processed */
  92101. int iAbortFlag; /* Mem address which causes query abort if positive */
  92102. int groupBySort; /* Rows come from source in GROUP BY order */
  92103. int addrEnd; /* End of processing for this SELECT */
  92104. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  92105. int sortOut = 0; /* Output register from the sorter */
  92106. /* Remove any and all aliases between the result set and the
  92107. ** GROUP BY clause.
  92108. */
  92109. if( pGroupBy ){
  92110. int k; /* Loop counter */
  92111. struct ExprList_item *pItem; /* For looping over expression in a list */
  92112. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  92113. pItem->iAlias = 0;
  92114. }
  92115. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  92116. pItem->iAlias = 0;
  92117. }
  92118. if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
  92119. }else{
  92120. p->nSelectRow = (double)1;
  92121. }
  92122. /* Create a label to jump to when we want to abort the query */
  92123. addrEnd = sqlite3VdbeMakeLabel(v);
  92124. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  92125. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  92126. ** SELECT statement.
  92127. */
  92128. memset(&sNC, 0, sizeof(sNC));
  92129. sNC.pParse = pParse;
  92130. sNC.pSrcList = pTabList;
  92131. sNC.pAggInfo = &sAggInfo;
  92132. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  92133. sAggInfo.pGroupBy = pGroupBy;
  92134. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  92135. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  92136. if( pHaving ){
  92137. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  92138. }
  92139. sAggInfo.nAccumulator = sAggInfo.nColumn;
  92140. for(i=0; i<sAggInfo.nFunc; i++){
  92141. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  92142. sNC.ncFlags |= NC_InAggFunc;
  92143. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  92144. sNC.ncFlags &= ~NC_InAggFunc;
  92145. }
  92146. if( db->mallocFailed ) goto select_end;
  92147. /* Processing for aggregates with GROUP BY is very different and
  92148. ** much more complex than aggregates without a GROUP BY.
  92149. */
  92150. if( pGroupBy ){
  92151. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  92152. int j1; /* A-vs-B comparision jump */
  92153. int addrOutputRow; /* Start of subroutine that outputs a result row */
  92154. int regOutputRow; /* Return address register for output subroutine */
  92155. int addrSetAbort; /* Set the abort flag and return */
  92156. int addrTopOfLoop; /* Top of the input loop */
  92157. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  92158. int addrReset; /* Subroutine for resetting the accumulator */
  92159. int regReset; /* Return address register for reset subroutine */
  92160. /* If there is a GROUP BY clause we might need a sorting index to
  92161. ** implement it. Allocate that sorting index now. If it turns out
  92162. ** that we do not need it after all, the OP_SorterOpen instruction
  92163. ** will be converted into a Noop.
  92164. */
  92165. sAggInfo.sortingIdx = pParse->nTab++;
  92166. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  92167. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  92168. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  92169. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  92170. /* Initialize memory locations used by GROUP BY aggregate processing
  92171. */
  92172. iUseFlag = ++pParse->nMem;
  92173. iAbortFlag = ++pParse->nMem;
  92174. regOutputRow = ++pParse->nMem;
  92175. addrOutputRow = sqlite3VdbeMakeLabel(v);
  92176. regReset = ++pParse->nMem;
  92177. addrReset = sqlite3VdbeMakeLabel(v);
  92178. iAMem = pParse->nMem + 1;
  92179. pParse->nMem += pGroupBy->nExpr;
  92180. iBMem = pParse->nMem + 1;
  92181. pParse->nMem += pGroupBy->nExpr;
  92182. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  92183. VdbeComment((v, "clear abort flag"));
  92184. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  92185. VdbeComment((v, "indicate accumulator empty"));
  92186. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  92187. /* Begin a loop that will extract all source rows in GROUP BY order.
  92188. ** This might involve two separate loops with an OP_Sort in between, or
  92189. ** it might be a single loop that uses an index to extract information
  92190. ** in the right order to begin with.
  92191. */
  92192. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  92193. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
  92194. if( pWInfo==0 ) goto select_end;
  92195. if( pWInfo->nOBSat==pGroupBy->nExpr ){
  92196. /* The optimizer is able to deliver rows in group by order so
  92197. ** we do not have to sort. The OP_OpenEphemeral table will be
  92198. ** cancelled later because we still need to use the pKeyInfo
  92199. */
  92200. groupBySort = 0;
  92201. }else{
  92202. /* Rows are coming out in undetermined order. We have to push
  92203. ** each row into a sorting index, terminate the first loop,
  92204. ** then loop over the sorting index in order to get the output
  92205. ** in sorted order
  92206. */
  92207. int regBase;
  92208. int regRecord;
  92209. int nCol;
  92210. int nGroupBy;
  92211. explainTempTable(pParse,
  92212. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  92213. "DISTINCT" : "GROUP BY");
  92214. groupBySort = 1;
  92215. nGroupBy = pGroupBy->nExpr;
  92216. nCol = nGroupBy + 1;
  92217. j = nGroupBy+1;
  92218. for(i=0; i<sAggInfo.nColumn; i++){
  92219. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  92220. nCol++;
  92221. j++;
  92222. }
  92223. }
  92224. regBase = sqlite3GetTempRange(pParse, nCol);
  92225. sqlite3ExprCacheClear(pParse);
  92226. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  92227. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  92228. j = nGroupBy+1;
  92229. for(i=0; i<sAggInfo.nColumn; i++){
  92230. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  92231. if( pCol->iSorterColumn>=j ){
  92232. int r1 = j + regBase;
  92233. int r2;
  92234. r2 = sqlite3ExprCodeGetColumn(pParse,
  92235. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  92236. if( r1!=r2 ){
  92237. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  92238. }
  92239. j++;
  92240. }
  92241. }
  92242. regRecord = sqlite3GetTempReg(pParse);
  92243. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  92244. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  92245. sqlite3ReleaseTempReg(pParse, regRecord);
  92246. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  92247. sqlite3WhereEnd(pWInfo);
  92248. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  92249. sortOut = sqlite3GetTempReg(pParse);
  92250. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  92251. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  92252. VdbeComment((v, "GROUP BY sort"));
  92253. sAggInfo.useSortingIdx = 1;
  92254. sqlite3ExprCacheClear(pParse);
  92255. }
  92256. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  92257. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  92258. ** Then compare the current GROUP BY terms against the GROUP BY terms
  92259. ** from the previous row currently stored in a0, a1, a2...
  92260. */
  92261. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  92262. sqlite3ExprCacheClear(pParse);
  92263. if( groupBySort ){
  92264. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  92265. }
  92266. for(j=0; j<pGroupBy->nExpr; j++){
  92267. if( groupBySort ){
  92268. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  92269. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  92270. }else{
  92271. sAggInfo.directMode = 1;
  92272. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  92273. }
  92274. }
  92275. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  92276. (char*)pKeyInfo, P4_KEYINFO);
  92277. j1 = sqlite3VdbeCurrentAddr(v);
  92278. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  92279. /* Generate code that runs whenever the GROUP BY changes.
  92280. ** Changes in the GROUP BY are detected by the previous code
  92281. ** block. If there were no changes, this block is skipped.
  92282. **
  92283. ** This code copies current group by terms in b0,b1,b2,...
  92284. ** over to a0,a1,a2. It then calls the output subroutine
  92285. ** and resets the aggregate accumulator registers in preparation
  92286. ** for the next GROUP BY batch.
  92287. */
  92288. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  92289. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  92290. VdbeComment((v, "output one row"));
  92291. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  92292. VdbeComment((v, "check abort flag"));
  92293. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  92294. VdbeComment((v, "reset accumulator"));
  92295. /* Update the aggregate accumulators based on the content of
  92296. ** the current row
  92297. */
  92298. sqlite3VdbeJumpHere(v, j1);
  92299. updateAccumulator(pParse, &sAggInfo);
  92300. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  92301. VdbeComment((v, "indicate data in accumulator"));
  92302. /* End of the loop
  92303. */
  92304. if( groupBySort ){
  92305. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  92306. }else{
  92307. sqlite3WhereEnd(pWInfo);
  92308. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  92309. }
  92310. /* Output the final row of result
  92311. */
  92312. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  92313. VdbeComment((v, "output final row"));
  92314. /* Jump over the subroutines
  92315. */
  92316. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  92317. /* Generate a subroutine that outputs a single row of the result
  92318. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  92319. ** is less than or equal to zero, the subroutine is a no-op. If
  92320. ** the processing calls for the query to abort, this subroutine
  92321. ** increments the iAbortFlag memory location before returning in
  92322. ** order to signal the caller to abort.
  92323. */
  92324. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  92325. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  92326. VdbeComment((v, "set abort flag"));
  92327. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  92328. sqlite3VdbeResolveLabel(v, addrOutputRow);
  92329. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  92330. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  92331. VdbeComment((v, "Groupby result generator entry point"));
  92332. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  92333. finalizeAggFunctions(pParse, &sAggInfo);
  92334. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  92335. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  92336. &sDistinct, pDest,
  92337. addrOutputRow+1, addrSetAbort);
  92338. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  92339. VdbeComment((v, "end groupby result generator"));
  92340. /* Generate a subroutine that will reset the group-by accumulator
  92341. */
  92342. sqlite3VdbeResolveLabel(v, addrReset);
  92343. resetAccumulator(pParse, &sAggInfo);
  92344. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  92345. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  92346. else {
  92347. ExprList *pDel = 0;
  92348. #ifndef SQLITE_OMIT_BTREECOUNT
  92349. Table *pTab;
  92350. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  92351. /* If isSimpleCount() returns a pointer to a Table structure, then
  92352. ** the SQL statement is of the form:
  92353. **
  92354. ** SELECT count(*) FROM <tbl>
  92355. **
  92356. ** where the Table structure returned represents table <tbl>.
  92357. **
  92358. ** This statement is so common that it is optimized specially. The
  92359. ** OP_Count instruction is executed either on the intkey table that
  92360. ** contains the data for table <tbl> or on one of its indexes. It
  92361. ** is better to execute the op on an index, as indexes are almost
  92362. ** always spread across less pages than their corresponding tables.
  92363. */
  92364. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92365. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  92366. Index *pIdx; /* Iterator variable */
  92367. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  92368. Index *pBest = 0; /* Best index found so far */
  92369. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  92370. sqlite3CodeVerifySchema(pParse, iDb);
  92371. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  92372. /* Search for the index that has the least amount of columns. If
  92373. ** there is such an index, and it has less columns than the table
  92374. ** does, then we can assume that it consumes less space on disk and
  92375. ** will therefore be cheaper to scan to determine the query result.
  92376. ** In this case set iRoot to the root page number of the index b-tree
  92377. ** and pKeyInfo to the KeyInfo structure required to navigate the
  92378. ** index.
  92379. **
  92380. ** (2011-04-15) Do not do a full scan of an unordered index.
  92381. **
  92382. ** In practice the KeyInfo structure will not be used. It is only
  92383. ** passed to keep OP_OpenRead happy.
  92384. */
  92385. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  92386. if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
  92387. pBest = pIdx;
  92388. }
  92389. }
  92390. if( pBest && pBest->nColumn<pTab->nCol ){
  92391. iRoot = pBest->tnum;
  92392. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  92393. }
  92394. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  92395. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  92396. if( pKeyInfo ){
  92397. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  92398. }
  92399. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  92400. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  92401. explainSimpleCount(pParse, pTab, pBest);
  92402. }else
  92403. #endif /* SQLITE_OMIT_BTREECOUNT */
  92404. {
  92405. /* Check if the query is of one of the following forms:
  92406. **
  92407. ** SELECT min(x) FROM ...
  92408. ** SELECT max(x) FROM ...
  92409. **
  92410. ** If it is, then ask the code in where.c to attempt to sort results
  92411. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  92412. ** If where.c is able to produce results sorted in this order, then
  92413. ** add vdbe code to break out of the processing loop after the
  92414. ** first iteration (since the first iteration of the loop is
  92415. ** guaranteed to operate on the row with the minimum or maximum
  92416. ** value of x, the only row required).
  92417. **
  92418. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  92419. ** modify behaviour as follows:
  92420. **
  92421. ** + If the query is a "SELECT min(x)", then the loop coded by
  92422. ** where.c should not iterate over any values with a NULL value
  92423. ** for x.
  92424. **
  92425. ** + The optimizer code in where.c (the thing that decides which
  92426. ** index or indices to use) should place a different priority on
  92427. ** satisfying the 'ORDER BY' clause than it does in other cases.
  92428. ** Refer to code and comments in where.c for details.
  92429. */
  92430. ExprList *pMinMax = 0;
  92431. u8 flag = minMaxQuery(p);
  92432. if( flag ){
  92433. assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
  92434. assert( p->pEList->a[0].pExpr->x.pList->nExpr==1 );
  92435. pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
  92436. pDel = pMinMax;
  92437. if( pMinMax && !db->mallocFailed ){
  92438. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  92439. pMinMax->a[0].pExpr->op = TK_COLUMN;
  92440. }
  92441. }
  92442. /* This case runs if the aggregate has no GROUP BY clause. The
  92443. ** processing is much simpler since there is only a single row
  92444. ** of output.
  92445. */
  92446. resetAccumulator(pParse, &sAggInfo);
  92447. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  92448. if( pWInfo==0 ){
  92449. sqlite3ExprListDelete(db, pDel);
  92450. goto select_end;
  92451. }
  92452. updateAccumulator(pParse, &sAggInfo);
  92453. assert( pMinMax==0 || pMinMax->nExpr==1 );
  92454. if( pWInfo->nOBSat>0 ){
  92455. sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  92456. VdbeComment((v, "%s() by index",
  92457. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  92458. }
  92459. sqlite3WhereEnd(pWInfo);
  92460. finalizeAggFunctions(pParse, &sAggInfo);
  92461. }
  92462. pOrderBy = 0;
  92463. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  92464. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  92465. pDest, addrEnd, addrEnd);
  92466. sqlite3ExprListDelete(db, pDel);
  92467. }
  92468. sqlite3VdbeResolveLabel(v, addrEnd);
  92469. } /* endif aggregate query */
  92470. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  92471. explainTempTable(pParse, "DISTINCT");
  92472. }
  92473. /* If there is an ORDER BY clause, then we need to sort the results
  92474. ** and send them to the callback one by one.
  92475. */
  92476. if( pOrderBy ){
  92477. explainTempTable(pParse, "ORDER BY");
  92478. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  92479. }
  92480. /* Jump here to skip this query
  92481. */
  92482. sqlite3VdbeResolveLabel(v, iEnd);
  92483. /* The SELECT was successfully coded. Set the return code to 0
  92484. ** to indicate no errors.
  92485. */
  92486. rc = 0;
  92487. /* Control jumps to here if an error is encountered above, or upon
  92488. ** successful coding of the SELECT.
  92489. */
  92490. select_end:
  92491. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  92492. /* Identify column names if results of the SELECT are to be output.
  92493. */
  92494. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  92495. generateColumnNames(pParse, pTabList, pEList);
  92496. }
  92497. sqlite3DbFree(db, sAggInfo.aCol);
  92498. sqlite3DbFree(db, sAggInfo.aFunc);
  92499. return rc;
  92500. }
  92501. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  92502. /*
  92503. ** Generate a human-readable description of a the Select object.
  92504. */
  92505. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  92506. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  92507. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  92508. if( p->selFlags & SF_Distinct ){
  92509. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  92510. }
  92511. if( p->selFlags & SF_Aggregate ){
  92512. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  92513. }
  92514. sqlite3ExplainNL(pVdbe);
  92515. sqlite3ExplainPrintf(pVdbe, " ");
  92516. }
  92517. sqlite3ExplainExprList(pVdbe, p->pEList);
  92518. sqlite3ExplainNL(pVdbe);
  92519. if( p->pSrc && p->pSrc->nSrc ){
  92520. int i;
  92521. sqlite3ExplainPrintf(pVdbe, "FROM ");
  92522. sqlite3ExplainPush(pVdbe);
  92523. for(i=0; i<p->pSrc->nSrc; i++){
  92524. struct SrcList_item *pItem = &p->pSrc->a[i];
  92525. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  92526. if( pItem->pSelect ){
  92527. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  92528. if( pItem->pTab ){
  92529. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  92530. }
  92531. }else if( pItem->zName ){
  92532. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  92533. }
  92534. if( pItem->zAlias ){
  92535. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  92536. }
  92537. if( pItem->jointype & JT_LEFT ){
  92538. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  92539. }
  92540. sqlite3ExplainNL(pVdbe);
  92541. }
  92542. sqlite3ExplainPop(pVdbe);
  92543. }
  92544. if( p->pWhere ){
  92545. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  92546. sqlite3ExplainExpr(pVdbe, p->pWhere);
  92547. sqlite3ExplainNL(pVdbe);
  92548. }
  92549. if( p->pGroupBy ){
  92550. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  92551. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  92552. sqlite3ExplainNL(pVdbe);
  92553. }
  92554. if( p->pHaving ){
  92555. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  92556. sqlite3ExplainExpr(pVdbe, p->pHaving);
  92557. sqlite3ExplainNL(pVdbe);
  92558. }
  92559. if( p->pOrderBy ){
  92560. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  92561. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  92562. sqlite3ExplainNL(pVdbe);
  92563. }
  92564. if( p->pLimit ){
  92565. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  92566. sqlite3ExplainExpr(pVdbe, p->pLimit);
  92567. sqlite3ExplainNL(pVdbe);
  92568. }
  92569. if( p->pOffset ){
  92570. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  92571. sqlite3ExplainExpr(pVdbe, p->pOffset);
  92572. sqlite3ExplainNL(pVdbe);
  92573. }
  92574. }
  92575. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  92576. if( p==0 ){
  92577. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  92578. return;
  92579. }
  92580. while( p->pPrior ) p = p->pPrior;
  92581. sqlite3ExplainPush(pVdbe);
  92582. while( p ){
  92583. explainOneSelect(pVdbe, p);
  92584. p = p->pNext;
  92585. if( p==0 ) break;
  92586. sqlite3ExplainNL(pVdbe);
  92587. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  92588. }
  92589. sqlite3ExplainPrintf(pVdbe, "END");
  92590. sqlite3ExplainPop(pVdbe);
  92591. }
  92592. /* End of the structure debug printing code
  92593. *****************************************************************************/
  92594. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  92595. /************** End of select.c **********************************************/
  92596. /************** Begin file table.c *******************************************/
  92597. /*
  92598. ** 2001 September 15
  92599. **
  92600. ** The author disclaims copyright to this source code. In place of
  92601. ** a legal notice, here is a blessing:
  92602. **
  92603. ** May you do good and not evil.
  92604. ** May you find forgiveness for yourself and forgive others.
  92605. ** May you share freely, never taking more than you give.
  92606. **
  92607. *************************************************************************
  92608. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  92609. ** interface routines. These are just wrappers around the main
  92610. ** interface routine of sqlite3_exec().
  92611. **
  92612. ** These routines are in a separate files so that they will not be linked
  92613. ** if they are not used.
  92614. */
  92615. /* #include <stdlib.h> */
  92616. /* #include <string.h> */
  92617. #ifndef SQLITE_OMIT_GET_TABLE
  92618. /*
  92619. ** This structure is used to pass data from sqlite3_get_table() through
  92620. ** to the callback function is uses to build the result.
  92621. */
  92622. typedef struct TabResult {
  92623. char **azResult; /* Accumulated output */
  92624. char *zErrMsg; /* Error message text, if an error occurs */
  92625. int nAlloc; /* Slots allocated for azResult[] */
  92626. int nRow; /* Number of rows in the result */
  92627. int nColumn; /* Number of columns in the result */
  92628. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  92629. int rc; /* Return code from sqlite3_exec() */
  92630. } TabResult;
  92631. /*
  92632. ** This routine is called once for each row in the result table. Its job
  92633. ** is to fill in the TabResult structure appropriately, allocating new
  92634. ** memory as necessary.
  92635. */
  92636. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  92637. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  92638. int need; /* Slots needed in p->azResult[] */
  92639. int i; /* Loop counter */
  92640. char *z; /* A single column of result */
  92641. /* Make sure there is enough space in p->azResult to hold everything
  92642. ** we need to remember from this invocation of the callback.
  92643. */
  92644. if( p->nRow==0 && argv!=0 ){
  92645. need = nCol*2;
  92646. }else{
  92647. need = nCol;
  92648. }
  92649. if( p->nData + need > p->nAlloc ){
  92650. char **azNew;
  92651. p->nAlloc = p->nAlloc*2 + need;
  92652. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  92653. if( azNew==0 ) goto malloc_failed;
  92654. p->azResult = azNew;
  92655. }
  92656. /* If this is the first row, then generate an extra row containing
  92657. ** the names of all columns.
  92658. */
  92659. if( p->nRow==0 ){
  92660. p->nColumn = nCol;
  92661. for(i=0; i<nCol; i++){
  92662. z = sqlite3_mprintf("%s", colv[i]);
  92663. if( z==0 ) goto malloc_failed;
  92664. p->azResult[p->nData++] = z;
  92665. }
  92666. }else if( p->nColumn!=nCol ){
  92667. sqlite3_free(p->zErrMsg);
  92668. p->zErrMsg = sqlite3_mprintf(
  92669. "sqlite3_get_table() called with two or more incompatible queries"
  92670. );
  92671. p->rc = SQLITE_ERROR;
  92672. return 1;
  92673. }
  92674. /* Copy over the row data
  92675. */
  92676. if( argv!=0 ){
  92677. for(i=0; i<nCol; i++){
  92678. if( argv[i]==0 ){
  92679. z = 0;
  92680. }else{
  92681. int n = sqlite3Strlen30(argv[i])+1;
  92682. z = sqlite3_malloc( n );
  92683. if( z==0 ) goto malloc_failed;
  92684. memcpy(z, argv[i], n);
  92685. }
  92686. p->azResult[p->nData++] = z;
  92687. }
  92688. p->nRow++;
  92689. }
  92690. return 0;
  92691. malloc_failed:
  92692. p->rc = SQLITE_NOMEM;
  92693. return 1;
  92694. }
  92695. /*
  92696. ** Query the database. But instead of invoking a callback for each row,
  92697. ** malloc() for space to hold the result and return the entire results
  92698. ** at the conclusion of the call.
  92699. **
  92700. ** The result that is written to ***pazResult is held in memory obtained
  92701. ** from malloc(). But the caller cannot free this memory directly.
  92702. ** Instead, the entire table should be passed to sqlite3_free_table() when
  92703. ** the calling procedure is finished using it.
  92704. */
  92705. SQLITE_API int sqlite3_get_table(
  92706. sqlite3 *db, /* The database on which the SQL executes */
  92707. const char *zSql, /* The SQL to be executed */
  92708. char ***pazResult, /* Write the result table here */
  92709. int *pnRow, /* Write the number of rows in the result here */
  92710. int *pnColumn, /* Write the number of columns of result here */
  92711. char **pzErrMsg /* Write error messages here */
  92712. ){
  92713. int rc;
  92714. TabResult res;
  92715. *pazResult = 0;
  92716. if( pnColumn ) *pnColumn = 0;
  92717. if( pnRow ) *pnRow = 0;
  92718. if( pzErrMsg ) *pzErrMsg = 0;
  92719. res.zErrMsg = 0;
  92720. res.nRow = 0;
  92721. res.nColumn = 0;
  92722. res.nData = 1;
  92723. res.nAlloc = 20;
  92724. res.rc = SQLITE_OK;
  92725. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  92726. if( res.azResult==0 ){
  92727. db->errCode = SQLITE_NOMEM;
  92728. return SQLITE_NOMEM;
  92729. }
  92730. res.azResult[0] = 0;
  92731. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  92732. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  92733. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  92734. if( (rc&0xff)==SQLITE_ABORT ){
  92735. sqlite3_free_table(&res.azResult[1]);
  92736. if( res.zErrMsg ){
  92737. if( pzErrMsg ){
  92738. sqlite3_free(*pzErrMsg);
  92739. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  92740. }
  92741. sqlite3_free(res.zErrMsg);
  92742. }
  92743. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  92744. return res.rc;
  92745. }
  92746. sqlite3_free(res.zErrMsg);
  92747. if( rc!=SQLITE_OK ){
  92748. sqlite3_free_table(&res.azResult[1]);
  92749. return rc;
  92750. }
  92751. if( res.nAlloc>res.nData ){
  92752. char **azNew;
  92753. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  92754. if( azNew==0 ){
  92755. sqlite3_free_table(&res.azResult[1]);
  92756. db->errCode = SQLITE_NOMEM;
  92757. return SQLITE_NOMEM;
  92758. }
  92759. res.azResult = azNew;
  92760. }
  92761. *pazResult = &res.azResult[1];
  92762. if( pnColumn ) *pnColumn = res.nColumn;
  92763. if( pnRow ) *pnRow = res.nRow;
  92764. return rc;
  92765. }
  92766. /*
  92767. ** This routine frees the space the sqlite3_get_table() malloced.
  92768. */
  92769. SQLITE_API void sqlite3_free_table(
  92770. char **azResult /* Result returned from from sqlite3_get_table() */
  92771. ){
  92772. if( azResult ){
  92773. int i, n;
  92774. azResult--;
  92775. assert( azResult!=0 );
  92776. n = SQLITE_PTR_TO_INT(azResult[0]);
  92777. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  92778. sqlite3_free(azResult);
  92779. }
  92780. }
  92781. #endif /* SQLITE_OMIT_GET_TABLE */
  92782. /************** End of table.c ***********************************************/
  92783. /************** Begin file trigger.c *****************************************/
  92784. /*
  92785. **
  92786. ** The author disclaims copyright to this source code. In place of
  92787. ** a legal notice, here is a blessing:
  92788. **
  92789. ** May you do good and not evil.
  92790. ** May you find forgiveness for yourself and forgive others.
  92791. ** May you share freely, never taking more than you give.
  92792. **
  92793. *************************************************************************
  92794. ** This file contains the implementation for TRIGGERs
  92795. */
  92796. #ifndef SQLITE_OMIT_TRIGGER
  92797. /*
  92798. ** Delete a linked list of TriggerStep structures.
  92799. */
  92800. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  92801. while( pTriggerStep ){
  92802. TriggerStep * pTmp = pTriggerStep;
  92803. pTriggerStep = pTriggerStep->pNext;
  92804. sqlite3ExprDelete(db, pTmp->pWhere);
  92805. sqlite3ExprListDelete(db, pTmp->pExprList);
  92806. sqlite3SelectDelete(db, pTmp->pSelect);
  92807. sqlite3IdListDelete(db, pTmp->pIdList);
  92808. sqlite3DbFree(db, pTmp);
  92809. }
  92810. }
  92811. /*
  92812. ** Given table pTab, return a list of all the triggers attached to
  92813. ** the table. The list is connected by Trigger.pNext pointers.
  92814. **
  92815. ** All of the triggers on pTab that are in the same database as pTab
  92816. ** are already attached to pTab->pTrigger. But there might be additional
  92817. ** triggers on pTab in the TEMP schema. This routine prepends all
  92818. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  92819. ** and returns the combined list.
  92820. **
  92821. ** To state it another way: This routine returns a list of all triggers
  92822. ** that fire off of pTab. The list will include any TEMP triggers on
  92823. ** pTab as well as the triggers lised in pTab->pTrigger.
  92824. */
  92825. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  92826. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  92827. Trigger *pList = 0; /* List of triggers to return */
  92828. if( pParse->disableTriggers ){
  92829. return 0;
  92830. }
  92831. if( pTmpSchema!=pTab->pSchema ){
  92832. HashElem *p;
  92833. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  92834. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  92835. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  92836. if( pTrig->pTabSchema==pTab->pSchema
  92837. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  92838. ){
  92839. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  92840. pList = pTrig;
  92841. }
  92842. }
  92843. }
  92844. return (pList ? pList : pTab->pTrigger);
  92845. }
  92846. /*
  92847. ** This is called by the parser when it sees a CREATE TRIGGER statement
  92848. ** up to the point of the BEGIN before the trigger actions. A Trigger
  92849. ** structure is generated based on the information available and stored
  92850. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  92851. ** sqlite3FinishTrigger() function is called to complete the trigger
  92852. ** construction process.
  92853. */
  92854. SQLITE_PRIVATE void sqlite3BeginTrigger(
  92855. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  92856. Token *pName1, /* The name of the trigger */
  92857. Token *pName2, /* The name of the trigger */
  92858. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  92859. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  92860. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  92861. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  92862. Expr *pWhen, /* WHEN clause */
  92863. int isTemp, /* True if the TEMPORARY keyword is present */
  92864. int noErr /* Suppress errors if the trigger already exists */
  92865. ){
  92866. Trigger *pTrigger = 0; /* The new trigger */
  92867. Table *pTab; /* Table that the trigger fires off of */
  92868. char *zName = 0; /* Name of the trigger */
  92869. sqlite3 *db = pParse->db; /* The database connection */
  92870. int iDb; /* The database to store the trigger in */
  92871. Token *pName; /* The unqualified db name */
  92872. DbFixer sFix; /* State vector for the DB fixer */
  92873. int iTabDb; /* Index of the database holding pTab */
  92874. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  92875. assert( pName2!=0 );
  92876. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  92877. assert( op>0 && op<0xff );
  92878. if( isTemp ){
  92879. /* If TEMP was specified, then the trigger name may not be qualified. */
  92880. if( pName2->n>0 ){
  92881. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  92882. goto trigger_cleanup;
  92883. }
  92884. iDb = 1;
  92885. pName = pName1;
  92886. }else{
  92887. /* Figure out the db that the trigger will be created in */
  92888. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  92889. if( iDb<0 ){
  92890. goto trigger_cleanup;
  92891. }
  92892. }
  92893. if( !pTableName || db->mallocFailed ){
  92894. goto trigger_cleanup;
  92895. }
  92896. /* A long-standing parser bug is that this syntax was allowed:
  92897. **
  92898. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  92899. ** ^^^^^^^^
  92900. **
  92901. ** To maintain backwards compatibility, ignore the database
  92902. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  92903. */
  92904. if( db->init.busy && iDb!=1 ){
  92905. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  92906. pTableName->a[0].zDatabase = 0;
  92907. }
  92908. /* If the trigger name was unqualified, and the table is a temp table,
  92909. ** then set iDb to 1 to create the trigger in the temporary database.
  92910. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  92911. ** exist, the error is caught by the block below.
  92912. */
  92913. pTab = sqlite3SrcListLookup(pParse, pTableName);
  92914. if( db->init.busy==0 && pName2->n==0 && pTab
  92915. && pTab->pSchema==db->aDb[1].pSchema ){
  92916. iDb = 1;
  92917. }
  92918. /* Ensure the table name matches database name and that the table exists */
  92919. if( db->mallocFailed ) goto trigger_cleanup;
  92920. assert( pTableName->nSrc==1 );
  92921. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
  92922. sqlite3FixSrcList(&sFix, pTableName) ){
  92923. goto trigger_cleanup;
  92924. }
  92925. pTab = sqlite3SrcListLookup(pParse, pTableName);
  92926. if( !pTab ){
  92927. /* The table does not exist. */
  92928. if( db->init.iDb==1 ){
  92929. /* Ticket #3810.
  92930. ** Normally, whenever a table is dropped, all associated triggers are
  92931. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  92932. ** and the table is dropped by a different database connection, the
  92933. ** trigger is not visible to the database connection that does the
  92934. ** drop so the trigger cannot be dropped. This results in an
  92935. ** "orphaned trigger" - a trigger whose associated table is missing.
  92936. */
  92937. db->init.orphanTrigger = 1;
  92938. }
  92939. goto trigger_cleanup;
  92940. }
  92941. if( IsVirtual(pTab) ){
  92942. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  92943. goto trigger_cleanup;
  92944. }
  92945. /* Check that the trigger name is not reserved and that no trigger of the
  92946. ** specified name exists */
  92947. zName = sqlite3NameFromToken(db, pName);
  92948. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  92949. goto trigger_cleanup;
  92950. }
  92951. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92952. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  92953. zName, sqlite3Strlen30(zName)) ){
  92954. if( !noErr ){
  92955. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  92956. }else{
  92957. assert( !db->init.busy );
  92958. sqlite3CodeVerifySchema(pParse, iDb);
  92959. }
  92960. goto trigger_cleanup;
  92961. }
  92962. /* Do not create a trigger on a system table */
  92963. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  92964. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  92965. pParse->nErr++;
  92966. goto trigger_cleanup;
  92967. }
  92968. /* INSTEAD of triggers are only for views and views only support INSTEAD
  92969. ** of triggers.
  92970. */
  92971. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  92972. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  92973. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  92974. goto trigger_cleanup;
  92975. }
  92976. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  92977. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  92978. " trigger on table: %S", pTableName, 0);
  92979. goto trigger_cleanup;
  92980. }
  92981. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  92982. #ifndef SQLITE_OMIT_AUTHORIZATION
  92983. {
  92984. int code = SQLITE_CREATE_TRIGGER;
  92985. const char *zDb = db->aDb[iTabDb].zName;
  92986. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  92987. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  92988. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  92989. goto trigger_cleanup;
  92990. }
  92991. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  92992. goto trigger_cleanup;
  92993. }
  92994. }
  92995. #endif
  92996. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  92997. ** cannot appear on views. So we might as well translate every
  92998. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  92999. ** elsewhere.
  93000. */
  93001. if (tr_tm == TK_INSTEAD){
  93002. tr_tm = TK_BEFORE;
  93003. }
  93004. /* Build the Trigger object */
  93005. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  93006. if( pTrigger==0 ) goto trigger_cleanup;
  93007. pTrigger->zName = zName;
  93008. zName = 0;
  93009. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  93010. pTrigger->pSchema = db->aDb[iDb].pSchema;
  93011. pTrigger->pTabSchema = pTab->pSchema;
  93012. pTrigger->op = (u8)op;
  93013. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  93014. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  93015. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  93016. assert( pParse->pNewTrigger==0 );
  93017. pParse->pNewTrigger = pTrigger;
  93018. trigger_cleanup:
  93019. sqlite3DbFree(db, zName);
  93020. sqlite3SrcListDelete(db, pTableName);
  93021. sqlite3IdListDelete(db, pColumns);
  93022. sqlite3ExprDelete(db, pWhen);
  93023. if( !pParse->pNewTrigger ){
  93024. sqlite3DeleteTrigger(db, pTrigger);
  93025. }else{
  93026. assert( pParse->pNewTrigger==pTrigger );
  93027. }
  93028. }
  93029. /*
  93030. ** This routine is called after all of the trigger actions have been parsed
  93031. ** in order to complete the process of building the trigger.
  93032. */
  93033. SQLITE_PRIVATE void sqlite3FinishTrigger(
  93034. Parse *pParse, /* Parser context */
  93035. TriggerStep *pStepList, /* The triggered program */
  93036. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  93037. ){
  93038. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  93039. char *zName; /* Name of trigger */
  93040. sqlite3 *db = pParse->db; /* The database */
  93041. DbFixer sFix; /* Fixer object */
  93042. int iDb; /* Database containing the trigger */
  93043. Token nameToken; /* Trigger name for error reporting */
  93044. pParse->pNewTrigger = 0;
  93045. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  93046. zName = pTrig->zName;
  93047. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  93048. pTrig->step_list = pStepList;
  93049. while( pStepList ){
  93050. pStepList->pTrig = pTrig;
  93051. pStepList = pStepList->pNext;
  93052. }
  93053. nameToken.z = pTrig->zName;
  93054. nameToken.n = sqlite3Strlen30(nameToken.z);
  93055. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
  93056. && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
  93057. goto triggerfinish_cleanup;
  93058. }
  93059. /* if we are not initializing,
  93060. ** build the sqlite_master entry
  93061. */
  93062. if( !db->init.busy ){
  93063. Vdbe *v;
  93064. char *z;
  93065. /* Make an entry in the sqlite_master table */
  93066. v = sqlite3GetVdbe(pParse);
  93067. if( v==0 ) goto triggerfinish_cleanup;
  93068. sqlite3BeginWriteOperation(pParse, 0, iDb);
  93069. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  93070. sqlite3NestedParse(pParse,
  93071. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  93072. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  93073. pTrig->table, z);
  93074. sqlite3DbFree(db, z);
  93075. sqlite3ChangeCookie(pParse, iDb);
  93076. sqlite3VdbeAddParseSchemaOp(v, iDb,
  93077. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  93078. }
  93079. if( db->init.busy ){
  93080. Trigger *pLink = pTrig;
  93081. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  93082. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93083. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  93084. if( pTrig ){
  93085. db->mallocFailed = 1;
  93086. }else if( pLink->pSchema==pLink->pTabSchema ){
  93087. Table *pTab;
  93088. int n = sqlite3Strlen30(pLink->table);
  93089. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  93090. assert( pTab!=0 );
  93091. pLink->pNext = pTab->pTrigger;
  93092. pTab->pTrigger = pLink;
  93093. }
  93094. }
  93095. triggerfinish_cleanup:
  93096. sqlite3DeleteTrigger(db, pTrig);
  93097. assert( !pParse->pNewTrigger );
  93098. sqlite3DeleteTriggerStep(db, pStepList);
  93099. }
  93100. /*
  93101. ** Turn a SELECT statement (that the pSelect parameter points to) into
  93102. ** a trigger step. Return a pointer to a TriggerStep structure.
  93103. **
  93104. ** The parser calls this routine when it finds a SELECT statement in
  93105. ** body of a TRIGGER.
  93106. */
  93107. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  93108. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  93109. if( pTriggerStep==0 ) {
  93110. sqlite3SelectDelete(db, pSelect);
  93111. return 0;
  93112. }
  93113. pTriggerStep->op = TK_SELECT;
  93114. pTriggerStep->pSelect = pSelect;
  93115. pTriggerStep->orconf = OE_Default;
  93116. return pTriggerStep;
  93117. }
  93118. /*
  93119. ** Allocate space to hold a new trigger step. The allocated space
  93120. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  93121. **
  93122. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  93123. */
  93124. static TriggerStep *triggerStepAllocate(
  93125. sqlite3 *db, /* Database connection */
  93126. u8 op, /* Trigger opcode */
  93127. Token *pName /* The target name */
  93128. ){
  93129. TriggerStep *pTriggerStep;
  93130. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  93131. if( pTriggerStep ){
  93132. char *z = (char*)&pTriggerStep[1];
  93133. memcpy(z, pName->z, pName->n);
  93134. pTriggerStep->target.z = z;
  93135. pTriggerStep->target.n = pName->n;
  93136. pTriggerStep->op = op;
  93137. }
  93138. return pTriggerStep;
  93139. }
  93140. /*
  93141. ** Build a trigger step out of an INSERT statement. Return a pointer
  93142. ** to the new trigger step.
  93143. **
  93144. ** The parser calls this routine when it sees an INSERT inside the
  93145. ** body of a trigger.
  93146. */
  93147. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  93148. sqlite3 *db, /* The database connection */
  93149. Token *pTableName, /* Name of the table into which we insert */
  93150. IdList *pColumn, /* List of columns in pTableName to insert into */
  93151. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  93152. Select *pSelect, /* A SELECT statement that supplies values */
  93153. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  93154. ){
  93155. TriggerStep *pTriggerStep;
  93156. assert(pEList == 0 || pSelect == 0);
  93157. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  93158. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  93159. if( pTriggerStep ){
  93160. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  93161. pTriggerStep->pIdList = pColumn;
  93162. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  93163. pTriggerStep->orconf = orconf;
  93164. }else{
  93165. sqlite3IdListDelete(db, pColumn);
  93166. }
  93167. sqlite3ExprListDelete(db, pEList);
  93168. sqlite3SelectDelete(db, pSelect);
  93169. return pTriggerStep;
  93170. }
  93171. /*
  93172. ** Construct a trigger step that implements an UPDATE statement and return
  93173. ** a pointer to that trigger step. The parser calls this routine when it
  93174. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  93175. */
  93176. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  93177. sqlite3 *db, /* The database connection */
  93178. Token *pTableName, /* Name of the table to be updated */
  93179. ExprList *pEList, /* The SET clause: list of column and new values */
  93180. Expr *pWhere, /* The WHERE clause */
  93181. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  93182. ){
  93183. TriggerStep *pTriggerStep;
  93184. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  93185. if( pTriggerStep ){
  93186. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  93187. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  93188. pTriggerStep->orconf = orconf;
  93189. }
  93190. sqlite3ExprListDelete(db, pEList);
  93191. sqlite3ExprDelete(db, pWhere);
  93192. return pTriggerStep;
  93193. }
  93194. /*
  93195. ** Construct a trigger step that implements a DELETE statement and return
  93196. ** a pointer to that trigger step. The parser calls this routine when it
  93197. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  93198. */
  93199. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  93200. sqlite3 *db, /* Database connection */
  93201. Token *pTableName, /* The table from which rows are deleted */
  93202. Expr *pWhere /* The WHERE clause */
  93203. ){
  93204. TriggerStep *pTriggerStep;
  93205. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  93206. if( pTriggerStep ){
  93207. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  93208. pTriggerStep->orconf = OE_Default;
  93209. }
  93210. sqlite3ExprDelete(db, pWhere);
  93211. return pTriggerStep;
  93212. }
  93213. /*
  93214. ** Recursively delete a Trigger structure
  93215. */
  93216. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  93217. if( pTrigger==0 ) return;
  93218. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  93219. sqlite3DbFree(db, pTrigger->zName);
  93220. sqlite3DbFree(db, pTrigger->table);
  93221. sqlite3ExprDelete(db, pTrigger->pWhen);
  93222. sqlite3IdListDelete(db, pTrigger->pColumns);
  93223. sqlite3DbFree(db, pTrigger);
  93224. }
  93225. /*
  93226. ** This function is called to drop a trigger from the database schema.
  93227. **
  93228. ** This may be called directly from the parser and therefore identifies
  93229. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  93230. ** same job as this routine except it takes a pointer to the trigger
  93231. ** instead of the trigger name.
  93232. **/
  93233. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  93234. Trigger *pTrigger = 0;
  93235. int i;
  93236. const char *zDb;
  93237. const char *zName;
  93238. int nName;
  93239. sqlite3 *db = pParse->db;
  93240. if( db->mallocFailed ) goto drop_trigger_cleanup;
  93241. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  93242. goto drop_trigger_cleanup;
  93243. }
  93244. assert( pName->nSrc==1 );
  93245. zDb = pName->a[0].zDatabase;
  93246. zName = pName->a[0].zName;
  93247. nName = sqlite3Strlen30(zName);
  93248. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  93249. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  93250. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  93251. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  93252. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  93253. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  93254. if( pTrigger ) break;
  93255. }
  93256. if( !pTrigger ){
  93257. if( !noErr ){
  93258. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  93259. }else{
  93260. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  93261. }
  93262. pParse->checkSchema = 1;
  93263. goto drop_trigger_cleanup;
  93264. }
  93265. sqlite3DropTriggerPtr(pParse, pTrigger);
  93266. drop_trigger_cleanup:
  93267. sqlite3SrcListDelete(db, pName);
  93268. }
  93269. /*
  93270. ** Return a pointer to the Table structure for the table that a trigger
  93271. ** is set on.
  93272. */
  93273. static Table *tableOfTrigger(Trigger *pTrigger){
  93274. int n = sqlite3Strlen30(pTrigger->table);
  93275. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  93276. }
  93277. /*
  93278. ** Drop a trigger given a pointer to that trigger.
  93279. */
  93280. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  93281. Table *pTable;
  93282. Vdbe *v;
  93283. sqlite3 *db = pParse->db;
  93284. int iDb;
  93285. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  93286. assert( iDb>=0 && iDb<db->nDb );
  93287. pTable = tableOfTrigger(pTrigger);
  93288. assert( pTable );
  93289. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  93290. #ifndef SQLITE_OMIT_AUTHORIZATION
  93291. {
  93292. int code = SQLITE_DROP_TRIGGER;
  93293. const char *zDb = db->aDb[iDb].zName;
  93294. const char *zTab = SCHEMA_TABLE(iDb);
  93295. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  93296. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  93297. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  93298. return;
  93299. }
  93300. }
  93301. #endif
  93302. /* Generate code to destroy the database record of the trigger.
  93303. */
  93304. assert( pTable!=0 );
  93305. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  93306. int base;
  93307. static const VdbeOpList dropTrigger[] = {
  93308. { OP_Rewind, 0, ADDR(9), 0},
  93309. { OP_String8, 0, 1, 0}, /* 1 */
  93310. { OP_Column, 0, 1, 2},
  93311. { OP_Ne, 2, ADDR(8), 1},
  93312. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  93313. { OP_Column, 0, 0, 2},
  93314. { OP_Ne, 2, ADDR(8), 1},
  93315. { OP_Delete, 0, 0, 0},
  93316. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  93317. };
  93318. sqlite3BeginWriteOperation(pParse, 0, iDb);
  93319. sqlite3OpenMasterTable(pParse, iDb);
  93320. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  93321. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  93322. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  93323. sqlite3ChangeCookie(pParse, iDb);
  93324. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  93325. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  93326. if( pParse->nMem<3 ){
  93327. pParse->nMem = 3;
  93328. }
  93329. }
  93330. }
  93331. /*
  93332. ** Remove a trigger from the hash tables of the sqlite* pointer.
  93333. */
  93334. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  93335. Trigger *pTrigger;
  93336. Hash *pHash;
  93337. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93338. pHash = &(db->aDb[iDb].pSchema->trigHash);
  93339. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  93340. if( ALWAYS(pTrigger) ){
  93341. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  93342. Table *pTab = tableOfTrigger(pTrigger);
  93343. Trigger **pp;
  93344. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  93345. *pp = (*pp)->pNext;
  93346. }
  93347. sqlite3DeleteTrigger(db, pTrigger);
  93348. db->flags |= SQLITE_InternChanges;
  93349. }
  93350. }
  93351. /*
  93352. ** pEList is the SET clause of an UPDATE statement. Each entry
  93353. ** in pEList is of the format <id>=<expr>. If any of the entries
  93354. ** in pEList have an <id> which matches an identifier in pIdList,
  93355. ** then return TRUE. If pIdList==NULL, then it is considered a
  93356. ** wildcard that matches anything. Likewise if pEList==NULL then
  93357. ** it matches anything so always return true. Return false only
  93358. ** if there is no match.
  93359. */
  93360. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  93361. int e;
  93362. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  93363. for(e=0; e<pEList->nExpr; e++){
  93364. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  93365. }
  93366. return 0;
  93367. }
  93368. /*
  93369. ** Return a list of all triggers on table pTab if there exists at least
  93370. ** one trigger that must be fired when an operation of type 'op' is
  93371. ** performed on the table, and, if that operation is an UPDATE, if at
  93372. ** least one of the columns in pChanges is being modified.
  93373. */
  93374. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  93375. Parse *pParse, /* Parse context */
  93376. Table *pTab, /* The table the contains the triggers */
  93377. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  93378. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  93379. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  93380. ){
  93381. int mask = 0;
  93382. Trigger *pList = 0;
  93383. Trigger *p;
  93384. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  93385. pList = sqlite3TriggerList(pParse, pTab);
  93386. }
  93387. assert( pList==0 || IsVirtual(pTab)==0 );
  93388. for(p=pList; p; p=p->pNext){
  93389. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  93390. mask |= p->tr_tm;
  93391. }
  93392. }
  93393. if( pMask ){
  93394. *pMask = mask;
  93395. }
  93396. return (mask ? pList : 0);
  93397. }
  93398. /*
  93399. ** Convert the pStep->target token into a SrcList and return a pointer
  93400. ** to that SrcList.
  93401. **
  93402. ** This routine adds a specific database name, if needed, to the target when
  93403. ** forming the SrcList. This prevents a trigger in one database from
  93404. ** referring to a target in another database. An exception is when the
  93405. ** trigger is in TEMP in which case it can refer to any other database it
  93406. ** wants.
  93407. */
  93408. static SrcList *targetSrcList(
  93409. Parse *pParse, /* The parsing context */
  93410. TriggerStep *pStep /* The trigger containing the target token */
  93411. ){
  93412. int iDb; /* Index of the database to use */
  93413. SrcList *pSrc; /* SrcList to be returned */
  93414. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  93415. if( pSrc ){
  93416. assert( pSrc->nSrc>0 );
  93417. assert( pSrc->a!=0 );
  93418. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  93419. if( iDb==0 || iDb>=2 ){
  93420. sqlite3 *db = pParse->db;
  93421. assert( iDb<pParse->db->nDb );
  93422. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  93423. }
  93424. }
  93425. return pSrc;
  93426. }
  93427. /*
  93428. ** Generate VDBE code for the statements inside the body of a single
  93429. ** trigger.
  93430. */
  93431. static int codeTriggerProgram(
  93432. Parse *pParse, /* The parser context */
  93433. TriggerStep *pStepList, /* List of statements inside the trigger body */
  93434. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  93435. ){
  93436. TriggerStep *pStep;
  93437. Vdbe *v = pParse->pVdbe;
  93438. sqlite3 *db = pParse->db;
  93439. assert( pParse->pTriggerTab && pParse->pToplevel );
  93440. assert( pStepList );
  93441. assert( v!=0 );
  93442. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  93443. /* Figure out the ON CONFLICT policy that will be used for this step
  93444. ** of the trigger program. If the statement that caused this trigger
  93445. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  93446. ** the ON CONFLICT policy that was specified as part of the trigger
  93447. ** step statement. Example:
  93448. **
  93449. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  93450. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  93451. ** END;
  93452. **
  93453. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  93454. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  93455. */
  93456. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  93457. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  93458. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  93459. ** that it is not safe to refactor constants (this happens after the
  93460. ** start of the first loop in the SQL statement is coded - at that
  93461. ** point code may be conditionally executed, so it is no longer safe to
  93462. ** initialize constant register values). */
  93463. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  93464. pParse->cookieGoto = 0;
  93465. switch( pStep->op ){
  93466. case TK_UPDATE: {
  93467. sqlite3Update(pParse,
  93468. targetSrcList(pParse, pStep),
  93469. sqlite3ExprListDup(db, pStep->pExprList, 0),
  93470. sqlite3ExprDup(db, pStep->pWhere, 0),
  93471. pParse->eOrconf
  93472. );
  93473. break;
  93474. }
  93475. case TK_INSERT: {
  93476. sqlite3Insert(pParse,
  93477. targetSrcList(pParse, pStep),
  93478. sqlite3ExprListDup(db, pStep->pExprList, 0),
  93479. sqlite3SelectDup(db, pStep->pSelect, 0),
  93480. sqlite3IdListDup(db, pStep->pIdList),
  93481. pParse->eOrconf
  93482. );
  93483. break;
  93484. }
  93485. case TK_DELETE: {
  93486. sqlite3DeleteFrom(pParse,
  93487. targetSrcList(pParse, pStep),
  93488. sqlite3ExprDup(db, pStep->pWhere, 0)
  93489. );
  93490. break;
  93491. }
  93492. default: assert( pStep->op==TK_SELECT ); {
  93493. SelectDest sDest;
  93494. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  93495. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  93496. sqlite3Select(pParse, pSelect, &sDest);
  93497. sqlite3SelectDelete(db, pSelect);
  93498. break;
  93499. }
  93500. }
  93501. if( pStep->op!=TK_SELECT ){
  93502. sqlite3VdbeAddOp0(v, OP_ResetCount);
  93503. }
  93504. }
  93505. return 0;
  93506. }
  93507. #ifdef SQLITE_DEBUG
  93508. /*
  93509. ** This function is used to add VdbeComment() annotations to a VDBE
  93510. ** program. It is not used in production code, only for debugging.
  93511. */
  93512. static const char *onErrorText(int onError){
  93513. switch( onError ){
  93514. case OE_Abort: return "abort";
  93515. case OE_Rollback: return "rollback";
  93516. case OE_Fail: return "fail";
  93517. case OE_Replace: return "replace";
  93518. case OE_Ignore: return "ignore";
  93519. case OE_Default: return "default";
  93520. }
  93521. return "n/a";
  93522. }
  93523. #endif
  93524. /*
  93525. ** Parse context structure pFrom has just been used to create a sub-vdbe
  93526. ** (trigger program). If an error has occurred, transfer error information
  93527. ** from pFrom to pTo.
  93528. */
  93529. static void transferParseError(Parse *pTo, Parse *pFrom){
  93530. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  93531. assert( pTo->zErrMsg==0 || pTo->nErr );
  93532. if( pTo->nErr==0 ){
  93533. pTo->zErrMsg = pFrom->zErrMsg;
  93534. pTo->nErr = pFrom->nErr;
  93535. }else{
  93536. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  93537. }
  93538. }
  93539. /*
  93540. ** Create and populate a new TriggerPrg object with a sub-program
  93541. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  93542. */
  93543. static TriggerPrg *codeRowTrigger(
  93544. Parse *pParse, /* Current parse context */
  93545. Trigger *pTrigger, /* Trigger to code */
  93546. Table *pTab, /* The table pTrigger is attached to */
  93547. int orconf /* ON CONFLICT policy to code trigger program with */
  93548. ){
  93549. Parse *pTop = sqlite3ParseToplevel(pParse);
  93550. sqlite3 *db = pParse->db; /* Database handle */
  93551. TriggerPrg *pPrg; /* Value to return */
  93552. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  93553. Vdbe *v; /* Temporary VM */
  93554. NameContext sNC; /* Name context for sub-vdbe */
  93555. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  93556. Parse *pSubParse; /* Parse context for sub-vdbe */
  93557. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  93558. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  93559. assert( pTop->pVdbe );
  93560. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  93561. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  93562. ** list of the top-level Parse object sooner rather than later. */
  93563. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  93564. if( !pPrg ) return 0;
  93565. pPrg->pNext = pTop->pTriggerPrg;
  93566. pTop->pTriggerPrg = pPrg;
  93567. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  93568. if( !pProgram ) return 0;
  93569. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  93570. pPrg->pTrigger = pTrigger;
  93571. pPrg->orconf = orconf;
  93572. pPrg->aColmask[0] = 0xffffffff;
  93573. pPrg->aColmask[1] = 0xffffffff;
  93574. /* Allocate and populate a new Parse context to use for coding the
  93575. ** trigger sub-program. */
  93576. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  93577. if( !pSubParse ) return 0;
  93578. memset(&sNC, 0, sizeof(sNC));
  93579. sNC.pParse = pSubParse;
  93580. pSubParse->db = db;
  93581. pSubParse->pTriggerTab = pTab;
  93582. pSubParse->pToplevel = pTop;
  93583. pSubParse->zAuthContext = pTrigger->zName;
  93584. pSubParse->eTriggerOp = pTrigger->op;
  93585. pSubParse->nQueryLoop = pParse->nQueryLoop;
  93586. v = sqlite3GetVdbe(pSubParse);
  93587. if( v ){
  93588. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  93589. pTrigger->zName, onErrorText(orconf),
  93590. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  93591. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  93592. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  93593. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  93594. pTab->zName
  93595. ));
  93596. #ifndef SQLITE_OMIT_TRACE
  93597. sqlite3VdbeChangeP4(v, -1,
  93598. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  93599. );
  93600. #endif
  93601. /* If one was specified, code the WHEN clause. If it evaluates to false
  93602. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  93603. ** OP_Halt inserted at the end of the program. */
  93604. if( pTrigger->pWhen ){
  93605. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  93606. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  93607. && db->mallocFailed==0
  93608. ){
  93609. iEndTrigger = sqlite3VdbeMakeLabel(v);
  93610. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  93611. }
  93612. sqlite3ExprDelete(db, pWhen);
  93613. }
  93614. /* Code the trigger program into the sub-vdbe. */
  93615. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  93616. /* Insert an OP_Halt at the end of the sub-program. */
  93617. if( iEndTrigger ){
  93618. sqlite3VdbeResolveLabel(v, iEndTrigger);
  93619. }
  93620. sqlite3VdbeAddOp0(v, OP_Halt);
  93621. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  93622. transferParseError(pParse, pSubParse);
  93623. if( db->mallocFailed==0 ){
  93624. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  93625. }
  93626. pProgram->nMem = pSubParse->nMem;
  93627. pProgram->nCsr = pSubParse->nTab;
  93628. pProgram->nOnce = pSubParse->nOnce;
  93629. pProgram->token = (void *)pTrigger;
  93630. pPrg->aColmask[0] = pSubParse->oldmask;
  93631. pPrg->aColmask[1] = pSubParse->newmask;
  93632. sqlite3VdbeDelete(v);
  93633. }
  93634. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  93635. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  93636. sqlite3StackFree(db, pSubParse);
  93637. return pPrg;
  93638. }
  93639. /*
  93640. ** Return a pointer to a TriggerPrg object containing the sub-program for
  93641. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  93642. ** TriggerPrg object exists, a new object is allocated and populated before
  93643. ** being returned.
  93644. */
  93645. static TriggerPrg *getRowTrigger(
  93646. Parse *pParse, /* Current parse context */
  93647. Trigger *pTrigger, /* Trigger to code */
  93648. Table *pTab, /* The table trigger pTrigger is attached to */
  93649. int orconf /* ON CONFLICT algorithm. */
  93650. ){
  93651. Parse *pRoot = sqlite3ParseToplevel(pParse);
  93652. TriggerPrg *pPrg;
  93653. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  93654. /* It may be that this trigger has already been coded (or is in the
  93655. ** process of being coded). If this is the case, then an entry with
  93656. ** a matching TriggerPrg.pTrigger field will be present somewhere
  93657. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  93658. for(pPrg=pRoot->pTriggerPrg;
  93659. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  93660. pPrg=pPrg->pNext
  93661. );
  93662. /* If an existing TriggerPrg could not be located, create a new one. */
  93663. if( !pPrg ){
  93664. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  93665. }
  93666. return pPrg;
  93667. }
  93668. /*
  93669. ** Generate code for the trigger program associated with trigger p on
  93670. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  93671. ** function are the same as those described in the header function for
  93672. ** sqlite3CodeRowTrigger()
  93673. */
  93674. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  93675. Parse *pParse, /* Parse context */
  93676. Trigger *p, /* Trigger to code */
  93677. Table *pTab, /* The table to code triggers from */
  93678. int reg, /* Reg array containing OLD.* and NEW.* values */
  93679. int orconf, /* ON CONFLICT policy */
  93680. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  93681. ){
  93682. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  93683. TriggerPrg *pPrg;
  93684. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  93685. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  93686. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  93687. ** is a pointer to the sub-vdbe containing the trigger program. */
  93688. if( pPrg ){
  93689. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  93690. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  93691. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  93692. VdbeComment(
  93693. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  93694. /* Set the P5 operand of the OP_Program instruction to non-zero if
  93695. ** recursive invocation of this trigger program is disallowed. Recursive
  93696. ** invocation is disallowed if (a) the sub-program is really a trigger,
  93697. ** not a foreign key action, and (b) the flag to enable recursive triggers
  93698. ** is clear. */
  93699. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  93700. }
  93701. }
  93702. /*
  93703. ** This is called to code the required FOR EACH ROW triggers for an operation
  93704. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  93705. ** is given by the op paramater. The tr_tm parameter determines whether the
  93706. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  93707. ** parameter pChanges is passed the list of columns being modified.
  93708. **
  93709. ** If there are no triggers that fire at the specified time for the specified
  93710. ** operation on pTab, this function is a no-op.
  93711. **
  93712. ** The reg argument is the address of the first in an array of registers
  93713. ** that contain the values substituted for the new.* and old.* references
  93714. ** in the trigger program. If N is the number of columns in table pTab
  93715. ** (a copy of pTab->nCol), then registers are populated as follows:
  93716. **
  93717. ** Register Contains
  93718. ** ------------------------------------------------------
  93719. ** reg+0 OLD.rowid
  93720. ** reg+1 OLD.* value of left-most column of pTab
  93721. ** ... ...
  93722. ** reg+N OLD.* value of right-most column of pTab
  93723. ** reg+N+1 NEW.rowid
  93724. ** reg+N+2 OLD.* value of left-most column of pTab
  93725. ** ... ...
  93726. ** reg+N+N+1 NEW.* value of right-most column of pTab
  93727. **
  93728. ** For ON DELETE triggers, the registers containing the NEW.* values will
  93729. ** never be accessed by the trigger program, so they are not allocated or
  93730. ** populated by the caller (there is no data to populate them with anyway).
  93731. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  93732. ** are never accessed, and so are not allocated by the caller. So, for an
  93733. ** ON INSERT trigger, the value passed to this function as parameter reg
  93734. ** is not a readable register, although registers (reg+N) through
  93735. ** (reg+N+N+1) are.
  93736. **
  93737. ** Parameter orconf is the default conflict resolution algorithm for the
  93738. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  93739. ** is the instruction that control should jump to if a trigger program
  93740. ** raises an IGNORE exception.
  93741. */
  93742. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  93743. Parse *pParse, /* Parse context */
  93744. Trigger *pTrigger, /* List of triggers on table pTab */
  93745. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  93746. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  93747. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  93748. Table *pTab, /* The table to code triggers from */
  93749. int reg, /* The first in an array of registers (see above) */
  93750. int orconf, /* ON CONFLICT policy */
  93751. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  93752. ){
  93753. Trigger *p; /* Used to iterate through pTrigger list */
  93754. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  93755. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  93756. assert( (op==TK_UPDATE)==(pChanges!=0) );
  93757. for(p=pTrigger; p; p=p->pNext){
  93758. /* Sanity checking: The schema for the trigger and for the table are
  93759. ** always defined. The trigger must be in the same schema as the table
  93760. ** or else it must be a TEMP trigger. */
  93761. assert( p->pSchema!=0 );
  93762. assert( p->pTabSchema!=0 );
  93763. assert( p->pSchema==p->pTabSchema
  93764. || p->pSchema==pParse->db->aDb[1].pSchema );
  93765. /* Determine whether we should code this trigger */
  93766. if( p->op==op
  93767. && p->tr_tm==tr_tm
  93768. && checkColumnOverlap(p->pColumns, pChanges)
  93769. ){
  93770. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  93771. }
  93772. }
  93773. }
  93774. /*
  93775. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  93776. ** This function returns a 32-bit bitmask indicating which columns of the
  93777. ** old.* or new.* tables actually are used by triggers. This information
  93778. ** may be used by the caller, for example, to avoid having to load the entire
  93779. ** old.* record into memory when executing an UPDATE or DELETE command.
  93780. **
  93781. ** Bit 0 of the returned mask is set if the left-most column of the
  93782. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  93783. ** the second leftmost column value is required, and so on. If there
  93784. ** are more than 32 columns in the table, and at least one of the columns
  93785. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  93786. **
  93787. ** It is not possible to determine if the old.rowid or new.rowid column is
  93788. ** accessed by triggers. The caller must always assume that it is.
  93789. **
  93790. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  93791. ** applies to the old.* table. If 1, the new.* table.
  93792. **
  93793. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  93794. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  93795. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  93796. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  93797. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  93798. */
  93799. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  93800. Parse *pParse, /* Parse context */
  93801. Trigger *pTrigger, /* List of triggers on table pTab */
  93802. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  93803. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  93804. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  93805. Table *pTab, /* The table to code triggers from */
  93806. int orconf /* Default ON CONFLICT policy for trigger steps */
  93807. ){
  93808. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  93809. u32 mask = 0;
  93810. Trigger *p;
  93811. assert( isNew==1 || isNew==0 );
  93812. for(p=pTrigger; p; p=p->pNext){
  93813. if( p->op==op && (tr_tm&p->tr_tm)
  93814. && checkColumnOverlap(p->pColumns,pChanges)
  93815. ){
  93816. TriggerPrg *pPrg;
  93817. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  93818. if( pPrg ){
  93819. mask |= pPrg->aColmask[isNew];
  93820. }
  93821. }
  93822. }
  93823. return mask;
  93824. }
  93825. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  93826. /************** End of trigger.c *********************************************/
  93827. /************** Begin file update.c ******************************************/
  93828. /*
  93829. ** 2001 September 15
  93830. **
  93831. ** The author disclaims copyright to this source code. In place of
  93832. ** a legal notice, here is a blessing:
  93833. **
  93834. ** May you do good and not evil.
  93835. ** May you find forgiveness for yourself and forgive others.
  93836. ** May you share freely, never taking more than you give.
  93837. **
  93838. *************************************************************************
  93839. ** This file contains C code routines that are called by the parser
  93840. ** to handle UPDATE statements.
  93841. */
  93842. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93843. /* Forward declaration */
  93844. static void updateVirtualTable(
  93845. Parse *pParse, /* The parsing context */
  93846. SrcList *pSrc, /* The virtual table to be modified */
  93847. Table *pTab, /* The virtual table */
  93848. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  93849. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  93850. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  93851. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  93852. int onError /* ON CONFLICT strategy */
  93853. );
  93854. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  93855. /*
  93856. ** The most recently coded instruction was an OP_Column to retrieve the
  93857. ** i-th column of table pTab. This routine sets the P4 parameter of the
  93858. ** OP_Column to the default value, if any.
  93859. **
  93860. ** The default value of a column is specified by a DEFAULT clause in the
  93861. ** column definition. This was either supplied by the user when the table
  93862. ** was created, or added later to the table definition by an ALTER TABLE
  93863. ** command. If the latter, then the row-records in the table btree on disk
  93864. ** may not contain a value for the column and the default value, taken
  93865. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  93866. ** If the former, then all row-records are guaranteed to include a value
  93867. ** for the column and the P4 value is not required.
  93868. **
  93869. ** Column definitions created by an ALTER TABLE command may only have
  93870. ** literal default values specified: a number, null or a string. (If a more
  93871. ** complicated default expression value was provided, it is evaluated
  93872. ** when the ALTER TABLE is executed and one of the literal values written
  93873. ** into the sqlite_master table.)
  93874. **
  93875. ** Therefore, the P4 parameter is only required if the default value for
  93876. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  93877. ** function is capable of transforming these types of expressions into
  93878. ** sqlite3_value objects.
  93879. **
  93880. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  93881. ** on register iReg. This is used when an equivalent integer value is
  93882. ** stored in place of an 8-byte floating point value in order to save
  93883. ** space.
  93884. */
  93885. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  93886. assert( pTab!=0 );
  93887. if( !pTab->pSelect ){
  93888. sqlite3_value *pValue;
  93889. u8 enc = ENC(sqlite3VdbeDb(v));
  93890. Column *pCol = &pTab->aCol[i];
  93891. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  93892. assert( i<pTab->nCol );
  93893. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  93894. pCol->affinity, &pValue);
  93895. if( pValue ){
  93896. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  93897. }
  93898. #ifndef SQLITE_OMIT_FLOATING_POINT
  93899. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  93900. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  93901. }
  93902. #endif
  93903. }
  93904. }
  93905. /*
  93906. ** Process an UPDATE statement.
  93907. **
  93908. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  93909. ** \_______/ \________/ \______/ \________________/
  93910. * onError pTabList pChanges pWhere
  93911. */
  93912. SQLITE_PRIVATE void sqlite3Update(
  93913. Parse *pParse, /* The parser context */
  93914. SrcList *pTabList, /* The table in which we should change things */
  93915. ExprList *pChanges, /* Things to be changed */
  93916. Expr *pWhere, /* The WHERE clause. May be null */
  93917. int onError /* How to handle constraint errors */
  93918. ){
  93919. int i, j; /* Loop counters */
  93920. Table *pTab; /* The table to be updated */
  93921. int addr = 0; /* VDBE instruction address of the start of the loop */
  93922. WhereInfo *pWInfo; /* Information about the WHERE clause */
  93923. Vdbe *v; /* The virtual database engine */
  93924. Index *pIdx; /* For looping over indices */
  93925. int nIdx; /* Number of indices that need updating */
  93926. int iCur; /* VDBE Cursor number of pTab */
  93927. sqlite3 *db; /* The database structure */
  93928. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  93929. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  93930. ** an expression for the i-th column of the table.
  93931. ** aXRef[i]==-1 if the i-th column is not changed. */
  93932. int chngRowid; /* True if the record number is being changed */
  93933. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  93934. int openAll = 0; /* True if all indices need to be opened */
  93935. AuthContext sContext; /* The authorization context */
  93936. NameContext sNC; /* The name-context to resolve expressions in */
  93937. int iDb; /* Database containing the table being updated */
  93938. int okOnePass; /* True for one-pass algorithm without the FIFO */
  93939. int hasFK; /* True if foreign key processing is required */
  93940. #ifndef SQLITE_OMIT_TRIGGER
  93941. int isView; /* True when updating a view (INSTEAD OF trigger) */
  93942. Trigger *pTrigger; /* List of triggers on pTab, if required */
  93943. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  93944. #endif
  93945. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  93946. /* Register Allocations */
  93947. int regRowCount = 0; /* A count of rows changed */
  93948. int regOldRowid; /* The old rowid */
  93949. int regNewRowid; /* The new rowid */
  93950. int regNew; /* Content of the NEW.* table in triggers */
  93951. int regOld = 0; /* Content of OLD.* table in triggers */
  93952. int regRowSet = 0; /* Rowset of rows to be updated */
  93953. memset(&sContext, 0, sizeof(sContext));
  93954. db = pParse->db;
  93955. if( pParse->nErr || db->mallocFailed ){
  93956. goto update_cleanup;
  93957. }
  93958. assert( pTabList->nSrc==1 );
  93959. /* Locate the table which we want to update.
  93960. */
  93961. pTab = sqlite3SrcListLookup(pParse, pTabList);
  93962. if( pTab==0 ) goto update_cleanup;
  93963. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  93964. /* Figure out if we have any triggers and if the table being
  93965. ** updated is a view.
  93966. */
  93967. #ifndef SQLITE_OMIT_TRIGGER
  93968. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  93969. isView = pTab->pSelect!=0;
  93970. assert( pTrigger || tmask==0 );
  93971. #else
  93972. # define pTrigger 0
  93973. # define isView 0
  93974. # define tmask 0
  93975. #endif
  93976. #ifdef SQLITE_OMIT_VIEW
  93977. # undef isView
  93978. # define isView 0
  93979. #endif
  93980. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  93981. goto update_cleanup;
  93982. }
  93983. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  93984. goto update_cleanup;
  93985. }
  93986. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  93987. if( aXRef==0 ) goto update_cleanup;
  93988. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  93989. /* Allocate a cursors for the main database table and for all indices.
  93990. ** The index cursors might not be used, but if they are used they
  93991. ** need to occur right after the database cursor. So go ahead and
  93992. ** allocate enough space, just in case.
  93993. */
  93994. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  93995. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93996. pParse->nTab++;
  93997. }
  93998. /* Initialize the name-context */
  93999. memset(&sNC, 0, sizeof(sNC));
  94000. sNC.pParse = pParse;
  94001. sNC.pSrcList = pTabList;
  94002. /* Resolve the column names in all the expressions of the
  94003. ** of the UPDATE statement. Also find the column index
  94004. ** for each column to be updated in the pChanges array. For each
  94005. ** column to be updated, make sure we have authorization to change
  94006. ** that column.
  94007. */
  94008. chngRowid = 0;
  94009. for(i=0; i<pChanges->nExpr; i++){
  94010. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  94011. goto update_cleanup;
  94012. }
  94013. for(j=0; j<pTab->nCol; j++){
  94014. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  94015. if( j==pTab->iPKey ){
  94016. chngRowid = 1;
  94017. pRowidExpr = pChanges->a[i].pExpr;
  94018. }
  94019. aXRef[j] = i;
  94020. break;
  94021. }
  94022. }
  94023. if( j>=pTab->nCol ){
  94024. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  94025. chngRowid = 1;
  94026. pRowidExpr = pChanges->a[i].pExpr;
  94027. }else{
  94028. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  94029. pParse->checkSchema = 1;
  94030. goto update_cleanup;
  94031. }
  94032. }
  94033. #ifndef SQLITE_OMIT_AUTHORIZATION
  94034. {
  94035. int rc;
  94036. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  94037. pTab->aCol[j].zName, db->aDb[iDb].zName);
  94038. if( rc==SQLITE_DENY ){
  94039. goto update_cleanup;
  94040. }else if( rc==SQLITE_IGNORE ){
  94041. aXRef[j] = -1;
  94042. }
  94043. }
  94044. #endif
  94045. }
  94046. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  94047. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  94048. ** array for each index associated with table being updated. Fill in
  94049. ** the value with a register number for indices that are to be used
  94050. ** and with zero for unused indices.
  94051. */
  94052. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  94053. if( nIdx>0 ){
  94054. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  94055. if( aRegIdx==0 ) goto update_cleanup;
  94056. }
  94057. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  94058. int reg;
  94059. if( hasFK || chngRowid ){
  94060. reg = ++pParse->nMem;
  94061. }else{
  94062. reg = 0;
  94063. for(i=0; i<pIdx->nColumn; i++){
  94064. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  94065. reg = ++pParse->nMem;
  94066. break;
  94067. }
  94068. }
  94069. }
  94070. aRegIdx[j] = reg;
  94071. }
  94072. /* Begin generating code. */
  94073. v = sqlite3GetVdbe(pParse);
  94074. if( v==0 ) goto update_cleanup;
  94075. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  94076. sqlite3BeginWriteOperation(pParse, 1, iDb);
  94077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94078. /* Virtual tables must be handled separately */
  94079. if( IsVirtual(pTab) ){
  94080. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  94081. pWhere, onError);
  94082. pWhere = 0;
  94083. pTabList = 0;
  94084. goto update_cleanup;
  94085. }
  94086. #endif
  94087. /* Allocate required registers. */
  94088. regRowSet = ++pParse->nMem;
  94089. regOldRowid = regNewRowid = ++pParse->nMem;
  94090. if( pTrigger || hasFK ){
  94091. regOld = pParse->nMem + 1;
  94092. pParse->nMem += pTab->nCol;
  94093. }
  94094. if( chngRowid || pTrigger || hasFK ){
  94095. regNewRowid = ++pParse->nMem;
  94096. }
  94097. regNew = pParse->nMem + 1;
  94098. pParse->nMem += pTab->nCol;
  94099. /* Start the view context. */
  94100. if( isView ){
  94101. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  94102. }
  94103. /* If we are trying to update a view, realize that view into
  94104. ** a ephemeral table.
  94105. */
  94106. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  94107. if( isView ){
  94108. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  94109. }
  94110. #endif
  94111. /* Resolve the column names in all the expressions in the
  94112. ** WHERE clause.
  94113. */
  94114. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  94115. goto update_cleanup;
  94116. }
  94117. /* Begin the database scan
  94118. */
  94119. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  94120. pWInfo = sqlite3WhereBegin(
  94121. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  94122. );
  94123. if( pWInfo==0 ) goto update_cleanup;
  94124. okOnePass = pWInfo->okOnePass;
  94125. /* Remember the rowid of every item to be updated.
  94126. */
  94127. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  94128. if( !okOnePass ){
  94129. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  94130. }
  94131. /* End the database scan loop.
  94132. */
  94133. sqlite3WhereEnd(pWInfo);
  94134. /* Initialize the count of updated rows
  94135. */
  94136. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  94137. regRowCount = ++pParse->nMem;
  94138. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  94139. }
  94140. if( !isView ){
  94141. /*
  94142. ** Open every index that needs updating. Note that if any
  94143. ** index could potentially invoke a REPLACE conflict resolution
  94144. ** action, then we need to open all indices because we might need
  94145. ** to be deleting some records.
  94146. */
  94147. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  94148. if( onError==OE_Replace ){
  94149. openAll = 1;
  94150. }else{
  94151. openAll = 0;
  94152. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  94153. if( pIdx->onError==OE_Replace ){
  94154. openAll = 1;
  94155. break;
  94156. }
  94157. }
  94158. }
  94159. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  94160. assert( aRegIdx );
  94161. if( openAll || aRegIdx[i]>0 ){
  94162. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  94163. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  94164. (char*)pKey, P4_KEYINFO_HANDOFF);
  94165. assert( pParse->nTab>iCur+i+1 );
  94166. }
  94167. }
  94168. }
  94169. /* Top of the update loop */
  94170. if( okOnePass ){
  94171. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  94172. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  94173. sqlite3VdbeJumpHere(v, a1);
  94174. }else{
  94175. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  94176. }
  94177. /* Make cursor iCur point to the record that is being updated. If
  94178. ** this record does not exist for some reason (deleted by a trigger,
  94179. ** for example, then jump to the next iteration of the RowSet loop. */
  94180. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  94181. /* If the record number will change, set register regNewRowid to
  94182. ** contain the new value. If the record number is not being modified,
  94183. ** then regNewRowid is the same register as regOldRowid, which is
  94184. ** already populated. */
  94185. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  94186. if( chngRowid ){
  94187. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  94188. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  94189. }
  94190. /* If there are triggers on this table, populate an array of registers
  94191. ** with the required old.* column data. */
  94192. if( hasFK || pTrigger ){
  94193. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  94194. oldmask |= sqlite3TriggerColmask(pParse,
  94195. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  94196. );
  94197. for(i=0; i<pTab->nCol; i++){
  94198. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  94199. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  94200. }else{
  94201. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  94202. }
  94203. }
  94204. if( chngRowid==0 ){
  94205. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  94206. }
  94207. }
  94208. /* Populate the array of registers beginning at regNew with the new
  94209. ** row data. This array is used to check constaints, create the new
  94210. ** table and index records, and as the values for any new.* references
  94211. ** made by triggers.
  94212. **
  94213. ** If there are one or more BEFORE triggers, then do not populate the
  94214. ** registers associated with columns that are (a) not modified by
  94215. ** this UPDATE statement and (b) not accessed by new.* references. The
  94216. ** values for registers not modified by the UPDATE must be reloaded from
  94217. ** the database after the BEFORE triggers are fired anyway (as the trigger
  94218. ** may have modified them). So not loading those that are not going to
  94219. ** be used eliminates some redundant opcodes.
  94220. */
  94221. newmask = sqlite3TriggerColmask(
  94222. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  94223. );
  94224. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  94225. for(i=0; i<pTab->nCol; i++){
  94226. if( i==pTab->iPKey ){
  94227. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  94228. }else{
  94229. j = aXRef[i];
  94230. if( j>=0 ){
  94231. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  94232. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  94233. /* This branch loads the value of a column that will not be changed
  94234. ** into a register. This is done if there are no BEFORE triggers, or
  94235. ** if there are one or more BEFORE triggers that use this value via
  94236. ** a new.* reference in a trigger program.
  94237. */
  94238. testcase( i==31 );
  94239. testcase( i==32 );
  94240. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  94241. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  94242. }
  94243. }
  94244. }
  94245. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  94246. ** verified. One could argue that this is wrong.
  94247. */
  94248. if( tmask&TRIGGER_BEFORE ){
  94249. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  94250. sqlite3TableAffinityStr(v, pTab);
  94251. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  94252. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  94253. /* The row-trigger may have deleted the row being updated. In this
  94254. ** case, jump to the next row. No updates or AFTER triggers are
  94255. ** required. This behaviour - what happens when the row being updated
  94256. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  94257. ** documentation.
  94258. */
  94259. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  94260. /* If it did not delete it, the row-trigger may still have modified
  94261. ** some of the columns of the row being updated. Load the values for
  94262. ** all columns not modified by the update statement into their
  94263. ** registers in case this has happened.
  94264. */
  94265. for(i=0; i<pTab->nCol; i++){
  94266. if( aXRef[i]<0 && i!=pTab->iPKey ){
  94267. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  94268. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  94269. }
  94270. }
  94271. }
  94272. if( !isView ){
  94273. int j1; /* Address of jump instruction */
  94274. /* Do constraint checks. */
  94275. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  94276. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  94277. /* Do FK constraint checks. */
  94278. if( hasFK ){
  94279. sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
  94280. }
  94281. /* Delete the index entries associated with the current record. */
  94282. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  94283. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  94284. /* If changing the record number, delete the old record. */
  94285. if( hasFK || chngRowid ){
  94286. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  94287. }
  94288. sqlite3VdbeJumpHere(v, j1);
  94289. if( hasFK ){
  94290. sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
  94291. }
  94292. /* Insert the new index entries and the new record. */
  94293. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  94294. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  94295. ** handle rows (possibly in other tables) that refer via a foreign key
  94296. ** to the row just updated. */
  94297. if( hasFK ){
  94298. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
  94299. }
  94300. }
  94301. /* Increment the row counter
  94302. */
  94303. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  94304. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  94305. }
  94306. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  94307. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  94308. /* Repeat the above with the next record to be updated, until
  94309. ** all record selected by the WHERE clause have been updated.
  94310. */
  94311. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  94312. sqlite3VdbeJumpHere(v, addr);
  94313. /* Close all tables */
  94314. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  94315. assert( aRegIdx );
  94316. if( openAll || aRegIdx[i]>0 ){
  94317. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  94318. }
  94319. }
  94320. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  94321. /* Update the sqlite_sequence table by storing the content of the
  94322. ** maximum rowid counter values recorded while inserting into
  94323. ** autoincrement tables.
  94324. */
  94325. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  94326. sqlite3AutoincrementEnd(pParse);
  94327. }
  94328. /*
  94329. ** Return the number of rows that were changed. If this routine is
  94330. ** generating code because of a call to sqlite3NestedParse(), do not
  94331. ** invoke the callback function.
  94332. */
  94333. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  94334. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  94335. sqlite3VdbeSetNumCols(v, 1);
  94336. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  94337. }
  94338. update_cleanup:
  94339. sqlite3AuthContextPop(&sContext);
  94340. sqlite3DbFree(db, aRegIdx);
  94341. sqlite3DbFree(db, aXRef);
  94342. sqlite3SrcListDelete(db, pTabList);
  94343. sqlite3ExprListDelete(db, pChanges);
  94344. sqlite3ExprDelete(db, pWhere);
  94345. return;
  94346. }
  94347. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  94348. ** thely may interfere with compilation of other functions in this file
  94349. ** (or in another file, if this file becomes part of the amalgamation). */
  94350. #ifdef isView
  94351. #undef isView
  94352. #endif
  94353. #ifdef pTrigger
  94354. #undef pTrigger
  94355. #endif
  94356. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94357. /*
  94358. ** Generate code for an UPDATE of a virtual table.
  94359. **
  94360. ** The strategy is that we create an ephemerial table that contains
  94361. ** for each row to be changed:
  94362. **
  94363. ** (A) The original rowid of that row.
  94364. ** (B) The revised rowid for the row. (note1)
  94365. ** (C) The content of every column in the row.
  94366. **
  94367. ** Then we loop over this ephemeral table and for each row in
  94368. ** the ephermeral table call VUpdate.
  94369. **
  94370. ** When finished, drop the ephemeral table.
  94371. **
  94372. ** (note1) Actually, if we know in advance that (A) is always the same
  94373. ** as (B) we only store (A), then duplicate (A) when pulling
  94374. ** it out of the ephemeral table before calling VUpdate.
  94375. */
  94376. static void updateVirtualTable(
  94377. Parse *pParse, /* The parsing context */
  94378. SrcList *pSrc, /* The virtual table to be modified */
  94379. Table *pTab, /* The virtual table */
  94380. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  94381. Expr *pRowid, /* Expression used to recompute the rowid */
  94382. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  94383. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  94384. int onError /* ON CONFLICT strategy */
  94385. ){
  94386. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  94387. ExprList *pEList = 0; /* The result set of the SELECT statement */
  94388. Select *pSelect = 0; /* The SELECT statement */
  94389. Expr *pExpr; /* Temporary expression */
  94390. int ephemTab; /* Table holding the result of the SELECT */
  94391. int i; /* Loop counter */
  94392. int addr; /* Address of top of loop */
  94393. int iReg; /* First register in set passed to OP_VUpdate */
  94394. sqlite3 *db = pParse->db; /* Database connection */
  94395. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  94396. SelectDest dest;
  94397. /* Construct the SELECT statement that will find the new values for
  94398. ** all updated rows.
  94399. */
  94400. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  94401. if( pRowid ){
  94402. pEList = sqlite3ExprListAppend(pParse, pEList,
  94403. sqlite3ExprDup(db, pRowid, 0));
  94404. }
  94405. assert( pTab->iPKey<0 );
  94406. for(i=0; i<pTab->nCol; i++){
  94407. if( aXRef[i]>=0 ){
  94408. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  94409. }else{
  94410. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  94411. }
  94412. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  94413. }
  94414. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  94415. /* Create the ephemeral table into which the update results will
  94416. ** be stored.
  94417. */
  94418. assert( v );
  94419. ephemTab = pParse->nTab++;
  94420. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  94421. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  94422. /* fill the ephemeral table
  94423. */
  94424. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  94425. sqlite3Select(pParse, pSelect, &dest);
  94426. /* Generate code to scan the ephemeral table and call VUpdate. */
  94427. iReg = ++pParse->nMem;
  94428. pParse->nMem += pTab->nCol+1;
  94429. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  94430. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  94431. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  94432. for(i=0; i<pTab->nCol; i++){
  94433. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  94434. }
  94435. sqlite3VtabMakeWritable(pParse, pTab);
  94436. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  94437. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  94438. sqlite3MayAbort(pParse);
  94439. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  94440. sqlite3VdbeJumpHere(v, addr);
  94441. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  94442. /* Cleanup */
  94443. sqlite3SelectDelete(db, pSelect);
  94444. }
  94445. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  94446. /************** End of update.c **********************************************/
  94447. /************** Begin file vacuum.c ******************************************/
  94448. /*
  94449. ** 2003 April 6
  94450. **
  94451. ** The author disclaims copyright to this source code. In place of
  94452. ** a legal notice, here is a blessing:
  94453. **
  94454. ** May you do good and not evil.
  94455. ** May you find forgiveness for yourself and forgive others.
  94456. ** May you share freely, never taking more than you give.
  94457. **
  94458. *************************************************************************
  94459. ** This file contains code used to implement the VACUUM command.
  94460. **
  94461. ** Most of the code in this file may be omitted by defining the
  94462. ** SQLITE_OMIT_VACUUM macro.
  94463. */
  94464. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  94465. /*
  94466. ** Finalize a prepared statement. If there was an error, store the
  94467. ** text of the error message in *pzErrMsg. Return the result code.
  94468. */
  94469. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  94470. int rc;
  94471. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  94472. if( rc ){
  94473. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  94474. }
  94475. return rc;
  94476. }
  94477. /*
  94478. ** Execute zSql on database db. Return an error code.
  94479. */
  94480. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  94481. sqlite3_stmt *pStmt;
  94482. VVA_ONLY( int rc; )
  94483. if( !zSql ){
  94484. return SQLITE_NOMEM;
  94485. }
  94486. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  94487. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  94488. return sqlite3_errcode(db);
  94489. }
  94490. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  94491. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  94492. return vacuumFinalize(db, pStmt, pzErrMsg);
  94493. }
  94494. /*
  94495. ** Execute zSql on database db. The statement returns exactly
  94496. ** one column. Execute this as SQL on the same database.
  94497. */
  94498. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  94499. sqlite3_stmt *pStmt;
  94500. int rc;
  94501. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  94502. if( rc!=SQLITE_OK ) return rc;
  94503. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  94504. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  94505. if( rc!=SQLITE_OK ){
  94506. vacuumFinalize(db, pStmt, pzErrMsg);
  94507. return rc;
  94508. }
  94509. }
  94510. return vacuumFinalize(db, pStmt, pzErrMsg);
  94511. }
  94512. /*
  94513. ** The non-standard VACUUM command is used to clean up the database,
  94514. ** collapse free space, etc. It is modelled after the VACUUM command
  94515. ** in PostgreSQL.
  94516. **
  94517. ** In version 1.0.x of SQLite, the VACUUM command would call
  94518. ** gdbm_reorganize() on all the database tables. But beginning
  94519. ** with 2.0.0, SQLite no longer uses GDBM so this command has
  94520. ** become a no-op.
  94521. */
  94522. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  94523. Vdbe *v = sqlite3GetVdbe(pParse);
  94524. if( v ){
  94525. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  94526. sqlite3VdbeUsesBtree(v, 0);
  94527. }
  94528. return;
  94529. }
  94530. /*
  94531. ** This routine implements the OP_Vacuum opcode of the VDBE.
  94532. */
  94533. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  94534. int rc = SQLITE_OK; /* Return code from service routines */
  94535. Btree *pMain; /* The database being vacuumed */
  94536. Btree *pTemp; /* The temporary database we vacuum into */
  94537. char *zSql = 0; /* SQL statements */
  94538. int saved_flags; /* Saved value of the db->flags */
  94539. int saved_nChange; /* Saved value of db->nChange */
  94540. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  94541. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  94542. Db *pDb = 0; /* Database to detach at end of vacuum */
  94543. int isMemDb; /* True if vacuuming a :memory: database */
  94544. int nRes; /* Bytes of reserved space at the end of each page */
  94545. int nDb; /* Number of attached databases */
  94546. if( !db->autoCommit ){
  94547. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  94548. return SQLITE_ERROR;
  94549. }
  94550. if( db->activeVdbeCnt>1 ){
  94551. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  94552. return SQLITE_ERROR;
  94553. }
  94554. /* Save the current value of the database flags so that it can be
  94555. ** restored before returning. Then set the writable-schema flag, and
  94556. ** disable CHECK and foreign key constraints. */
  94557. saved_flags = db->flags;
  94558. saved_nChange = db->nChange;
  94559. saved_nTotalChange = db->nTotalChange;
  94560. saved_xTrace = db->xTrace;
  94561. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  94562. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  94563. db->xTrace = 0;
  94564. pMain = db->aDb[0].pBt;
  94565. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  94566. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  94567. ** can be set to 'off' for this file, as it is not recovered if a crash
  94568. ** occurs anyway. The integrity of the database is maintained by a
  94569. ** (possibly synchronous) transaction opened on the main database before
  94570. ** sqlite3BtreeCopyFile() is called.
  94571. **
  94572. ** An optimisation would be to use a non-journaled pager.
  94573. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  94574. ** that actually made the VACUUM run slower. Very little journalling
  94575. ** actually occurs when doing a vacuum since the vacuum_db is initially
  94576. ** empty. Only the journal header is written. Apparently it takes more
  94577. ** time to parse and run the PRAGMA to turn journalling off than it does
  94578. ** to write the journal header file.
  94579. */
  94580. nDb = db->nDb;
  94581. if( sqlite3TempInMemory(db) ){
  94582. zSql = "ATTACH ':memory:' AS vacuum_db;";
  94583. }else{
  94584. zSql = "ATTACH '' AS vacuum_db;";
  94585. }
  94586. rc = execSql(db, pzErrMsg, zSql);
  94587. if( db->nDb>nDb ){
  94588. pDb = &db->aDb[db->nDb-1];
  94589. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  94590. }
  94591. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94592. pTemp = db->aDb[db->nDb-1].pBt;
  94593. /* The call to execSql() to attach the temp database has left the file
  94594. ** locked (as there was more than one active statement when the transaction
  94595. ** to read the schema was concluded. Unlock it here so that this doesn't
  94596. ** cause problems for the call to BtreeSetPageSize() below. */
  94597. sqlite3BtreeCommit(pTemp);
  94598. nRes = sqlite3BtreeGetReserve(pMain);
  94599. /* A VACUUM cannot change the pagesize of an encrypted database. */
  94600. #ifdef SQLITE_HAS_CODEC
  94601. if( db->nextPagesize ){
  94602. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  94603. int nKey;
  94604. char *zKey;
  94605. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  94606. if( nKey ) db->nextPagesize = 0;
  94607. }
  94608. #endif
  94609. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  94610. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94611. /* Begin a transaction and take an exclusive lock on the main database
  94612. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  94613. ** to ensure that we do not try to change the page-size on a WAL database.
  94614. */
  94615. rc = execSql(db, pzErrMsg, "BEGIN;");
  94616. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94617. rc = sqlite3BtreeBeginTrans(pMain, 2);
  94618. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94619. /* Do not attempt to change the page size for a WAL database */
  94620. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  94621. ==PAGER_JOURNALMODE_WAL ){
  94622. db->nextPagesize = 0;
  94623. }
  94624. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  94625. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  94626. || NEVER(db->mallocFailed)
  94627. ){
  94628. rc = SQLITE_NOMEM;
  94629. goto end_of_vacuum;
  94630. }
  94631. #ifndef SQLITE_OMIT_AUTOVACUUM
  94632. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  94633. sqlite3BtreeGetAutoVacuum(pMain));
  94634. #endif
  94635. /* Query the schema of the main database. Create a mirror schema
  94636. ** in the temporary database.
  94637. */
  94638. rc = execExecSql(db, pzErrMsg,
  94639. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  94640. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  94641. " AND rootpage>0"
  94642. );
  94643. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94644. rc = execExecSql(db, pzErrMsg,
  94645. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  94646. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  94647. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94648. rc = execExecSql(db, pzErrMsg,
  94649. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  94650. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  94651. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94652. /* Loop through the tables in the main database. For each, do
  94653. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  94654. ** the contents to the temporary database.
  94655. */
  94656. rc = execExecSql(db, pzErrMsg,
  94657. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  94658. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  94659. "FROM main.sqlite_master "
  94660. "WHERE type = 'table' AND name!='sqlite_sequence' "
  94661. " AND rootpage>0"
  94662. );
  94663. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94664. /* Copy over the sequence table
  94665. */
  94666. rc = execExecSql(db, pzErrMsg,
  94667. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  94668. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  94669. );
  94670. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94671. rc = execExecSql(db, pzErrMsg,
  94672. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  94673. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  94674. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  94675. );
  94676. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94677. /* Copy the triggers, views, and virtual tables from the main database
  94678. ** over to the temporary database. None of these objects has any
  94679. ** associated storage, so all we have to do is copy their entries
  94680. ** from the SQLITE_MASTER table.
  94681. */
  94682. rc = execSql(db, pzErrMsg,
  94683. "INSERT INTO vacuum_db.sqlite_master "
  94684. " SELECT type, name, tbl_name, rootpage, sql"
  94685. " FROM main.sqlite_master"
  94686. " WHERE type='view' OR type='trigger'"
  94687. " OR (type='table' AND rootpage=0)"
  94688. );
  94689. if( rc ) goto end_of_vacuum;
  94690. /* At this point, there is a write transaction open on both the
  94691. ** vacuum database and the main database. Assuming no error occurs,
  94692. ** both transactions are closed by this block - the main database
  94693. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  94694. ** call to sqlite3BtreeCommit().
  94695. */
  94696. {
  94697. u32 meta;
  94698. int i;
  94699. /* This array determines which meta meta values are preserved in the
  94700. ** vacuum. Even entries are the meta value number and odd entries
  94701. ** are an increment to apply to the meta value after the vacuum.
  94702. ** The increment is used to increase the schema cookie so that other
  94703. ** connections to the same database will know to reread the schema.
  94704. */
  94705. static const unsigned char aCopy[] = {
  94706. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  94707. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  94708. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  94709. BTREE_USER_VERSION, 0, /* Preserve the user version */
  94710. };
  94711. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  94712. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  94713. /* Copy Btree meta values */
  94714. for(i=0; i<ArraySize(aCopy); i+=2){
  94715. /* GetMeta() and UpdateMeta() cannot fail in this context because
  94716. ** we already have page 1 loaded into cache and marked dirty. */
  94717. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  94718. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  94719. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  94720. }
  94721. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  94722. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94723. rc = sqlite3BtreeCommit(pTemp);
  94724. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  94725. #ifndef SQLITE_OMIT_AUTOVACUUM
  94726. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  94727. #endif
  94728. }
  94729. assert( rc==SQLITE_OK );
  94730. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  94731. end_of_vacuum:
  94732. /* Restore the original value of db->flags */
  94733. db->flags = saved_flags;
  94734. db->nChange = saved_nChange;
  94735. db->nTotalChange = saved_nTotalChange;
  94736. db->xTrace = saved_xTrace;
  94737. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  94738. /* Currently there is an SQL level transaction open on the vacuum
  94739. ** database. No locks are held on any other files (since the main file
  94740. ** was committed at the btree level). So it safe to end the transaction
  94741. ** by manually setting the autoCommit flag to true and detaching the
  94742. ** vacuum database. The vacuum_db journal file is deleted when the pager
  94743. ** is closed by the DETACH.
  94744. */
  94745. db->autoCommit = 1;
  94746. if( pDb ){
  94747. sqlite3BtreeClose(pDb->pBt);
  94748. pDb->pBt = 0;
  94749. pDb->pSchema = 0;
  94750. }
  94751. /* This both clears the schemas and reduces the size of the db->aDb[]
  94752. ** array. */
  94753. sqlite3ResetAllSchemasOfConnection(db);
  94754. return rc;
  94755. }
  94756. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  94757. /************** End of vacuum.c **********************************************/
  94758. /************** Begin file vtab.c ********************************************/
  94759. /*
  94760. ** 2006 June 10
  94761. **
  94762. ** The author disclaims copyright to this source code. In place of
  94763. ** a legal notice, here is a blessing:
  94764. **
  94765. ** May you do good and not evil.
  94766. ** May you find forgiveness for yourself and forgive others.
  94767. ** May you share freely, never taking more than you give.
  94768. **
  94769. *************************************************************************
  94770. ** This file contains code used to help implement virtual tables.
  94771. */
  94772. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94773. /*
  94774. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  94775. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  94776. ** this struct allocated on the stack. It is used by the implementation of
  94777. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  94778. ** are invoked only from within xCreate and xConnect methods.
  94779. */
  94780. struct VtabCtx {
  94781. VTable *pVTable; /* The virtual table being constructed */
  94782. Table *pTab; /* The Table object to which the virtual table belongs */
  94783. };
  94784. /*
  94785. ** The actual function that does the work of creating a new module.
  94786. ** This function implements the sqlite3_create_module() and
  94787. ** sqlite3_create_module_v2() interfaces.
  94788. */
  94789. static int createModule(
  94790. sqlite3 *db, /* Database in which module is registered */
  94791. const char *zName, /* Name assigned to this module */
  94792. const sqlite3_module *pModule, /* The definition of the module */
  94793. void *pAux, /* Context pointer for xCreate/xConnect */
  94794. void (*xDestroy)(void *) /* Module destructor function */
  94795. ){
  94796. int rc = SQLITE_OK;
  94797. int nName;
  94798. sqlite3_mutex_enter(db->mutex);
  94799. nName = sqlite3Strlen30(zName);
  94800. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  94801. rc = SQLITE_MISUSE_BKPT;
  94802. }else{
  94803. Module *pMod;
  94804. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  94805. if( pMod ){
  94806. Module *pDel;
  94807. char *zCopy = (char *)(&pMod[1]);
  94808. memcpy(zCopy, zName, nName+1);
  94809. pMod->zName = zCopy;
  94810. pMod->pModule = pModule;
  94811. pMod->pAux = pAux;
  94812. pMod->xDestroy = xDestroy;
  94813. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  94814. assert( pDel==0 || pDel==pMod );
  94815. if( pDel ){
  94816. db->mallocFailed = 1;
  94817. sqlite3DbFree(db, pDel);
  94818. }
  94819. }
  94820. }
  94821. rc = sqlite3ApiExit(db, rc);
  94822. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  94823. sqlite3_mutex_leave(db->mutex);
  94824. return rc;
  94825. }
  94826. /*
  94827. ** External API function used to create a new virtual-table module.
  94828. */
  94829. SQLITE_API int sqlite3_create_module(
  94830. sqlite3 *db, /* Database in which module is registered */
  94831. const char *zName, /* Name assigned to this module */
  94832. const sqlite3_module *pModule, /* The definition of the module */
  94833. void *pAux /* Context pointer for xCreate/xConnect */
  94834. ){
  94835. return createModule(db, zName, pModule, pAux, 0);
  94836. }
  94837. /*
  94838. ** External API function used to create a new virtual-table module.
  94839. */
  94840. SQLITE_API int sqlite3_create_module_v2(
  94841. sqlite3 *db, /* Database in which module is registered */
  94842. const char *zName, /* Name assigned to this module */
  94843. const sqlite3_module *pModule, /* The definition of the module */
  94844. void *pAux, /* Context pointer for xCreate/xConnect */
  94845. void (*xDestroy)(void *) /* Module destructor function */
  94846. ){
  94847. return createModule(db, zName, pModule, pAux, xDestroy);
  94848. }
  94849. /*
  94850. ** Lock the virtual table so that it cannot be disconnected.
  94851. ** Locks nest. Every lock should have a corresponding unlock.
  94852. ** If an unlock is omitted, resources leaks will occur.
  94853. **
  94854. ** If a disconnect is attempted while a virtual table is locked,
  94855. ** the disconnect is deferred until all locks have been removed.
  94856. */
  94857. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  94858. pVTab->nRef++;
  94859. }
  94860. /*
  94861. ** pTab is a pointer to a Table structure representing a virtual-table.
  94862. ** Return a pointer to the VTable object used by connection db to access
  94863. ** this virtual-table, if one has been created, or NULL otherwise.
  94864. */
  94865. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  94866. VTable *pVtab;
  94867. assert( IsVirtual(pTab) );
  94868. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  94869. return pVtab;
  94870. }
  94871. /*
  94872. ** Decrement the ref-count on a virtual table object. When the ref-count
  94873. ** reaches zero, call the xDisconnect() method to delete the object.
  94874. */
  94875. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  94876. sqlite3 *db = pVTab->db;
  94877. assert( db );
  94878. assert( pVTab->nRef>0 );
  94879. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  94880. pVTab->nRef--;
  94881. if( pVTab->nRef==0 ){
  94882. sqlite3_vtab *p = pVTab->pVtab;
  94883. if( p ){
  94884. p->pModule->xDisconnect(p);
  94885. }
  94886. sqlite3DbFree(db, pVTab);
  94887. }
  94888. }
  94889. /*
  94890. ** Table p is a virtual table. This function moves all elements in the
  94891. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  94892. ** database connections to be disconnected at the next opportunity.
  94893. ** Except, if argument db is not NULL, then the entry associated with
  94894. ** connection db is left in the p->pVTable list.
  94895. */
  94896. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  94897. VTable *pRet = 0;
  94898. VTable *pVTable = p->pVTable;
  94899. p->pVTable = 0;
  94900. /* Assert that the mutex (if any) associated with the BtShared database
  94901. ** that contains table p is held by the caller. See header comments
  94902. ** above function sqlite3VtabUnlockList() for an explanation of why
  94903. ** this makes it safe to access the sqlite3.pDisconnect list of any
  94904. ** database connection that may have an entry in the p->pVTable list.
  94905. */
  94906. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  94907. while( pVTable ){
  94908. sqlite3 *db2 = pVTable->db;
  94909. VTable *pNext = pVTable->pNext;
  94910. assert( db2 );
  94911. if( db2==db ){
  94912. pRet = pVTable;
  94913. p->pVTable = pRet;
  94914. pRet->pNext = 0;
  94915. }else{
  94916. pVTable->pNext = db2->pDisconnect;
  94917. db2->pDisconnect = pVTable;
  94918. }
  94919. pVTable = pNext;
  94920. }
  94921. assert( !db || pRet );
  94922. return pRet;
  94923. }
  94924. /*
  94925. ** Table *p is a virtual table. This function removes the VTable object
  94926. ** for table *p associated with database connection db from the linked
  94927. ** list in p->pVTab. It also decrements the VTable ref count. This is
  94928. ** used when closing database connection db to free all of its VTable
  94929. ** objects without disturbing the rest of the Schema object (which may
  94930. ** be being used by other shared-cache connections).
  94931. */
  94932. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  94933. VTable **ppVTab;
  94934. assert( IsVirtual(p) );
  94935. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94936. assert( sqlite3_mutex_held(db->mutex) );
  94937. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  94938. if( (*ppVTab)->db==db ){
  94939. VTable *pVTab = *ppVTab;
  94940. *ppVTab = pVTab->pNext;
  94941. sqlite3VtabUnlock(pVTab);
  94942. break;
  94943. }
  94944. }
  94945. }
  94946. /*
  94947. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  94948. **
  94949. ** This function may only be called when the mutexes associated with all
  94950. ** shared b-tree databases opened using connection db are held by the
  94951. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  94952. ** sqlite3.pDisconnect list is accessed only as follows:
  94953. **
  94954. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  94955. ** associated with the database handle itself must be held.
  94956. **
  94957. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  94958. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  94959. ** associated with the database the virtual table is stored in is held
  94960. ** or, if the virtual table is stored in a non-sharable database, then
  94961. ** the database handle mutex is held.
  94962. **
  94963. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  94964. ** by multiple threads. It is thread-safe.
  94965. */
  94966. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  94967. VTable *p = db->pDisconnect;
  94968. db->pDisconnect = 0;
  94969. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94970. assert( sqlite3_mutex_held(db->mutex) );
  94971. if( p ){
  94972. sqlite3ExpirePreparedStatements(db);
  94973. do {
  94974. VTable *pNext = p->pNext;
  94975. sqlite3VtabUnlock(p);
  94976. p = pNext;
  94977. }while( p );
  94978. }
  94979. }
  94980. /*
  94981. ** Clear any and all virtual-table information from the Table record.
  94982. ** This routine is called, for example, just before deleting the Table
  94983. ** record.
  94984. **
  94985. ** Since it is a virtual-table, the Table structure contains a pointer
  94986. ** to the head of a linked list of VTable structures. Each VTable
  94987. ** structure is associated with a single sqlite3* user of the schema.
  94988. ** The reference count of the VTable structure associated with database
  94989. ** connection db is decremented immediately (which may lead to the
  94990. ** structure being xDisconnected and free). Any other VTable structures
  94991. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  94992. ** database connection.
  94993. */
  94994. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  94995. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  94996. if( p->azModuleArg ){
  94997. int i;
  94998. for(i=0; i<p->nModuleArg; i++){
  94999. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  95000. }
  95001. sqlite3DbFree(db, p->azModuleArg);
  95002. }
  95003. }
  95004. /*
  95005. ** Add a new module argument to pTable->azModuleArg[].
  95006. ** The string is not copied - the pointer is stored. The
  95007. ** string will be freed automatically when the table is
  95008. ** deleted.
  95009. */
  95010. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  95011. int i = pTable->nModuleArg++;
  95012. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  95013. char **azModuleArg;
  95014. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  95015. if( azModuleArg==0 ){
  95016. int j;
  95017. for(j=0; j<i; j++){
  95018. sqlite3DbFree(db, pTable->azModuleArg[j]);
  95019. }
  95020. sqlite3DbFree(db, zArg);
  95021. sqlite3DbFree(db, pTable->azModuleArg);
  95022. pTable->nModuleArg = 0;
  95023. }else{
  95024. azModuleArg[i] = zArg;
  95025. azModuleArg[i+1] = 0;
  95026. }
  95027. pTable->azModuleArg = azModuleArg;
  95028. }
  95029. /*
  95030. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  95031. ** statement. The module name has been parsed, but the optional list
  95032. ** of parameters that follow the module name are still pending.
  95033. */
  95034. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  95035. Parse *pParse, /* Parsing context */
  95036. Token *pName1, /* Name of new table, or database name */
  95037. Token *pName2, /* Name of new table or NULL */
  95038. Token *pModuleName, /* Name of the module for the virtual table */
  95039. int ifNotExists /* No error if the table already exists */
  95040. ){
  95041. int iDb; /* The database the table is being created in */
  95042. Table *pTable; /* The new virtual table */
  95043. sqlite3 *db; /* Database connection */
  95044. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  95045. pTable = pParse->pNewTable;
  95046. if( pTable==0 ) return;
  95047. assert( 0==pTable->pIndex );
  95048. db = pParse->db;
  95049. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  95050. assert( iDb>=0 );
  95051. pTable->tabFlags |= TF_Virtual;
  95052. pTable->nModuleArg = 0;
  95053. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  95054. addModuleArgument(db, pTable, 0);
  95055. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  95056. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  95057. #ifndef SQLITE_OMIT_AUTHORIZATION
  95058. /* Creating a virtual table invokes the authorization callback twice.
  95059. ** The first invocation, to obtain permission to INSERT a row into the
  95060. ** sqlite_master table, has already been made by sqlite3StartTable().
  95061. ** The second call, to obtain permission to create the table, is made now.
  95062. */
  95063. if( pTable->azModuleArg ){
  95064. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  95065. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  95066. }
  95067. #endif
  95068. }
  95069. /*
  95070. ** This routine takes the module argument that has been accumulating
  95071. ** in pParse->zArg[] and appends it to the list of arguments on the
  95072. ** virtual table currently under construction in pParse->pTable.
  95073. */
  95074. static void addArgumentToVtab(Parse *pParse){
  95075. if( pParse->sArg.z && pParse->pNewTable ){
  95076. const char *z = (const char*)pParse->sArg.z;
  95077. int n = pParse->sArg.n;
  95078. sqlite3 *db = pParse->db;
  95079. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  95080. }
  95081. }
  95082. /*
  95083. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  95084. ** has been completely parsed.
  95085. */
  95086. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  95087. Table *pTab = pParse->pNewTable; /* The table being constructed */
  95088. sqlite3 *db = pParse->db; /* The database connection */
  95089. if( pTab==0 ) return;
  95090. addArgumentToVtab(pParse);
  95091. pParse->sArg.z = 0;
  95092. if( pTab->nModuleArg<1 ) return;
  95093. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  95094. ** first time (in other words if the virtual table is actually being
  95095. ** created now instead of just being read out of sqlite_master) then
  95096. ** do additional initialization work and store the statement text
  95097. ** in the sqlite_master table.
  95098. */
  95099. if( !db->init.busy ){
  95100. char *zStmt;
  95101. char *zWhere;
  95102. int iDb;
  95103. Vdbe *v;
  95104. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  95105. if( pEnd ){
  95106. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  95107. }
  95108. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  95109. /* A slot for the record has already been allocated in the
  95110. ** SQLITE_MASTER table. We just need to update that slot with all
  95111. ** the information we've collected.
  95112. **
  95113. ** The VM register number pParse->regRowid holds the rowid of an
  95114. ** entry in the sqlite_master table tht was created for this vtab
  95115. ** by sqlite3StartTable().
  95116. */
  95117. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95118. sqlite3NestedParse(pParse,
  95119. "UPDATE %Q.%s "
  95120. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  95121. "WHERE rowid=#%d",
  95122. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  95123. pTab->zName,
  95124. pTab->zName,
  95125. zStmt,
  95126. pParse->regRowid
  95127. );
  95128. sqlite3DbFree(db, zStmt);
  95129. v = sqlite3GetVdbe(pParse);
  95130. sqlite3ChangeCookie(pParse, iDb);
  95131. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  95132. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  95133. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  95134. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  95135. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  95136. }
  95137. /* If we are rereading the sqlite_master table create the in-memory
  95138. ** record of the table. The xConnect() method is not called until
  95139. ** the first time the virtual table is used in an SQL statement. This
  95140. ** allows a schema that contains virtual tables to be loaded before
  95141. ** the required virtual table implementations are registered. */
  95142. else {
  95143. Table *pOld;
  95144. Schema *pSchema = pTab->pSchema;
  95145. const char *zName = pTab->zName;
  95146. int nName = sqlite3Strlen30(zName);
  95147. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  95148. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  95149. if( pOld ){
  95150. db->mallocFailed = 1;
  95151. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  95152. return;
  95153. }
  95154. pParse->pNewTable = 0;
  95155. }
  95156. }
  95157. /*
  95158. ** The parser calls this routine when it sees the first token
  95159. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  95160. */
  95161. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  95162. addArgumentToVtab(pParse);
  95163. pParse->sArg.z = 0;
  95164. pParse->sArg.n = 0;
  95165. }
  95166. /*
  95167. ** The parser calls this routine for each token after the first token
  95168. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  95169. */
  95170. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  95171. Token *pArg = &pParse->sArg;
  95172. if( pArg->z==0 ){
  95173. pArg->z = p->z;
  95174. pArg->n = p->n;
  95175. }else{
  95176. assert(pArg->z < p->z);
  95177. pArg->n = (int)(&p->z[p->n] - pArg->z);
  95178. }
  95179. }
  95180. /*
  95181. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  95182. ** pointer to the function to invoke is passed as the fourth parameter
  95183. ** to this procedure.
  95184. */
  95185. static int vtabCallConstructor(
  95186. sqlite3 *db,
  95187. Table *pTab,
  95188. Module *pMod,
  95189. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  95190. char **pzErr
  95191. ){
  95192. VtabCtx sCtx, *pPriorCtx;
  95193. VTable *pVTable;
  95194. int rc;
  95195. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  95196. int nArg = pTab->nModuleArg;
  95197. char *zErr = 0;
  95198. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  95199. int iDb;
  95200. if( !zModuleName ){
  95201. return SQLITE_NOMEM;
  95202. }
  95203. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  95204. if( !pVTable ){
  95205. sqlite3DbFree(db, zModuleName);
  95206. return SQLITE_NOMEM;
  95207. }
  95208. pVTable->db = db;
  95209. pVTable->pMod = pMod;
  95210. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95211. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  95212. /* Invoke the virtual table constructor */
  95213. assert( &db->pVtabCtx );
  95214. assert( xConstruct );
  95215. sCtx.pTab = pTab;
  95216. sCtx.pVTable = pVTable;
  95217. pPriorCtx = db->pVtabCtx;
  95218. db->pVtabCtx = &sCtx;
  95219. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  95220. db->pVtabCtx = pPriorCtx;
  95221. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  95222. if( SQLITE_OK!=rc ){
  95223. if( zErr==0 ){
  95224. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  95225. }else {
  95226. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  95227. sqlite3_free(zErr);
  95228. }
  95229. sqlite3DbFree(db, pVTable);
  95230. }else if( ALWAYS(pVTable->pVtab) ){
  95231. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  95232. ** the sqlite3_vtab object if successful. */
  95233. pVTable->pVtab->pModule = pMod->pModule;
  95234. pVTable->nRef = 1;
  95235. if( sCtx.pTab ){
  95236. const char *zFormat = "vtable constructor did not declare schema: %s";
  95237. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  95238. sqlite3VtabUnlock(pVTable);
  95239. rc = SQLITE_ERROR;
  95240. }else{
  95241. int iCol;
  95242. /* If everything went according to plan, link the new VTable structure
  95243. ** into the linked list headed by pTab->pVTable. Then loop through the
  95244. ** columns of the table to see if any of them contain the token "hidden".
  95245. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  95246. ** the type string. */
  95247. pVTable->pNext = pTab->pVTable;
  95248. pTab->pVTable = pVTable;
  95249. for(iCol=0; iCol<pTab->nCol; iCol++){
  95250. char *zType = pTab->aCol[iCol].zType;
  95251. int nType;
  95252. int i = 0;
  95253. if( !zType ) continue;
  95254. nType = sqlite3Strlen30(zType);
  95255. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  95256. for(i=0; i<nType; i++){
  95257. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  95258. && (zType[i+7]=='\0' || zType[i+7]==' ')
  95259. ){
  95260. i++;
  95261. break;
  95262. }
  95263. }
  95264. }
  95265. if( i<nType ){
  95266. int j;
  95267. int nDel = 6 + (zType[i+6] ? 1 : 0);
  95268. for(j=i; (j+nDel)<=nType; j++){
  95269. zType[j] = zType[j+nDel];
  95270. }
  95271. if( zType[i]=='\0' && i>0 ){
  95272. assert(zType[i-1]==' ');
  95273. zType[i-1] = '\0';
  95274. }
  95275. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  95276. }
  95277. }
  95278. }
  95279. }
  95280. sqlite3DbFree(db, zModuleName);
  95281. return rc;
  95282. }
  95283. /*
  95284. ** This function is invoked by the parser to call the xConnect() method
  95285. ** of the virtual table pTab. If an error occurs, an error code is returned
  95286. ** and an error left in pParse.
  95287. **
  95288. ** This call is a no-op if table pTab is not a virtual table.
  95289. */
  95290. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  95291. sqlite3 *db = pParse->db;
  95292. const char *zMod;
  95293. Module *pMod;
  95294. int rc;
  95295. assert( pTab );
  95296. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  95297. return SQLITE_OK;
  95298. }
  95299. /* Locate the required virtual table module */
  95300. zMod = pTab->azModuleArg[0];
  95301. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  95302. if( !pMod ){
  95303. const char *zModule = pTab->azModuleArg[0];
  95304. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  95305. rc = SQLITE_ERROR;
  95306. }else{
  95307. char *zErr = 0;
  95308. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  95309. if( rc!=SQLITE_OK ){
  95310. sqlite3ErrorMsg(pParse, "%s", zErr);
  95311. }
  95312. sqlite3DbFree(db, zErr);
  95313. }
  95314. return rc;
  95315. }
  95316. /*
  95317. ** Grow the db->aVTrans[] array so that there is room for at least one
  95318. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  95319. */
  95320. static int growVTrans(sqlite3 *db){
  95321. const int ARRAY_INCR = 5;
  95322. /* Grow the sqlite3.aVTrans array if required */
  95323. if( (db->nVTrans%ARRAY_INCR)==0 ){
  95324. VTable **aVTrans;
  95325. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  95326. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  95327. if( !aVTrans ){
  95328. return SQLITE_NOMEM;
  95329. }
  95330. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  95331. db->aVTrans = aVTrans;
  95332. }
  95333. return SQLITE_OK;
  95334. }
  95335. /*
  95336. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  95337. ** have already been reserved using growVTrans().
  95338. */
  95339. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  95340. /* Add pVtab to the end of sqlite3.aVTrans */
  95341. db->aVTrans[db->nVTrans++] = pVTab;
  95342. sqlite3VtabLock(pVTab);
  95343. }
  95344. /*
  95345. ** This function is invoked by the vdbe to call the xCreate method
  95346. ** of the virtual table named zTab in database iDb.
  95347. **
  95348. ** If an error occurs, *pzErr is set to point an an English language
  95349. ** description of the error and an SQLITE_XXX error code is returned.
  95350. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  95351. */
  95352. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  95353. int rc = SQLITE_OK;
  95354. Table *pTab;
  95355. Module *pMod;
  95356. const char *zMod;
  95357. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  95358. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  95359. /* Locate the required virtual table module */
  95360. zMod = pTab->azModuleArg[0];
  95361. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  95362. /* If the module has been registered and includes a Create method,
  95363. ** invoke it now. If the module has not been registered, return an
  95364. ** error. Otherwise, do nothing.
  95365. */
  95366. if( !pMod ){
  95367. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  95368. rc = SQLITE_ERROR;
  95369. }else{
  95370. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  95371. }
  95372. /* Justification of ALWAYS(): The xConstructor method is required to
  95373. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  95374. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  95375. rc = growVTrans(db);
  95376. if( rc==SQLITE_OK ){
  95377. addToVTrans(db, sqlite3GetVTable(db, pTab));
  95378. }
  95379. }
  95380. return rc;
  95381. }
  95382. /*
  95383. ** This function is used to set the schema of a virtual table. It is only
  95384. ** valid to call this function from within the xCreate() or xConnect() of a
  95385. ** virtual table module.
  95386. */
  95387. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  95388. Parse *pParse;
  95389. int rc = SQLITE_OK;
  95390. Table *pTab;
  95391. char *zErr = 0;
  95392. sqlite3_mutex_enter(db->mutex);
  95393. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  95394. sqlite3Error(db, SQLITE_MISUSE, 0);
  95395. sqlite3_mutex_leave(db->mutex);
  95396. return SQLITE_MISUSE_BKPT;
  95397. }
  95398. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  95399. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  95400. if( pParse==0 ){
  95401. rc = SQLITE_NOMEM;
  95402. }else{
  95403. pParse->declareVtab = 1;
  95404. pParse->db = db;
  95405. pParse->nQueryLoop = 1;
  95406. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  95407. && pParse->pNewTable
  95408. && !db->mallocFailed
  95409. && !pParse->pNewTable->pSelect
  95410. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  95411. ){
  95412. if( !pTab->aCol ){
  95413. pTab->aCol = pParse->pNewTable->aCol;
  95414. pTab->nCol = pParse->pNewTable->nCol;
  95415. pParse->pNewTable->nCol = 0;
  95416. pParse->pNewTable->aCol = 0;
  95417. }
  95418. db->pVtabCtx->pTab = 0;
  95419. }else{
  95420. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  95421. sqlite3DbFree(db, zErr);
  95422. rc = SQLITE_ERROR;
  95423. }
  95424. pParse->declareVtab = 0;
  95425. if( pParse->pVdbe ){
  95426. sqlite3VdbeFinalize(pParse->pVdbe);
  95427. }
  95428. sqlite3DeleteTable(db, pParse->pNewTable);
  95429. sqlite3StackFree(db, pParse);
  95430. }
  95431. assert( (rc&0xff)==rc );
  95432. rc = sqlite3ApiExit(db, rc);
  95433. sqlite3_mutex_leave(db->mutex);
  95434. return rc;
  95435. }
  95436. /*
  95437. ** This function is invoked by the vdbe to call the xDestroy method
  95438. ** of the virtual table named zTab in database iDb. This occurs
  95439. ** when a DROP TABLE is mentioned.
  95440. **
  95441. ** This call is a no-op if zTab is not a virtual table.
  95442. */
  95443. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  95444. int rc = SQLITE_OK;
  95445. Table *pTab;
  95446. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  95447. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  95448. VTable *p = vtabDisconnectAll(db, pTab);
  95449. assert( rc==SQLITE_OK );
  95450. rc = p->pMod->pModule->xDestroy(p->pVtab);
  95451. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  95452. if( rc==SQLITE_OK ){
  95453. assert( pTab->pVTable==p && p->pNext==0 );
  95454. p->pVtab = 0;
  95455. pTab->pVTable = 0;
  95456. sqlite3VtabUnlock(p);
  95457. }
  95458. }
  95459. return rc;
  95460. }
  95461. /*
  95462. ** This function invokes either the xRollback or xCommit method
  95463. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  95464. ** called is identified by the second argument, "offset", which is
  95465. ** the offset of the method to call in the sqlite3_module structure.
  95466. **
  95467. ** The array is cleared after invoking the callbacks.
  95468. */
  95469. static void callFinaliser(sqlite3 *db, int offset){
  95470. int i;
  95471. if( db->aVTrans ){
  95472. for(i=0; i<db->nVTrans; i++){
  95473. VTable *pVTab = db->aVTrans[i];
  95474. sqlite3_vtab *p = pVTab->pVtab;
  95475. if( p ){
  95476. int (*x)(sqlite3_vtab *);
  95477. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  95478. if( x ) x(p);
  95479. }
  95480. pVTab->iSavepoint = 0;
  95481. sqlite3VtabUnlock(pVTab);
  95482. }
  95483. sqlite3DbFree(db, db->aVTrans);
  95484. db->nVTrans = 0;
  95485. db->aVTrans = 0;
  95486. }
  95487. }
  95488. /*
  95489. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  95490. ** array. Return the error code for the first error that occurs, or
  95491. ** SQLITE_OK if all xSync operations are successful.
  95492. **
  95493. ** Set *pzErrmsg to point to a buffer that should be released using
  95494. ** sqlite3DbFree() containing an error message, if one is available.
  95495. */
  95496. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  95497. int i;
  95498. int rc = SQLITE_OK;
  95499. VTable **aVTrans = db->aVTrans;
  95500. db->aVTrans = 0;
  95501. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  95502. int (*x)(sqlite3_vtab *);
  95503. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  95504. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  95505. rc = x(pVtab);
  95506. sqlite3DbFree(db, *pzErrmsg);
  95507. *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  95508. sqlite3_free(pVtab->zErrMsg);
  95509. }
  95510. }
  95511. db->aVTrans = aVTrans;
  95512. return rc;
  95513. }
  95514. /*
  95515. ** Invoke the xRollback method of all virtual tables in the
  95516. ** sqlite3.aVTrans array. Then clear the array itself.
  95517. */
  95518. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  95519. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  95520. return SQLITE_OK;
  95521. }
  95522. /*
  95523. ** Invoke the xCommit method of all virtual tables in the
  95524. ** sqlite3.aVTrans array. Then clear the array itself.
  95525. */
  95526. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  95527. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  95528. return SQLITE_OK;
  95529. }
  95530. /*
  95531. ** If the virtual table pVtab supports the transaction interface
  95532. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  95533. ** not currently open, invoke the xBegin method now.
  95534. **
  95535. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  95536. ** in the sqlite3.aVTrans array.
  95537. */
  95538. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  95539. int rc = SQLITE_OK;
  95540. const sqlite3_module *pModule;
  95541. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  95542. ** than zero, then this function is being called from within a
  95543. ** virtual module xSync() callback. It is illegal to write to
  95544. ** virtual module tables in this case, so return SQLITE_LOCKED.
  95545. */
  95546. if( sqlite3VtabInSync(db) ){
  95547. return SQLITE_LOCKED;
  95548. }
  95549. if( !pVTab ){
  95550. return SQLITE_OK;
  95551. }
  95552. pModule = pVTab->pVtab->pModule;
  95553. if( pModule->xBegin ){
  95554. int i;
  95555. /* If pVtab is already in the aVTrans array, return early */
  95556. for(i=0; i<db->nVTrans; i++){
  95557. if( db->aVTrans[i]==pVTab ){
  95558. return SQLITE_OK;
  95559. }
  95560. }
  95561. /* Invoke the xBegin method. If successful, add the vtab to the
  95562. ** sqlite3.aVTrans[] array. */
  95563. rc = growVTrans(db);
  95564. if( rc==SQLITE_OK ){
  95565. rc = pModule->xBegin(pVTab->pVtab);
  95566. if( rc==SQLITE_OK ){
  95567. addToVTrans(db, pVTab);
  95568. }
  95569. }
  95570. }
  95571. return rc;
  95572. }
  95573. /*
  95574. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  95575. ** virtual tables that currently have an open transaction. Pass iSavepoint
  95576. ** as the second argument to the virtual table method invoked.
  95577. **
  95578. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  95579. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  95580. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  95581. ** an open transaction is invoked.
  95582. **
  95583. ** If any virtual table method returns an error code other than SQLITE_OK,
  95584. ** processing is abandoned and the error returned to the caller of this
  95585. ** function immediately. If all calls to virtual table methods are successful,
  95586. ** SQLITE_OK is returned.
  95587. */
  95588. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  95589. int rc = SQLITE_OK;
  95590. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  95591. assert( iSavepoint>=0 );
  95592. if( db->aVTrans ){
  95593. int i;
  95594. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  95595. VTable *pVTab = db->aVTrans[i];
  95596. const sqlite3_module *pMod = pVTab->pMod->pModule;
  95597. if( pVTab->pVtab && pMod->iVersion>=2 ){
  95598. int (*xMethod)(sqlite3_vtab *, int);
  95599. switch( op ){
  95600. case SAVEPOINT_BEGIN:
  95601. xMethod = pMod->xSavepoint;
  95602. pVTab->iSavepoint = iSavepoint+1;
  95603. break;
  95604. case SAVEPOINT_ROLLBACK:
  95605. xMethod = pMod->xRollbackTo;
  95606. break;
  95607. default:
  95608. xMethod = pMod->xRelease;
  95609. break;
  95610. }
  95611. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  95612. rc = xMethod(pVTab->pVtab, iSavepoint);
  95613. }
  95614. }
  95615. }
  95616. }
  95617. return rc;
  95618. }
  95619. /*
  95620. ** The first parameter (pDef) is a function implementation. The
  95621. ** second parameter (pExpr) is the first argument to this function.
  95622. ** If pExpr is a column in a virtual table, then let the virtual
  95623. ** table implementation have an opportunity to overload the function.
  95624. **
  95625. ** This routine is used to allow virtual table implementations to
  95626. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  95627. **
  95628. ** Return either the pDef argument (indicating no change) or a
  95629. ** new FuncDef structure that is marked as ephemeral using the
  95630. ** SQLITE_FUNC_EPHEM flag.
  95631. */
  95632. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  95633. sqlite3 *db, /* Database connection for reporting malloc problems */
  95634. FuncDef *pDef, /* Function to possibly overload */
  95635. int nArg, /* Number of arguments to the function */
  95636. Expr *pExpr /* First argument to the function */
  95637. ){
  95638. Table *pTab;
  95639. sqlite3_vtab *pVtab;
  95640. sqlite3_module *pMod;
  95641. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  95642. void *pArg = 0;
  95643. FuncDef *pNew;
  95644. int rc = 0;
  95645. char *zLowerName;
  95646. unsigned char *z;
  95647. /* Check to see the left operand is a column in a virtual table */
  95648. if( NEVER(pExpr==0) ) return pDef;
  95649. if( pExpr->op!=TK_COLUMN ) return pDef;
  95650. pTab = pExpr->pTab;
  95651. if( NEVER(pTab==0) ) return pDef;
  95652. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  95653. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  95654. assert( pVtab!=0 );
  95655. assert( pVtab->pModule!=0 );
  95656. pMod = (sqlite3_module *)pVtab->pModule;
  95657. if( pMod->xFindFunction==0 ) return pDef;
  95658. /* Call the xFindFunction method on the virtual table implementation
  95659. ** to see if the implementation wants to overload this function
  95660. */
  95661. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  95662. if( zLowerName ){
  95663. for(z=(unsigned char*)zLowerName; *z; z++){
  95664. *z = sqlite3UpperToLower[*z];
  95665. }
  95666. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  95667. sqlite3DbFree(db, zLowerName);
  95668. }
  95669. if( rc==0 ){
  95670. return pDef;
  95671. }
  95672. /* Create a new ephemeral function definition for the overloaded
  95673. ** function */
  95674. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  95675. + sqlite3Strlen30(pDef->zName) + 1);
  95676. if( pNew==0 ){
  95677. return pDef;
  95678. }
  95679. *pNew = *pDef;
  95680. pNew->zName = (char *)&pNew[1];
  95681. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  95682. pNew->xFunc = xFunc;
  95683. pNew->pUserData = pArg;
  95684. pNew->flags |= SQLITE_FUNC_EPHEM;
  95685. return pNew;
  95686. }
  95687. /*
  95688. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  95689. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  95690. ** array if it is missing. If pTab is already in the array, this routine
  95691. ** is a no-op.
  95692. */
  95693. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  95694. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  95695. int i, n;
  95696. Table **apVtabLock;
  95697. assert( IsVirtual(pTab) );
  95698. for(i=0; i<pToplevel->nVtabLock; i++){
  95699. if( pTab==pToplevel->apVtabLock[i] ) return;
  95700. }
  95701. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  95702. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  95703. if( apVtabLock ){
  95704. pToplevel->apVtabLock = apVtabLock;
  95705. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  95706. }else{
  95707. pToplevel->db->mallocFailed = 1;
  95708. }
  95709. }
  95710. /*
  95711. ** Return the ON CONFLICT resolution mode in effect for the virtual
  95712. ** table update operation currently in progress.
  95713. **
  95714. ** The results of this routine are undefined unless it is called from
  95715. ** within an xUpdate method.
  95716. */
  95717. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  95718. static const unsigned char aMap[] = {
  95719. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  95720. };
  95721. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  95722. assert( OE_Ignore==4 && OE_Replace==5 );
  95723. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  95724. return (int)aMap[db->vtabOnConflict-1];
  95725. }
  95726. /*
  95727. ** Call from within the xCreate() or xConnect() methods to provide
  95728. ** the SQLite core with additional information about the behavior
  95729. ** of the virtual table being implemented.
  95730. */
  95731. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  95732. va_list ap;
  95733. int rc = SQLITE_OK;
  95734. sqlite3_mutex_enter(db->mutex);
  95735. va_start(ap, op);
  95736. switch( op ){
  95737. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  95738. VtabCtx *p = db->pVtabCtx;
  95739. if( !p ){
  95740. rc = SQLITE_MISUSE_BKPT;
  95741. }else{
  95742. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  95743. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  95744. }
  95745. break;
  95746. }
  95747. default:
  95748. rc = SQLITE_MISUSE_BKPT;
  95749. break;
  95750. }
  95751. va_end(ap);
  95752. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  95753. sqlite3_mutex_leave(db->mutex);
  95754. return rc;
  95755. }
  95756. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  95757. /************** End of vtab.c ************************************************/
  95758. /************** Begin file where.c *******************************************/
  95759. /*
  95760. ** 2001 September 15
  95761. **
  95762. ** The author disclaims copyright to this source code. In place of
  95763. ** a legal notice, here is a blessing:
  95764. **
  95765. ** May you do good and not evil.
  95766. ** May you find forgiveness for yourself and forgive others.
  95767. ** May you share freely, never taking more than you give.
  95768. **
  95769. *************************************************************************
  95770. ** This module contains C code that generates VDBE code used to process
  95771. ** the WHERE clause of SQL statements. This module is responsible for
  95772. ** generating the code that loops through a table looking for applicable
  95773. ** rows. Indices are selected and used to speed the search when doing
  95774. ** so is applicable. Because this module is responsible for selecting
  95775. ** indices, you might also think of this module as the "query optimizer".
  95776. */
  95777. /*
  95778. ** Trace output macros
  95779. */
  95780. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  95781. /***/ int sqlite3WhereTrace = 0;
  95782. #endif
  95783. #if defined(SQLITE_DEBUG) \
  95784. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  95785. # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  95786. #else
  95787. # define WHERETRACE(X)
  95788. #endif
  95789. /* Forward reference
  95790. */
  95791. typedef struct WhereClause WhereClause;
  95792. typedef struct WhereMaskSet WhereMaskSet;
  95793. typedef struct WhereOrInfo WhereOrInfo;
  95794. typedef struct WhereAndInfo WhereAndInfo;
  95795. typedef struct WhereCost WhereCost;
  95796. /*
  95797. ** The query generator uses an array of instances of this structure to
  95798. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  95799. ** clause subexpression is separated from the others by AND operators,
  95800. ** usually, or sometimes subexpressions separated by OR.
  95801. **
  95802. ** All WhereTerms are collected into a single WhereClause structure.
  95803. ** The following identity holds:
  95804. **
  95805. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  95806. **
  95807. ** When a term is of the form:
  95808. **
  95809. ** X <op> <expr>
  95810. **
  95811. ** where X is a column name and <op> is one of certain operators,
  95812. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  95813. ** cursor number and column number for X. WhereTerm.eOperator records
  95814. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  95815. ** use of a bitmask encoding for the operator allows us to search
  95816. ** quickly for terms that match any of several different operators.
  95817. **
  95818. ** A WhereTerm might also be two or more subterms connected by OR:
  95819. **
  95820. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  95821. **
  95822. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  95823. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  95824. ** is collected about the
  95825. **
  95826. ** If a term in the WHERE clause does not match either of the two previous
  95827. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  95828. ** to the original subexpression content and wtFlags is set up appropriately
  95829. ** but no other fields in the WhereTerm object are meaningful.
  95830. **
  95831. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  95832. ** but they do so indirectly. A single WhereMaskSet structure translates
  95833. ** cursor number into bits and the translated bit is stored in the prereq
  95834. ** fields. The translation is used in order to maximize the number of
  95835. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  95836. ** spread out over the non-negative integers. For example, the cursor
  95837. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  95838. ** translates these sparse cursor numbers into consecutive integers
  95839. ** beginning with 0 in order to make the best possible use of the available
  95840. ** bits in the Bitmask. So, in the example above, the cursor numbers
  95841. ** would be mapped into integers 0 through 7.
  95842. **
  95843. ** The number of terms in a join is limited by the number of bits
  95844. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  95845. ** is only able to process joins with 64 or fewer tables.
  95846. */
  95847. typedef struct WhereTerm WhereTerm;
  95848. struct WhereTerm {
  95849. Expr *pExpr; /* Pointer to the subexpression that is this term */
  95850. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  95851. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  95852. union {
  95853. int leftColumn; /* Column number of X in "X <op> <expr>" */
  95854. WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
  95855. WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
  95856. } u;
  95857. u16 eOperator; /* A WO_xx value describing <op> */
  95858. u8 wtFlags; /* TERM_xxx bit flags. See below */
  95859. u8 nChild; /* Number of children that must disable us */
  95860. WhereClause *pWC; /* The clause this term is part of */
  95861. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  95862. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  95863. };
  95864. /*
  95865. ** Allowed values of WhereTerm.wtFlags
  95866. */
  95867. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  95868. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  95869. #define TERM_CODED 0x04 /* This term is already coded */
  95870. #define TERM_COPIED 0x08 /* Has a child */
  95871. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  95872. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  95873. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  95874. #ifdef SQLITE_ENABLE_STAT3
  95875. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  95876. #else
  95877. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  95878. #endif
  95879. /*
  95880. ** An instance of the following structure holds all information about a
  95881. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  95882. **
  95883. ** Explanation of pOuter: For a WHERE clause of the form
  95884. **
  95885. ** a AND ((b AND c) OR (d AND e)) AND f
  95886. **
  95887. ** There are separate WhereClause objects for the whole clause and for
  95888. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  95889. ** subclauses points to the WhereClause object for the whole clause.
  95890. */
  95891. struct WhereClause {
  95892. Parse *pParse; /* The parser context */
  95893. WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  95894. Bitmask vmask; /* Bitmask identifying virtual table cursors */
  95895. WhereClause *pOuter; /* Outer conjunction */
  95896. u8 op; /* Split operator. TK_AND or TK_OR */
  95897. u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
  95898. int nTerm; /* Number of terms */
  95899. int nSlot; /* Number of entries in a[] */
  95900. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  95901. #if defined(SQLITE_SMALL_STACK)
  95902. WhereTerm aStatic[1]; /* Initial static space for a[] */
  95903. #else
  95904. WhereTerm aStatic[8]; /* Initial static space for a[] */
  95905. #endif
  95906. };
  95907. /*
  95908. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  95909. ** a dynamically allocated instance of the following structure.
  95910. */
  95911. struct WhereOrInfo {
  95912. WhereClause wc; /* Decomposition into subterms */
  95913. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  95914. };
  95915. /*
  95916. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  95917. ** a dynamically allocated instance of the following structure.
  95918. */
  95919. struct WhereAndInfo {
  95920. WhereClause wc; /* The subexpression broken out */
  95921. };
  95922. /*
  95923. ** An instance of the following structure keeps track of a mapping
  95924. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  95925. **
  95926. ** The VDBE cursor numbers are small integers contained in
  95927. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  95928. ** clause, the cursor numbers might not begin with 0 and they might
  95929. ** contain gaps in the numbering sequence. But we want to make maximum
  95930. ** use of the bits in our bitmasks. This structure provides a mapping
  95931. ** from the sparse cursor numbers into consecutive integers beginning
  95932. ** with 0.
  95933. **
  95934. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  95935. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  95936. **
  95937. ** For example, if the WHERE clause expression used these VDBE
  95938. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  95939. ** would map those cursor numbers into bits 0 through 5.
  95940. **
  95941. ** Note that the mapping is not necessarily ordered. In the example
  95942. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  95943. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  95944. ** does not really matter. What is important is that sparse cursor
  95945. ** numbers all get mapped into bit numbers that begin with 0 and contain
  95946. ** no gaps.
  95947. */
  95948. struct WhereMaskSet {
  95949. int n; /* Number of assigned cursor values */
  95950. int ix[BMS]; /* Cursor assigned to each bit */
  95951. };
  95952. /*
  95953. ** A WhereCost object records a lookup strategy and the estimated
  95954. ** cost of pursuing that strategy.
  95955. */
  95956. struct WhereCost {
  95957. WherePlan plan; /* The lookup strategy */
  95958. double rCost; /* Overall cost of pursuing this search strategy */
  95959. Bitmask used; /* Bitmask of cursors used by this plan */
  95960. };
  95961. /*
  95962. ** Bitmasks for the operators that indices are able to exploit. An
  95963. ** OR-ed combination of these values can be used when searching for
  95964. ** terms in the where clause.
  95965. */
  95966. #define WO_IN 0x001
  95967. #define WO_EQ 0x002
  95968. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  95969. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  95970. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  95971. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  95972. #define WO_MATCH 0x040
  95973. #define WO_ISNULL 0x080
  95974. #define WO_OR 0x100 /* Two or more OR-connected terms */
  95975. #define WO_AND 0x200 /* Two or more AND-connected terms */
  95976. #define WO_NOOP 0x800 /* This term does not restrict search space */
  95977. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  95978. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  95979. /*
  95980. ** Value for wsFlags returned by bestIndex() and stored in
  95981. ** WhereLevel.wsFlags. These flags determine which search
  95982. ** strategies are appropriate.
  95983. **
  95984. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  95985. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  95986. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  95987. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  95988. ** the "op" parameter to findTerm when we are resolving equality constraints.
  95989. ** ISNULL constraints will then not be used on the right table of a left
  95990. ** join. Tickets #2177 and #2189.
  95991. */
  95992. #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  95993. #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  95994. #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
  95995. #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  95996. #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  95997. #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
  95998. #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
  95999. #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
  96000. #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
  96001. #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  96002. #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  96003. #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
  96004. #define WHERE_IDX_ONLY 0x00400000 /* Use index only - omit table */
  96005. #define WHERE_ORDERED 0x00800000 /* Output will appear in correct order */
  96006. #define WHERE_REVERSE 0x01000000 /* Scan in reverse order */
  96007. #define WHERE_UNIQUE 0x02000000 /* Selects no more than one row */
  96008. #define WHERE_ALL_UNIQUE 0x04000000 /* This and all prior have one row */
  96009. #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  96010. #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  96011. #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
  96012. #define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
  96013. #define WHERE_COVER_SCAN 0x80000000 /* Full scan of a covering index */
  96014. /*
  96015. ** This module contains many separate subroutines that work together to
  96016. ** find the best indices to use for accessing a particular table in a query.
  96017. ** An instance of the following structure holds context information about the
  96018. ** index search so that it can be more easily passed between the various
  96019. ** routines.
  96020. */
  96021. typedef struct WhereBestIdx WhereBestIdx;
  96022. struct WhereBestIdx {
  96023. Parse *pParse; /* Parser context */
  96024. WhereClause *pWC; /* The WHERE clause */
  96025. struct SrcList_item *pSrc; /* The FROM clause term to search */
  96026. Bitmask notReady; /* Mask of cursors not available */
  96027. Bitmask notValid; /* Cursors not available for any purpose */
  96028. ExprList *pOrderBy; /* The ORDER BY clause */
  96029. ExprList *pDistinct; /* The select-list if query is DISTINCT */
  96030. sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
  96031. int i, n; /* Which loop is being coded; # of loops */
  96032. WhereLevel *aLevel; /* Info about outer loops */
  96033. WhereCost cost; /* Lowest cost query plan */
  96034. };
  96035. /*
  96036. ** Return TRUE if the probe cost is less than the baseline cost
  96037. */
  96038. static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
  96039. if( pProbe->rCost<pBaseline->rCost ) return 1;
  96040. if( pProbe->rCost>pBaseline->rCost ) return 0;
  96041. if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
  96042. if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
  96043. return 0;
  96044. }
  96045. /*
  96046. ** Initialize a preallocated WhereClause structure.
  96047. */
  96048. static void whereClauseInit(
  96049. WhereClause *pWC, /* The WhereClause to be initialized */
  96050. Parse *pParse, /* The parsing context */
  96051. WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
  96052. u16 wctrlFlags /* Might include WHERE_AND_ONLY */
  96053. ){
  96054. pWC->pParse = pParse;
  96055. pWC->pMaskSet = pMaskSet;
  96056. pWC->pOuter = 0;
  96057. pWC->nTerm = 0;
  96058. pWC->nSlot = ArraySize(pWC->aStatic);
  96059. pWC->a = pWC->aStatic;
  96060. pWC->vmask = 0;
  96061. pWC->wctrlFlags = wctrlFlags;
  96062. }
  96063. /* Forward reference */
  96064. static void whereClauseClear(WhereClause*);
  96065. /*
  96066. ** Deallocate all memory associated with a WhereOrInfo object.
  96067. */
  96068. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  96069. whereClauseClear(&p->wc);
  96070. sqlite3DbFree(db, p);
  96071. }
  96072. /*
  96073. ** Deallocate all memory associated with a WhereAndInfo object.
  96074. */
  96075. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  96076. whereClauseClear(&p->wc);
  96077. sqlite3DbFree(db, p);
  96078. }
  96079. /*
  96080. ** Deallocate a WhereClause structure. The WhereClause structure
  96081. ** itself is not freed. This routine is the inverse of whereClauseInit().
  96082. */
  96083. static void whereClauseClear(WhereClause *pWC){
  96084. int i;
  96085. WhereTerm *a;
  96086. sqlite3 *db = pWC->pParse->db;
  96087. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  96088. if( a->wtFlags & TERM_DYNAMIC ){
  96089. sqlite3ExprDelete(db, a->pExpr);
  96090. }
  96091. if( a->wtFlags & TERM_ORINFO ){
  96092. whereOrInfoDelete(db, a->u.pOrInfo);
  96093. }else if( a->wtFlags & TERM_ANDINFO ){
  96094. whereAndInfoDelete(db, a->u.pAndInfo);
  96095. }
  96096. }
  96097. if( pWC->a!=pWC->aStatic ){
  96098. sqlite3DbFree(db, pWC->a);
  96099. }
  96100. }
  96101. /*
  96102. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  96103. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  96104. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  96105. ** 0 is returned if the new WhereTerm could not be added due to a memory
  96106. ** allocation error. The memory allocation failure will be recorded in
  96107. ** the db->mallocFailed flag so that higher-level functions can detect it.
  96108. **
  96109. ** This routine will increase the size of the pWC->a[] array as necessary.
  96110. **
  96111. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  96112. ** for freeing the expression p is assumed by the WhereClause object pWC.
  96113. ** This is true even if this routine fails to allocate a new WhereTerm.
  96114. **
  96115. ** WARNING: This routine might reallocate the space used to store
  96116. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  96117. ** calling this routine. Such pointers may be reinitialized by referencing
  96118. ** the pWC->a[] array.
  96119. */
  96120. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  96121. WhereTerm *pTerm;
  96122. int idx;
  96123. testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
  96124. if( pWC->nTerm>=pWC->nSlot ){
  96125. WhereTerm *pOld = pWC->a;
  96126. sqlite3 *db = pWC->pParse->db;
  96127. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  96128. if( pWC->a==0 ){
  96129. if( wtFlags & TERM_DYNAMIC ){
  96130. sqlite3ExprDelete(db, p);
  96131. }
  96132. pWC->a = pOld;
  96133. return 0;
  96134. }
  96135. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  96136. if( pOld!=pWC->aStatic ){
  96137. sqlite3DbFree(db, pOld);
  96138. }
  96139. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  96140. }
  96141. pTerm = &pWC->a[idx = pWC->nTerm++];
  96142. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  96143. pTerm->wtFlags = wtFlags;
  96144. pTerm->pWC = pWC;
  96145. pTerm->iParent = -1;
  96146. return idx;
  96147. }
  96148. /*
  96149. ** This routine identifies subexpressions in the WHERE clause where
  96150. ** each subexpression is separated by the AND operator or some other
  96151. ** operator specified in the op parameter. The WhereClause structure
  96152. ** is filled with pointers to subexpressions. For example:
  96153. **
  96154. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  96155. ** \________/ \_______________/ \________________/
  96156. ** slot[0] slot[1] slot[2]
  96157. **
  96158. ** The original WHERE clause in pExpr is unaltered. All this routine
  96159. ** does is make slot[] entries point to substructure within pExpr.
  96160. **
  96161. ** In the previous sentence and in the diagram, "slot[]" refers to
  96162. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  96163. ** all terms of the WHERE clause.
  96164. */
  96165. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  96166. pWC->op = (u8)op;
  96167. if( pExpr==0 ) return;
  96168. if( pExpr->op!=op ){
  96169. whereClauseInsert(pWC, pExpr, 0);
  96170. }else{
  96171. whereSplit(pWC, pExpr->pLeft, op);
  96172. whereSplit(pWC, pExpr->pRight, op);
  96173. }
  96174. }
  96175. /*
  96176. ** Initialize an expression mask set (a WhereMaskSet object)
  96177. */
  96178. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  96179. /*
  96180. ** Return the bitmask for the given cursor number. Return 0 if
  96181. ** iCursor is not in the set.
  96182. */
  96183. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  96184. int i;
  96185. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  96186. for(i=0; i<pMaskSet->n; i++){
  96187. if( pMaskSet->ix[i]==iCursor ){
  96188. return ((Bitmask)1)<<i;
  96189. }
  96190. }
  96191. return 0;
  96192. }
  96193. /*
  96194. ** Create a new mask for cursor iCursor.
  96195. **
  96196. ** There is one cursor per table in the FROM clause. The number of
  96197. ** tables in the FROM clause is limited by a test early in the
  96198. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  96199. ** array will never overflow.
  96200. */
  96201. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  96202. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  96203. pMaskSet->ix[pMaskSet->n++] = iCursor;
  96204. }
  96205. /*
  96206. ** This routine walks (recursively) an expression tree and generates
  96207. ** a bitmask indicating which tables are used in that expression
  96208. ** tree.
  96209. **
  96210. ** In order for this routine to work, the calling function must have
  96211. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  96212. ** the header comment on that routine for additional information.
  96213. ** The sqlite3ResolveExprNames() routines looks for column names and
  96214. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  96215. ** the VDBE cursor number of the table. This routine just has to
  96216. ** translate the cursor numbers into bitmask values and OR all
  96217. ** the bitmasks together.
  96218. */
  96219. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  96220. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  96221. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  96222. Bitmask mask = 0;
  96223. if( p==0 ) return 0;
  96224. if( p->op==TK_COLUMN ){
  96225. mask = getMask(pMaskSet, p->iTable);
  96226. return mask;
  96227. }
  96228. mask = exprTableUsage(pMaskSet, p->pRight);
  96229. mask |= exprTableUsage(pMaskSet, p->pLeft);
  96230. if( ExprHasProperty(p, EP_xIsSelect) ){
  96231. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  96232. }else{
  96233. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  96234. }
  96235. return mask;
  96236. }
  96237. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  96238. int i;
  96239. Bitmask mask = 0;
  96240. if( pList ){
  96241. for(i=0; i<pList->nExpr; i++){
  96242. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  96243. }
  96244. }
  96245. return mask;
  96246. }
  96247. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  96248. Bitmask mask = 0;
  96249. while( pS ){
  96250. SrcList *pSrc = pS->pSrc;
  96251. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  96252. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  96253. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  96254. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  96255. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  96256. if( ALWAYS(pSrc!=0) ){
  96257. int i;
  96258. for(i=0; i<pSrc->nSrc; i++){
  96259. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  96260. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  96261. }
  96262. }
  96263. pS = pS->pPrior;
  96264. }
  96265. return mask;
  96266. }
  96267. /*
  96268. ** Return TRUE if the given operator is one of the operators that is
  96269. ** allowed for an indexable WHERE clause term. The allowed operators are
  96270. ** "=", "<", ">", "<=", ">=", and "IN".
  96271. **
  96272. ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
  96273. ** of one of the following forms: column = expression column > expression
  96274. ** column >= expression column < expression column <= expression
  96275. ** expression = column expression > column expression >= column
  96276. ** expression < column expression <= column column IN
  96277. ** (expression-list) column IN (subquery) column IS NULL
  96278. */
  96279. static int allowedOp(int op){
  96280. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  96281. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  96282. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  96283. assert( TK_GE==TK_EQ+4 );
  96284. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  96285. }
  96286. /*
  96287. ** Swap two objects of type TYPE.
  96288. */
  96289. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  96290. /*
  96291. ** Commute a comparison operator. Expressions of the form "X op Y"
  96292. ** are converted into "Y op X".
  96293. **
  96294. ** If left/right precendence rules come into play when determining the
  96295. ** collating
  96296. ** side of the comparison, it remains associated with the same side after
  96297. ** the commutation. So "Y collate NOCASE op X" becomes
  96298. ** "X op Y". This is because any collation sequence on
  96299. ** the left hand side of a comparison overrides any collation sequence
  96300. ** attached to the right. For the same reason the EP_Collate flag
  96301. ** is not commuted.
  96302. */
  96303. static void exprCommute(Parse *pParse, Expr *pExpr){
  96304. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  96305. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  96306. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  96307. if( expRight==expLeft ){
  96308. /* Either X and Y both have COLLATE operator or neither do */
  96309. if( expRight ){
  96310. /* Both X and Y have COLLATE operators. Make sure X is always
  96311. ** used by clearing the EP_Collate flag from Y. */
  96312. pExpr->pRight->flags &= ~EP_Collate;
  96313. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  96314. /* Neither X nor Y have COLLATE operators, but X has a non-default
  96315. ** collating sequence. So add the EP_Collate marker on X to cause
  96316. ** it to be searched first. */
  96317. pExpr->pLeft->flags |= EP_Collate;
  96318. }
  96319. }
  96320. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  96321. if( pExpr->op>=TK_GT ){
  96322. assert( TK_LT==TK_GT+2 );
  96323. assert( TK_GE==TK_LE+2 );
  96324. assert( TK_GT>TK_EQ );
  96325. assert( TK_GT<TK_LE );
  96326. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  96327. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  96328. }
  96329. }
  96330. /*
  96331. ** Translate from TK_xx operator to WO_xx bitmask.
  96332. */
  96333. static u16 operatorMask(int op){
  96334. u16 c;
  96335. assert( allowedOp(op) );
  96336. if( op==TK_IN ){
  96337. c = WO_IN;
  96338. }else if( op==TK_ISNULL ){
  96339. c = WO_ISNULL;
  96340. }else{
  96341. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  96342. c = (u16)(WO_EQ<<(op-TK_EQ));
  96343. }
  96344. assert( op!=TK_ISNULL || c==WO_ISNULL );
  96345. assert( op!=TK_IN || c==WO_IN );
  96346. assert( op!=TK_EQ || c==WO_EQ );
  96347. assert( op!=TK_LT || c==WO_LT );
  96348. assert( op!=TK_LE || c==WO_LE );
  96349. assert( op!=TK_GT || c==WO_GT );
  96350. assert( op!=TK_GE || c==WO_GE );
  96351. return c;
  96352. }
  96353. /*
  96354. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  96355. ** where X is a reference to the iColumn of table iCur and <op> is one of
  96356. ** the WO_xx operator codes specified by the op parameter.
  96357. ** Return a pointer to the term. Return 0 if not found.
  96358. */
  96359. static WhereTerm *findTerm(
  96360. WhereClause *pWC, /* The WHERE clause to be searched */
  96361. int iCur, /* Cursor number of LHS */
  96362. int iColumn, /* Column number of LHS */
  96363. Bitmask notReady, /* RHS must not overlap with this mask */
  96364. u32 op, /* Mask of WO_xx values describing operator */
  96365. Index *pIdx /* Must be compatible with this index, if not NULL */
  96366. ){
  96367. WhereTerm *pTerm;
  96368. int k;
  96369. assert( iCur>=0 );
  96370. op &= WO_ALL;
  96371. for(; pWC; pWC=pWC->pOuter){
  96372. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  96373. if( pTerm->leftCursor==iCur
  96374. && (pTerm->prereqRight & notReady)==0
  96375. && pTerm->u.leftColumn==iColumn
  96376. && (pTerm->eOperator & op)!=0
  96377. ){
  96378. if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
  96379. Expr *pX = pTerm->pExpr;
  96380. CollSeq *pColl;
  96381. char idxaff;
  96382. int j;
  96383. Parse *pParse = pWC->pParse;
  96384. idxaff = pIdx->pTable->aCol[iColumn].affinity;
  96385. if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
  96386. /* Figure out the collation sequence required from an index for
  96387. ** it to be useful for optimising expression pX. Store this
  96388. ** value in variable pColl.
  96389. */
  96390. assert(pX->pLeft);
  96391. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  96392. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  96393. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  96394. if( NEVER(j>=pIdx->nColumn) ) return 0;
  96395. }
  96396. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
  96397. }
  96398. return pTerm;
  96399. }
  96400. }
  96401. }
  96402. return 0;
  96403. }
  96404. /* Forward reference */
  96405. static void exprAnalyze(SrcList*, WhereClause*, int);
  96406. /*
  96407. ** Call exprAnalyze on all terms in a WHERE clause.
  96408. **
  96409. **
  96410. */
  96411. static void exprAnalyzeAll(
  96412. SrcList *pTabList, /* the FROM clause */
  96413. WhereClause *pWC /* the WHERE clause to be analyzed */
  96414. ){
  96415. int i;
  96416. for(i=pWC->nTerm-1; i>=0; i--){
  96417. exprAnalyze(pTabList, pWC, i);
  96418. }
  96419. }
  96420. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  96421. /*
  96422. ** Check to see if the given expression is a LIKE or GLOB operator that
  96423. ** can be optimized using inequality constraints. Return TRUE if it is
  96424. ** so and false if not.
  96425. **
  96426. ** In order for the operator to be optimizible, the RHS must be a string
  96427. ** literal that does not begin with a wildcard.
  96428. */
  96429. static int isLikeOrGlob(
  96430. Parse *pParse, /* Parsing and code generating context */
  96431. Expr *pExpr, /* Test this expression */
  96432. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  96433. int *pisComplete, /* True if the only wildcard is % in the last character */
  96434. int *pnoCase /* True if uppercase is equivalent to lowercase */
  96435. ){
  96436. const char *z = 0; /* String on RHS of LIKE operator */
  96437. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  96438. ExprList *pList; /* List of operands to the LIKE operator */
  96439. int c; /* One character in z[] */
  96440. int cnt; /* Number of non-wildcard prefix characters */
  96441. char wc[3]; /* Wildcard characters */
  96442. sqlite3 *db = pParse->db; /* Database connection */
  96443. sqlite3_value *pVal = 0;
  96444. int op; /* Opcode of pRight */
  96445. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  96446. return 0;
  96447. }
  96448. #ifdef SQLITE_EBCDIC
  96449. if( *pnoCase ) return 0;
  96450. #endif
  96451. pList = pExpr->x.pList;
  96452. pLeft = pList->a[1].pExpr;
  96453. if( pLeft->op!=TK_COLUMN
  96454. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  96455. || IsVirtual(pLeft->pTab)
  96456. ){
  96457. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  96458. ** be the name of an indexed column with TEXT affinity. */
  96459. return 0;
  96460. }
  96461. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  96462. pRight = pList->a[0].pExpr;
  96463. op = pRight->op;
  96464. if( op==TK_REGISTER ){
  96465. op = pRight->op2;
  96466. }
  96467. if( op==TK_VARIABLE ){
  96468. Vdbe *pReprepare = pParse->pReprepare;
  96469. int iCol = pRight->iColumn;
  96470. pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
  96471. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  96472. z = (char *)sqlite3_value_text(pVal);
  96473. }
  96474. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  96475. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  96476. }else if( op==TK_STRING ){
  96477. z = pRight->u.zToken;
  96478. }
  96479. if( z ){
  96480. cnt = 0;
  96481. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  96482. cnt++;
  96483. }
  96484. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  96485. Expr *pPrefix;
  96486. *pisComplete = c==wc[0] && z[cnt+1]==0;
  96487. pPrefix = sqlite3Expr(db, TK_STRING, z);
  96488. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  96489. *ppPrefix = pPrefix;
  96490. if( op==TK_VARIABLE ){
  96491. Vdbe *v = pParse->pVdbe;
  96492. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  96493. if( *pisComplete && pRight->u.zToken[1] ){
  96494. /* If the rhs of the LIKE expression is a variable, and the current
  96495. ** value of the variable means there is no need to invoke the LIKE
  96496. ** function, then no OP_Variable will be added to the program.
  96497. ** This causes problems for the sqlite3_bind_parameter_name()
  96498. ** API. To workaround them, add a dummy OP_Variable here.
  96499. */
  96500. int r1 = sqlite3GetTempReg(pParse);
  96501. sqlite3ExprCodeTarget(pParse, pRight, r1);
  96502. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  96503. sqlite3ReleaseTempReg(pParse, r1);
  96504. }
  96505. }
  96506. }else{
  96507. z = 0;
  96508. }
  96509. }
  96510. sqlite3ValueFree(pVal);
  96511. return (z!=0);
  96512. }
  96513. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  96514. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96515. /*
  96516. ** Check to see if the given expression is of the form
  96517. **
  96518. ** column MATCH expr
  96519. **
  96520. ** If it is then return TRUE. If not, return FALSE.
  96521. */
  96522. static int isMatchOfColumn(
  96523. Expr *pExpr /* Test this expression */
  96524. ){
  96525. ExprList *pList;
  96526. if( pExpr->op!=TK_FUNCTION ){
  96527. return 0;
  96528. }
  96529. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  96530. return 0;
  96531. }
  96532. pList = pExpr->x.pList;
  96533. if( pList->nExpr!=2 ){
  96534. return 0;
  96535. }
  96536. if( pList->a[1].pExpr->op != TK_COLUMN ){
  96537. return 0;
  96538. }
  96539. return 1;
  96540. }
  96541. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  96542. /*
  96543. ** If the pBase expression originated in the ON or USING clause of
  96544. ** a join, then transfer the appropriate markings over to derived.
  96545. */
  96546. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  96547. pDerived->flags |= pBase->flags & EP_FromJoin;
  96548. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  96549. }
  96550. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  96551. /*
  96552. ** Analyze a term that consists of two or more OR-connected
  96553. ** subterms. So in:
  96554. **
  96555. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  96556. ** ^^^^^^^^^^^^^^^^^^^^
  96557. **
  96558. ** This routine analyzes terms such as the middle term in the above example.
  96559. ** A WhereOrTerm object is computed and attached to the term under
  96560. ** analysis, regardless of the outcome of the analysis. Hence:
  96561. **
  96562. ** WhereTerm.wtFlags |= TERM_ORINFO
  96563. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  96564. **
  96565. ** The term being analyzed must have two or more of OR-connected subterms.
  96566. ** A single subterm might be a set of AND-connected sub-subterms.
  96567. ** Examples of terms under analysis:
  96568. **
  96569. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  96570. ** (B) x=expr1 OR expr2=x OR x=expr3
  96571. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  96572. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  96573. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  96574. **
  96575. ** CASE 1:
  96576. **
  96577. ** If all subterms are of the form T.C=expr for some single column of C
  96578. ** a single table T (as shown in example B above) then create a new virtual
  96579. ** term that is an equivalent IN expression. In other words, if the term
  96580. ** being analyzed is:
  96581. **
  96582. ** x = expr1 OR expr2 = x OR x = expr3
  96583. **
  96584. ** then create a new virtual term like this:
  96585. **
  96586. ** x IN (expr1,expr2,expr3)
  96587. **
  96588. ** CASE 2:
  96589. **
  96590. ** If all subterms are indexable by a single table T, then set
  96591. **
  96592. ** WhereTerm.eOperator = WO_OR
  96593. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  96594. **
  96595. ** A subterm is "indexable" if it is of the form
  96596. ** "T.C <op> <expr>" where C is any column of table T and
  96597. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  96598. ** A subterm is also indexable if it is an AND of two or more
  96599. ** subsubterms at least one of which is indexable. Indexable AND
  96600. ** subterms have their eOperator set to WO_AND and they have
  96601. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  96602. **
  96603. ** From another point of view, "indexable" means that the subterm could
  96604. ** potentially be used with an index if an appropriate index exists.
  96605. ** This analysis does not consider whether or not the index exists; that
  96606. ** is something the bestIndex() routine will determine. This analysis
  96607. ** only looks at whether subterms appropriate for indexing exist.
  96608. **
  96609. ** All examples A through E above all satisfy case 2. But if a term
  96610. ** also statisfies case 1 (such as B) we know that the optimizer will
  96611. ** always prefer case 1, so in that case we pretend that case 2 is not
  96612. ** satisfied.
  96613. **
  96614. ** It might be the case that multiple tables are indexable. For example,
  96615. ** (E) above is indexable on tables P, Q, and R.
  96616. **
  96617. ** Terms that satisfy case 2 are candidates for lookup by using
  96618. ** separate indices to find rowids for each subterm and composing
  96619. ** the union of all rowids using a RowSet object. This is similar
  96620. ** to "bitmap indices" in other database engines.
  96621. **
  96622. ** OTHERWISE:
  96623. **
  96624. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  96625. ** zero. This term is not useful for search.
  96626. */
  96627. static void exprAnalyzeOrTerm(
  96628. SrcList *pSrc, /* the FROM clause */
  96629. WhereClause *pWC, /* the complete WHERE clause */
  96630. int idxTerm /* Index of the OR-term to be analyzed */
  96631. ){
  96632. Parse *pParse = pWC->pParse; /* Parser context */
  96633. sqlite3 *db = pParse->db; /* Database connection */
  96634. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  96635. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  96636. WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  96637. int i; /* Loop counters */
  96638. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  96639. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  96640. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  96641. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  96642. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  96643. /*
  96644. ** Break the OR clause into its separate subterms. The subterms are
  96645. ** stored in a WhereClause structure containing within the WhereOrInfo
  96646. ** object that is attached to the original OR clause term.
  96647. */
  96648. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  96649. assert( pExpr->op==TK_OR );
  96650. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  96651. if( pOrInfo==0 ) return;
  96652. pTerm->wtFlags |= TERM_ORINFO;
  96653. pOrWc = &pOrInfo->wc;
  96654. whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
  96655. whereSplit(pOrWc, pExpr, TK_OR);
  96656. exprAnalyzeAll(pSrc, pOrWc);
  96657. if( db->mallocFailed ) return;
  96658. assert( pOrWc->nTerm>=2 );
  96659. /*
  96660. ** Compute the set of tables that might satisfy cases 1 or 2.
  96661. */
  96662. indexable = ~(Bitmask)0;
  96663. chngToIN = ~(pWC->vmask);
  96664. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  96665. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  96666. WhereAndInfo *pAndInfo;
  96667. assert( pOrTerm->eOperator==0 );
  96668. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  96669. chngToIN = 0;
  96670. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  96671. if( pAndInfo ){
  96672. WhereClause *pAndWC;
  96673. WhereTerm *pAndTerm;
  96674. int j;
  96675. Bitmask b = 0;
  96676. pOrTerm->u.pAndInfo = pAndInfo;
  96677. pOrTerm->wtFlags |= TERM_ANDINFO;
  96678. pOrTerm->eOperator = WO_AND;
  96679. pAndWC = &pAndInfo->wc;
  96680. whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
  96681. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  96682. exprAnalyzeAll(pSrc, pAndWC);
  96683. pAndWC->pOuter = pWC;
  96684. testcase( db->mallocFailed );
  96685. if( !db->mallocFailed ){
  96686. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  96687. assert( pAndTerm->pExpr );
  96688. if( allowedOp(pAndTerm->pExpr->op) ){
  96689. b |= getMask(pMaskSet, pAndTerm->leftCursor);
  96690. }
  96691. }
  96692. }
  96693. indexable &= b;
  96694. }
  96695. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  96696. /* Skip this term for now. We revisit it when we process the
  96697. ** corresponding TERM_VIRTUAL term */
  96698. }else{
  96699. Bitmask b;
  96700. b = getMask(pMaskSet, pOrTerm->leftCursor);
  96701. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  96702. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  96703. b |= getMask(pMaskSet, pOther->leftCursor);
  96704. }
  96705. indexable &= b;
  96706. if( pOrTerm->eOperator!=WO_EQ ){
  96707. chngToIN = 0;
  96708. }else{
  96709. chngToIN &= b;
  96710. }
  96711. }
  96712. }
  96713. /*
  96714. ** Record the set of tables that satisfy case 2. The set might be
  96715. ** empty.
  96716. */
  96717. pOrInfo->indexable = indexable;
  96718. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  96719. /*
  96720. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  96721. ** we have to do some additional checking to see if case 1 really
  96722. ** is satisfied.
  96723. **
  96724. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  96725. ** that there is no possibility of transforming the OR clause into an
  96726. ** IN operator because one or more terms in the OR clause contain
  96727. ** something other than == on a column in the single table. The 1-bit
  96728. ** case means that every term of the OR clause is of the form
  96729. ** "table.column=expr" for some single table. The one bit that is set
  96730. ** will correspond to the common table. We still need to check to make
  96731. ** sure the same column is used on all terms. The 2-bit case is when
  96732. ** the all terms are of the form "table1.column=table2.column". It
  96733. ** might be possible to form an IN operator with either table1.column
  96734. ** or table2.column as the LHS if either is common to every term of
  96735. ** the OR clause.
  96736. **
  96737. ** Note that terms of the form "table.column1=table.column2" (the
  96738. ** same table on both sizes of the ==) cannot be optimized.
  96739. */
  96740. if( chngToIN ){
  96741. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  96742. int iColumn = -1; /* Column index on lhs of IN operator */
  96743. int iCursor = -1; /* Table cursor common to all terms */
  96744. int j = 0; /* Loop counter */
  96745. /* Search for a table and column that appears on one side or the
  96746. ** other of the == operator in every subterm. That table and column
  96747. ** will be recorded in iCursor and iColumn. There might not be any
  96748. ** such table and column. Set okToChngToIN if an appropriate table
  96749. ** and column is found but leave okToChngToIN false if not found.
  96750. */
  96751. for(j=0; j<2 && !okToChngToIN; j++){
  96752. pOrTerm = pOrWc->a;
  96753. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  96754. assert( pOrTerm->eOperator==WO_EQ );
  96755. pOrTerm->wtFlags &= ~TERM_OR_OK;
  96756. if( pOrTerm->leftCursor==iCursor ){
  96757. /* This is the 2-bit case and we are on the second iteration and
  96758. ** current term is from the first iteration. So skip this term. */
  96759. assert( j==1 );
  96760. continue;
  96761. }
  96762. if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
  96763. /* This term must be of the form t1.a==t2.b where t2 is in the
  96764. ** chngToIN set but t1 is not. This term will be either preceeded
  96765. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  96766. ** and use its inversion. */
  96767. testcase( pOrTerm->wtFlags & TERM_COPIED );
  96768. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  96769. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  96770. continue;
  96771. }
  96772. iColumn = pOrTerm->u.leftColumn;
  96773. iCursor = pOrTerm->leftCursor;
  96774. break;
  96775. }
  96776. if( i<0 ){
  96777. /* No candidate table+column was found. This can only occur
  96778. ** on the second iteration */
  96779. assert( j==1 );
  96780. assert( (chngToIN&(chngToIN-1))==0 );
  96781. assert( chngToIN==getMask(pMaskSet, iCursor) );
  96782. break;
  96783. }
  96784. testcase( j==1 );
  96785. /* We have found a candidate table and column. Check to see if that
  96786. ** table and column is common to every term in the OR clause */
  96787. okToChngToIN = 1;
  96788. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  96789. assert( pOrTerm->eOperator==WO_EQ );
  96790. if( pOrTerm->leftCursor!=iCursor ){
  96791. pOrTerm->wtFlags &= ~TERM_OR_OK;
  96792. }else if( pOrTerm->u.leftColumn!=iColumn ){
  96793. okToChngToIN = 0;
  96794. }else{
  96795. int affLeft, affRight;
  96796. /* If the right-hand side is also a column, then the affinities
  96797. ** of both right and left sides must be such that no type
  96798. ** conversions are required on the right. (Ticket #2249)
  96799. */
  96800. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  96801. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  96802. if( affRight!=0 && affRight!=affLeft ){
  96803. okToChngToIN = 0;
  96804. }else{
  96805. pOrTerm->wtFlags |= TERM_OR_OK;
  96806. }
  96807. }
  96808. }
  96809. }
  96810. /* At this point, okToChngToIN is true if original pTerm satisfies
  96811. ** case 1. In that case, construct a new virtual term that is
  96812. ** pTerm converted into an IN operator.
  96813. **
  96814. ** EV: R-00211-15100
  96815. */
  96816. if( okToChngToIN ){
  96817. Expr *pDup; /* A transient duplicate expression */
  96818. ExprList *pList = 0; /* The RHS of the IN operator */
  96819. Expr *pLeft = 0; /* The LHS of the IN operator */
  96820. Expr *pNew; /* The complete IN operator */
  96821. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  96822. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  96823. assert( pOrTerm->eOperator==WO_EQ );
  96824. assert( pOrTerm->leftCursor==iCursor );
  96825. assert( pOrTerm->u.leftColumn==iColumn );
  96826. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  96827. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
  96828. pLeft = pOrTerm->pExpr->pLeft;
  96829. }
  96830. assert( pLeft!=0 );
  96831. pDup = sqlite3ExprDup(db, pLeft, 0);
  96832. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  96833. if( pNew ){
  96834. int idxNew;
  96835. transferJoinMarkings(pNew, pExpr);
  96836. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  96837. pNew->x.pList = pList;
  96838. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  96839. testcase( idxNew==0 );
  96840. exprAnalyze(pSrc, pWC, idxNew);
  96841. pTerm = &pWC->a[idxTerm];
  96842. pWC->a[idxNew].iParent = idxTerm;
  96843. pTerm->nChild = 1;
  96844. }else{
  96845. sqlite3ExprListDelete(db, pList);
  96846. }
  96847. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  96848. }
  96849. }
  96850. }
  96851. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  96852. /*
  96853. ** The input to this routine is an WhereTerm structure with only the
  96854. ** "pExpr" field filled in. The job of this routine is to analyze the
  96855. ** subexpression and populate all the other fields of the WhereTerm
  96856. ** structure.
  96857. **
  96858. ** If the expression is of the form "<expr> <op> X" it gets commuted
  96859. ** to the standard form of "X <op> <expr>".
  96860. **
  96861. ** If the expression is of the form "X <op> Y" where both X and Y are
  96862. ** columns, then the original expression is unchanged and a new virtual
  96863. ** term of the form "Y <op> X" is added to the WHERE clause and
  96864. ** analyzed separately. The original term is marked with TERM_COPIED
  96865. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  96866. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  96867. ** is a commuted copy of a prior term.) The original term has nChild=1
  96868. ** and the copy has idxParent set to the index of the original term.
  96869. */
  96870. static void exprAnalyze(
  96871. SrcList *pSrc, /* the FROM clause */
  96872. WhereClause *pWC, /* the WHERE clause */
  96873. int idxTerm /* Index of the term to be analyzed */
  96874. ){
  96875. WhereTerm *pTerm; /* The term to be analyzed */
  96876. WhereMaskSet *pMaskSet; /* Set of table index masks */
  96877. Expr *pExpr; /* The expression to be analyzed */
  96878. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  96879. Bitmask prereqAll; /* Prerequesites of pExpr */
  96880. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  96881. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  96882. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  96883. int noCase = 0; /* LIKE/GLOB distinguishes case */
  96884. int op; /* Top-level operator. pExpr->op */
  96885. Parse *pParse = pWC->pParse; /* Parsing context */
  96886. sqlite3 *db = pParse->db; /* Database connection */
  96887. if( db->mallocFailed ){
  96888. return;
  96889. }
  96890. pTerm = &pWC->a[idxTerm];
  96891. pMaskSet = pWC->pMaskSet;
  96892. pExpr = pTerm->pExpr;
  96893. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  96894. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  96895. op = pExpr->op;
  96896. if( op==TK_IN ){
  96897. assert( pExpr->pRight==0 );
  96898. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  96899. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  96900. }else{
  96901. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  96902. }
  96903. }else if( op==TK_ISNULL ){
  96904. pTerm->prereqRight = 0;
  96905. }else{
  96906. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  96907. }
  96908. prereqAll = exprTableUsage(pMaskSet, pExpr);
  96909. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  96910. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  96911. prereqAll |= x;
  96912. extraRight = x-1; /* ON clause terms may not be used with an index
  96913. ** on left table of a LEFT JOIN. Ticket #3015 */
  96914. }
  96915. pTerm->prereqAll = prereqAll;
  96916. pTerm->leftCursor = -1;
  96917. pTerm->iParent = -1;
  96918. pTerm->eOperator = 0;
  96919. if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
  96920. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  96921. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  96922. if( pLeft->op==TK_COLUMN ){
  96923. pTerm->leftCursor = pLeft->iTable;
  96924. pTerm->u.leftColumn = pLeft->iColumn;
  96925. pTerm->eOperator = operatorMask(op);
  96926. }
  96927. if( pRight && pRight->op==TK_COLUMN ){
  96928. WhereTerm *pNew;
  96929. Expr *pDup;
  96930. if( pTerm->leftCursor>=0 ){
  96931. int idxNew;
  96932. pDup = sqlite3ExprDup(db, pExpr, 0);
  96933. if( db->mallocFailed ){
  96934. sqlite3ExprDelete(db, pDup);
  96935. return;
  96936. }
  96937. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  96938. if( idxNew==0 ) return;
  96939. pNew = &pWC->a[idxNew];
  96940. pNew->iParent = idxTerm;
  96941. pTerm = &pWC->a[idxTerm];
  96942. pTerm->nChild = 1;
  96943. pTerm->wtFlags |= TERM_COPIED;
  96944. }else{
  96945. pDup = pExpr;
  96946. pNew = pTerm;
  96947. }
  96948. exprCommute(pParse, pDup);
  96949. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  96950. pNew->leftCursor = pLeft->iTable;
  96951. pNew->u.leftColumn = pLeft->iColumn;
  96952. testcase( (prereqLeft | extraRight) != prereqLeft );
  96953. pNew->prereqRight = prereqLeft | extraRight;
  96954. pNew->prereqAll = prereqAll;
  96955. pNew->eOperator = operatorMask(pDup->op);
  96956. }
  96957. }
  96958. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  96959. /* If a term is the BETWEEN operator, create two new virtual terms
  96960. ** that define the range that the BETWEEN implements. For example:
  96961. **
  96962. ** a BETWEEN b AND c
  96963. **
  96964. ** is converted into:
  96965. **
  96966. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  96967. **
  96968. ** The two new terms are added onto the end of the WhereClause object.
  96969. ** The new terms are "dynamic" and are children of the original BETWEEN
  96970. ** term. That means that if the BETWEEN term is coded, the children are
  96971. ** skipped. Or, if the children are satisfied by an index, the original
  96972. ** BETWEEN term is skipped.
  96973. */
  96974. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  96975. ExprList *pList = pExpr->x.pList;
  96976. int i;
  96977. static const u8 ops[] = {TK_GE, TK_LE};
  96978. assert( pList!=0 );
  96979. assert( pList->nExpr==2 );
  96980. for(i=0; i<2; i++){
  96981. Expr *pNewExpr;
  96982. int idxNew;
  96983. pNewExpr = sqlite3PExpr(pParse, ops[i],
  96984. sqlite3ExprDup(db, pExpr->pLeft, 0),
  96985. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  96986. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  96987. testcase( idxNew==0 );
  96988. exprAnalyze(pSrc, pWC, idxNew);
  96989. pTerm = &pWC->a[idxTerm];
  96990. pWC->a[idxNew].iParent = idxTerm;
  96991. }
  96992. pTerm->nChild = 2;
  96993. }
  96994. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  96995. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  96996. /* Analyze a term that is composed of two or more subterms connected by
  96997. ** an OR operator.
  96998. */
  96999. else if( pExpr->op==TK_OR ){
  97000. assert( pWC->op==TK_AND );
  97001. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  97002. pTerm = &pWC->a[idxTerm];
  97003. }
  97004. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  97005. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  97006. /* Add constraints to reduce the search space on a LIKE or GLOB
  97007. ** operator.
  97008. **
  97009. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  97010. **
  97011. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  97012. **
  97013. ** The last character of the prefix "abc" is incremented to form the
  97014. ** termination condition "abd".
  97015. */
  97016. if( pWC->op==TK_AND
  97017. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  97018. ){
  97019. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  97020. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  97021. Expr *pNewExpr1;
  97022. Expr *pNewExpr2;
  97023. int idxNew1;
  97024. int idxNew2;
  97025. Token sCollSeqName; /* Name of collating sequence */
  97026. pLeft = pExpr->x.pList->a[1].pExpr;
  97027. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  97028. if( !db->mallocFailed ){
  97029. u8 c, *pC; /* Last character before the first wildcard */
  97030. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  97031. c = *pC;
  97032. if( noCase ){
  97033. /* The point is to increment the last character before the first
  97034. ** wildcard. But if we increment '@', that will push it into the
  97035. ** alphabetic range where case conversions will mess up the
  97036. ** inequality. To avoid this, make sure to also run the full
  97037. ** LIKE on all candidate expressions by clearing the isComplete flag
  97038. */
  97039. if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
  97040. c = sqlite3UpperToLower[c];
  97041. }
  97042. *pC = c + 1;
  97043. }
  97044. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  97045. sCollSeqName.n = 6;
  97046. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  97047. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  97048. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  97049. pStr1, 0);
  97050. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  97051. testcase( idxNew1==0 );
  97052. exprAnalyze(pSrc, pWC, idxNew1);
  97053. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  97054. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  97055. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  97056. pStr2, 0);
  97057. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  97058. testcase( idxNew2==0 );
  97059. exprAnalyze(pSrc, pWC, idxNew2);
  97060. pTerm = &pWC->a[idxTerm];
  97061. if( isComplete ){
  97062. pWC->a[idxNew1].iParent = idxTerm;
  97063. pWC->a[idxNew2].iParent = idxTerm;
  97064. pTerm->nChild = 2;
  97065. }
  97066. }
  97067. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  97068. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97069. /* Add a WO_MATCH auxiliary term to the constraint set if the
  97070. ** current expression is of the form: column MATCH expr.
  97071. ** This information is used by the xBestIndex methods of
  97072. ** virtual tables. The native query optimizer does not attempt
  97073. ** to do anything with MATCH functions.
  97074. */
  97075. if( isMatchOfColumn(pExpr) ){
  97076. int idxNew;
  97077. Expr *pRight, *pLeft;
  97078. WhereTerm *pNewTerm;
  97079. Bitmask prereqColumn, prereqExpr;
  97080. pRight = pExpr->x.pList->a[0].pExpr;
  97081. pLeft = pExpr->x.pList->a[1].pExpr;
  97082. prereqExpr = exprTableUsage(pMaskSet, pRight);
  97083. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  97084. if( (prereqExpr & prereqColumn)==0 ){
  97085. Expr *pNewExpr;
  97086. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  97087. 0, sqlite3ExprDup(db, pRight, 0), 0);
  97088. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  97089. testcase( idxNew==0 );
  97090. pNewTerm = &pWC->a[idxNew];
  97091. pNewTerm->prereqRight = prereqExpr;
  97092. pNewTerm->leftCursor = pLeft->iTable;
  97093. pNewTerm->u.leftColumn = pLeft->iColumn;
  97094. pNewTerm->eOperator = WO_MATCH;
  97095. pNewTerm->iParent = idxTerm;
  97096. pTerm = &pWC->a[idxTerm];
  97097. pTerm->nChild = 1;
  97098. pTerm->wtFlags |= TERM_COPIED;
  97099. pNewTerm->prereqAll = pTerm->prereqAll;
  97100. }
  97101. }
  97102. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  97103. #ifdef SQLITE_ENABLE_STAT3
  97104. /* When sqlite_stat3 histogram data is available an operator of the
  97105. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  97106. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  97107. ** virtual term of that form.
  97108. **
  97109. ** Note that the virtual term must be tagged with TERM_VNULL. This
  97110. ** TERM_VNULL tag will suppress the not-null check at the beginning
  97111. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  97112. ** the start of the loop will prevent any results from being returned.
  97113. */
  97114. if( pExpr->op==TK_NOTNULL
  97115. && pExpr->pLeft->op==TK_COLUMN
  97116. && pExpr->pLeft->iColumn>=0
  97117. ){
  97118. Expr *pNewExpr;
  97119. Expr *pLeft = pExpr->pLeft;
  97120. int idxNew;
  97121. WhereTerm *pNewTerm;
  97122. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  97123. sqlite3ExprDup(db, pLeft, 0),
  97124. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  97125. idxNew = whereClauseInsert(pWC, pNewExpr,
  97126. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  97127. if( idxNew ){
  97128. pNewTerm = &pWC->a[idxNew];
  97129. pNewTerm->prereqRight = 0;
  97130. pNewTerm->leftCursor = pLeft->iTable;
  97131. pNewTerm->u.leftColumn = pLeft->iColumn;
  97132. pNewTerm->eOperator = WO_GT;
  97133. pNewTerm->iParent = idxTerm;
  97134. pTerm = &pWC->a[idxTerm];
  97135. pTerm->nChild = 1;
  97136. pTerm->wtFlags |= TERM_COPIED;
  97137. pNewTerm->prereqAll = pTerm->prereqAll;
  97138. }
  97139. }
  97140. #endif /* SQLITE_ENABLE_STAT */
  97141. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  97142. ** an index for tables to the left of the join.
  97143. */
  97144. pTerm->prereqRight |= extraRight;
  97145. }
  97146. /*
  97147. ** This function searches the expression list passed as the second argument
  97148. ** for an expression of type TK_COLUMN that refers to the same column and
  97149. ** uses the same collation sequence as the iCol'th column of index pIdx.
  97150. ** Argument iBase is the cursor number used for the table that pIdx refers
  97151. ** to.
  97152. **
  97153. ** If such an expression is found, its index in pList->a[] is returned. If
  97154. ** no expression is found, -1 is returned.
  97155. */
  97156. static int findIndexCol(
  97157. Parse *pParse, /* Parse context */
  97158. ExprList *pList, /* Expression list to search */
  97159. int iBase, /* Cursor for table associated with pIdx */
  97160. Index *pIdx, /* Index to match column of */
  97161. int iCol /* Column of index to match */
  97162. ){
  97163. int i;
  97164. const char *zColl = pIdx->azColl[iCol];
  97165. for(i=0; i<pList->nExpr; i++){
  97166. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  97167. if( p->op==TK_COLUMN
  97168. && p->iColumn==pIdx->aiColumn[iCol]
  97169. && p->iTable==iBase
  97170. ){
  97171. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  97172. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  97173. return i;
  97174. }
  97175. }
  97176. }
  97177. return -1;
  97178. }
  97179. /*
  97180. ** This routine determines if pIdx can be used to assist in processing a
  97181. ** DISTINCT qualifier. In other words, it tests whether or not using this
  97182. ** index for the outer loop guarantees that rows with equal values for
  97183. ** all expressions in the pDistinct list are delivered grouped together.
  97184. **
  97185. ** For example, the query
  97186. **
  97187. ** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
  97188. **
  97189. ** can benefit from any index on columns "b" and "c".
  97190. */
  97191. static int isDistinctIndex(
  97192. Parse *pParse, /* Parsing context */
  97193. WhereClause *pWC, /* The WHERE clause */
  97194. Index *pIdx, /* The index being considered */
  97195. int base, /* Cursor number for the table pIdx is on */
  97196. ExprList *pDistinct, /* The DISTINCT expressions */
  97197. int nEqCol /* Number of index columns with == */
  97198. ){
  97199. Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
  97200. int i; /* Iterator variable */
  97201. assert( pDistinct!=0 );
  97202. if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
  97203. testcase( pDistinct->nExpr==BMS-1 );
  97204. /* Loop through all the expressions in the distinct list. If any of them
  97205. ** are not simple column references, return early. Otherwise, test if the
  97206. ** WHERE clause contains a "col=X" clause. If it does, the expression
  97207. ** can be ignored. If it does not, and the column does not belong to the
  97208. ** same table as index pIdx, return early. Finally, if there is no
  97209. ** matching "col=X" expression and the column is on the same table as pIdx,
  97210. ** set the corresponding bit in variable mask.
  97211. */
  97212. for(i=0; i<pDistinct->nExpr; i++){
  97213. WhereTerm *pTerm;
  97214. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  97215. if( p->op!=TK_COLUMN ) return 0;
  97216. pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
  97217. if( pTerm ){
  97218. Expr *pX = pTerm->pExpr;
  97219. CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  97220. CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
  97221. if( p1==p2 ) continue;
  97222. }
  97223. if( p->iTable!=base ) return 0;
  97224. mask |= (((Bitmask)1) << i);
  97225. }
  97226. for(i=nEqCol; mask && i<pIdx->nColumn; i++){
  97227. int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
  97228. if( iExpr<0 ) break;
  97229. mask &= ~(((Bitmask)1) << iExpr);
  97230. }
  97231. return (mask==0);
  97232. }
  97233. /*
  97234. ** Return true if the DISTINCT expression-list passed as the third argument
  97235. ** is redundant. A DISTINCT list is redundant if the database contains a
  97236. ** UNIQUE index that guarantees that the result of the query will be distinct
  97237. ** anyway.
  97238. */
  97239. static int isDistinctRedundant(
  97240. Parse *pParse,
  97241. SrcList *pTabList,
  97242. WhereClause *pWC,
  97243. ExprList *pDistinct
  97244. ){
  97245. Table *pTab;
  97246. Index *pIdx;
  97247. int i;
  97248. int iBase;
  97249. /* If there is more than one table or sub-select in the FROM clause of
  97250. ** this query, then it will not be possible to show that the DISTINCT
  97251. ** clause is redundant. */
  97252. if( pTabList->nSrc!=1 ) return 0;
  97253. iBase = pTabList->a[0].iCursor;
  97254. pTab = pTabList->a[0].pTab;
  97255. /* If any of the expressions is an IPK column on table iBase, then return
  97256. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  97257. ** current SELECT is a correlated sub-query.
  97258. */
  97259. for(i=0; i<pDistinct->nExpr; i++){
  97260. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  97261. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  97262. }
  97263. /* Loop through all indices on the table, checking each to see if it makes
  97264. ** the DISTINCT qualifier redundant. It does so if:
  97265. **
  97266. ** 1. The index is itself UNIQUE, and
  97267. **
  97268. ** 2. All of the columns in the index are either part of the pDistinct
  97269. ** list, or else the WHERE clause contains a term of the form "col=X",
  97270. ** where X is a constant value. The collation sequences of the
  97271. ** comparison and select-list expressions must match those of the index.
  97272. **
  97273. ** 3. All of those index columns for which the WHERE clause does not
  97274. ** contain a "col=X" term are subject to a NOT NULL constraint.
  97275. */
  97276. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97277. if( pIdx->onError==OE_None ) continue;
  97278. for(i=0; i<pIdx->nColumn; i++){
  97279. int iCol = pIdx->aiColumn[i];
  97280. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  97281. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  97282. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  97283. break;
  97284. }
  97285. }
  97286. }
  97287. if( i==pIdx->nColumn ){
  97288. /* This index implies that the DISTINCT qualifier is redundant. */
  97289. return 1;
  97290. }
  97291. }
  97292. return 0;
  97293. }
  97294. /*
  97295. ** Prepare a crude estimate of the logarithm of the input value.
  97296. ** The results need not be exact. This is only used for estimating
  97297. ** the total cost of performing operations with O(logN) or O(NlogN)
  97298. ** complexity. Because N is just a guess, it is no great tragedy if
  97299. ** logN is a little off.
  97300. */
  97301. static double estLog(double N){
  97302. double logN = 1;
  97303. double x = 10;
  97304. while( N>x ){
  97305. logN += 1;
  97306. x *= 10;
  97307. }
  97308. return logN;
  97309. }
  97310. /*
  97311. ** Two routines for printing the content of an sqlite3_index_info
  97312. ** structure. Used for testing and debugging only. If neither
  97313. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  97314. ** are no-ops.
  97315. */
  97316. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  97317. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  97318. int i;
  97319. if( !sqlite3WhereTrace ) return;
  97320. for(i=0; i<p->nConstraint; i++){
  97321. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  97322. i,
  97323. p->aConstraint[i].iColumn,
  97324. p->aConstraint[i].iTermOffset,
  97325. p->aConstraint[i].op,
  97326. p->aConstraint[i].usable);
  97327. }
  97328. for(i=0; i<p->nOrderBy; i++){
  97329. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  97330. i,
  97331. p->aOrderBy[i].iColumn,
  97332. p->aOrderBy[i].desc);
  97333. }
  97334. }
  97335. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  97336. int i;
  97337. if( !sqlite3WhereTrace ) return;
  97338. for(i=0; i<p->nConstraint; i++){
  97339. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  97340. i,
  97341. p->aConstraintUsage[i].argvIndex,
  97342. p->aConstraintUsage[i].omit);
  97343. }
  97344. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  97345. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  97346. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  97347. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  97348. }
  97349. #else
  97350. #define TRACE_IDX_INPUTS(A)
  97351. #define TRACE_IDX_OUTPUTS(A)
  97352. #endif
  97353. /*
  97354. ** Required because bestIndex() is called by bestOrClauseIndex()
  97355. */
  97356. static void bestIndex(WhereBestIdx*);
  97357. /*
  97358. ** This routine attempts to find an scanning strategy that can be used
  97359. ** to optimize an 'OR' expression that is part of a WHERE clause.
  97360. **
  97361. ** The table associated with FROM clause term pSrc may be either a
  97362. ** regular B-Tree table or a virtual table.
  97363. */
  97364. static void bestOrClauseIndex(WhereBestIdx *p){
  97365. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  97366. WhereClause *pWC = p->pWC; /* The WHERE clause */
  97367. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  97368. const int iCur = pSrc->iCursor; /* The cursor of the table */
  97369. const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
  97370. WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
  97371. WhereTerm *pTerm; /* A single term of the WHERE clause */
  97372. /* The OR-clause optimization is disallowed if the INDEXED BY or
  97373. ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
  97374. if( pSrc->notIndexed || pSrc->pIndex!=0 ){
  97375. return;
  97376. }
  97377. if( pWC->wctrlFlags & WHERE_AND_ONLY ){
  97378. return;
  97379. }
  97380. /* Search the WHERE clause terms for a usable WO_OR term. */
  97381. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  97382. if( pTerm->eOperator==WO_OR
  97383. && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
  97384. && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
  97385. ){
  97386. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  97387. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  97388. WhereTerm *pOrTerm;
  97389. int flags = WHERE_MULTI_OR;
  97390. double rTotal = 0;
  97391. double nRow = 0;
  97392. Bitmask used = 0;
  97393. WhereBestIdx sBOI;
  97394. sBOI = *p;
  97395. sBOI.pOrderBy = 0;
  97396. sBOI.pDistinct = 0;
  97397. sBOI.ppIdxInfo = 0;
  97398. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  97399. WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
  97400. (pOrTerm - pOrWC->a), (pTerm - pWC->a)
  97401. ));
  97402. if( pOrTerm->eOperator==WO_AND ){
  97403. sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
  97404. bestIndex(&sBOI);
  97405. }else if( pOrTerm->leftCursor==iCur ){
  97406. WhereClause tempWC;
  97407. tempWC.pParse = pWC->pParse;
  97408. tempWC.pMaskSet = pWC->pMaskSet;
  97409. tempWC.pOuter = pWC;
  97410. tempWC.op = TK_AND;
  97411. tempWC.a = pOrTerm;
  97412. tempWC.wctrlFlags = 0;
  97413. tempWC.nTerm = 1;
  97414. sBOI.pWC = &tempWC;
  97415. bestIndex(&sBOI);
  97416. }else{
  97417. continue;
  97418. }
  97419. rTotal += sBOI.cost.rCost;
  97420. nRow += sBOI.cost.plan.nRow;
  97421. used |= sBOI.cost.used;
  97422. if( rTotal>=p->cost.rCost ) break;
  97423. }
  97424. /* If there is an ORDER BY clause, increase the scan cost to account
  97425. ** for the cost of the sort. */
  97426. if( p->pOrderBy!=0 ){
  97427. WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
  97428. rTotal, rTotal+nRow*estLog(nRow)));
  97429. rTotal += nRow*estLog(nRow);
  97430. }
  97431. /* If the cost of scanning using this OR term for optimization is
  97432. ** less than the current cost stored in pCost, replace the contents
  97433. ** of pCost. */
  97434. WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
  97435. if( rTotal<p->cost.rCost ){
  97436. p->cost.rCost = rTotal;
  97437. p->cost.used = used;
  97438. p->cost.plan.nRow = nRow;
  97439. p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
  97440. p->cost.plan.wsFlags = flags;
  97441. p->cost.plan.u.pTerm = pTerm;
  97442. }
  97443. }
  97444. }
  97445. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  97446. }
  97447. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  97448. /*
  97449. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  97450. ** could be used with an index to access pSrc, assuming an appropriate
  97451. ** index existed.
  97452. */
  97453. static int termCanDriveIndex(
  97454. WhereTerm *pTerm, /* WHERE clause term to check */
  97455. struct SrcList_item *pSrc, /* Table we are trying to access */
  97456. Bitmask notReady /* Tables in outer loops of the join */
  97457. ){
  97458. char aff;
  97459. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  97460. if( pTerm->eOperator!=WO_EQ ) return 0;
  97461. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  97462. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  97463. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  97464. return 1;
  97465. }
  97466. #endif
  97467. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  97468. /*
  97469. ** If the query plan for pSrc specified in pCost is a full table scan
  97470. ** and indexing is allows (if there is no NOT INDEXED clause) and it
  97471. ** possible to construct a transient index that would perform better
  97472. ** than a full table scan even when the cost of constructing the index
  97473. ** is taken into account, then alter the query plan to use the
  97474. ** transient index.
  97475. */
  97476. static void bestAutomaticIndex(WhereBestIdx *p){
  97477. Parse *pParse = p->pParse; /* The parsing context */
  97478. WhereClause *pWC = p->pWC; /* The WHERE clause */
  97479. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  97480. double nTableRow; /* Rows in the input table */
  97481. double logN; /* log(nTableRow) */
  97482. double costTempIdx; /* per-query cost of the transient index */
  97483. WhereTerm *pTerm; /* A single term of the WHERE clause */
  97484. WhereTerm *pWCEnd; /* End of pWC->a[] */
  97485. Table *pTable; /* Table tht might be indexed */
  97486. if( pParse->nQueryLoop<=(double)1 ){
  97487. /* There is no point in building an automatic index for a single scan */
  97488. return;
  97489. }
  97490. if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
  97491. /* Automatic indices are disabled at run-time */
  97492. return;
  97493. }
  97494. if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
  97495. && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
  97496. ){
  97497. /* We already have some kind of index in use for this query. */
  97498. return;
  97499. }
  97500. if( pSrc->viaCoroutine ){
  97501. /* Cannot index a co-routine */
  97502. return;
  97503. }
  97504. if( pSrc->notIndexed ){
  97505. /* The NOT INDEXED clause appears in the SQL. */
  97506. return;
  97507. }
  97508. if( pSrc->isCorrelated ){
  97509. /* The source is a correlated sub-query. No point in indexing it. */
  97510. return;
  97511. }
  97512. assert( pParse->nQueryLoop >= (double)1 );
  97513. pTable = pSrc->pTab;
  97514. nTableRow = pTable->nRowEst;
  97515. logN = estLog(nTableRow);
  97516. costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
  97517. if( costTempIdx>=p->cost.rCost ){
  97518. /* The cost of creating the transient table would be greater than
  97519. ** doing the full table scan */
  97520. return;
  97521. }
  97522. /* Search for any equality comparison term */
  97523. pWCEnd = &pWC->a[pWC->nTerm];
  97524. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  97525. if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
  97526. WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
  97527. p->cost.rCost, costTempIdx));
  97528. p->cost.rCost = costTempIdx;
  97529. p->cost.plan.nRow = logN + 1;
  97530. p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
  97531. p->cost.used = pTerm->prereqRight;
  97532. break;
  97533. }
  97534. }
  97535. }
  97536. #else
  97537. # define bestAutomaticIndex(A) /* no-op */
  97538. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  97539. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  97540. /*
  97541. ** Generate code to construct the Index object for an automatic index
  97542. ** and to set up the WhereLevel object pLevel so that the code generator
  97543. ** makes use of the automatic index.
  97544. */
  97545. static void constructAutomaticIndex(
  97546. Parse *pParse, /* The parsing context */
  97547. WhereClause *pWC, /* The WHERE clause */
  97548. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  97549. Bitmask notReady, /* Mask of cursors that are not available */
  97550. WhereLevel *pLevel /* Write new index here */
  97551. ){
  97552. int nColumn; /* Number of columns in the constructed index */
  97553. WhereTerm *pTerm; /* A single term of the WHERE clause */
  97554. WhereTerm *pWCEnd; /* End of pWC->a[] */
  97555. int nByte; /* Byte of memory needed for pIdx */
  97556. Index *pIdx; /* Object describing the transient index */
  97557. Vdbe *v; /* Prepared statement under construction */
  97558. int addrInit; /* Address of the initialization bypass jump */
  97559. Table *pTable; /* The table being indexed */
  97560. KeyInfo *pKeyinfo; /* Key information for the index */
  97561. int addrTop; /* Top of the index fill loop */
  97562. int regRecord; /* Register holding an index record */
  97563. int n; /* Column counter */
  97564. int i; /* Loop counter */
  97565. int mxBitCol; /* Maximum column in pSrc->colUsed */
  97566. CollSeq *pColl; /* Collating sequence to on a column */
  97567. Bitmask idxCols; /* Bitmap of columns used for indexing */
  97568. Bitmask extraCols; /* Bitmap of additional columns */
  97569. /* Generate code to skip over the creation and initialization of the
  97570. ** transient index on 2nd and subsequent iterations of the loop. */
  97571. v = pParse->pVdbe;
  97572. assert( v!=0 );
  97573. addrInit = sqlite3CodeOnce(pParse);
  97574. /* Count the number of columns that will be added to the index
  97575. ** and used to match WHERE clause constraints */
  97576. nColumn = 0;
  97577. pTable = pSrc->pTab;
  97578. pWCEnd = &pWC->a[pWC->nTerm];
  97579. idxCols = 0;
  97580. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  97581. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  97582. int iCol = pTerm->u.leftColumn;
  97583. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  97584. testcase( iCol==BMS );
  97585. testcase( iCol==BMS-1 );
  97586. if( (idxCols & cMask)==0 ){
  97587. nColumn++;
  97588. idxCols |= cMask;
  97589. }
  97590. }
  97591. }
  97592. assert( nColumn>0 );
  97593. pLevel->plan.nEq = nColumn;
  97594. /* Count the number of additional columns needed to create a
  97595. ** covering index. A "covering index" is an index that contains all
  97596. ** columns that are needed by the query. With a covering index, the
  97597. ** original table never needs to be accessed. Automatic indices must
  97598. ** be a covering index because the index will not be updated if the
  97599. ** original table changes and the index and table cannot both be used
  97600. ** if they go out of sync.
  97601. */
  97602. extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
  97603. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  97604. testcase( pTable->nCol==BMS-1 );
  97605. testcase( pTable->nCol==BMS-2 );
  97606. for(i=0; i<mxBitCol; i++){
  97607. if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
  97608. }
  97609. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  97610. nColumn += pTable->nCol - BMS + 1;
  97611. }
  97612. pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
  97613. /* Construct the Index object to describe this index */
  97614. nByte = sizeof(Index);
  97615. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  97616. nByte += nColumn*sizeof(char*); /* Index.azColl */
  97617. nByte += nColumn; /* Index.aSortOrder */
  97618. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  97619. if( pIdx==0 ) return;
  97620. pLevel->plan.u.pIdx = pIdx;
  97621. pIdx->azColl = (char**)&pIdx[1];
  97622. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  97623. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  97624. pIdx->zName = "auto-index";
  97625. pIdx->nColumn = nColumn;
  97626. pIdx->pTable = pTable;
  97627. n = 0;
  97628. idxCols = 0;
  97629. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  97630. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  97631. int iCol = pTerm->u.leftColumn;
  97632. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  97633. if( (idxCols & cMask)==0 ){
  97634. Expr *pX = pTerm->pExpr;
  97635. idxCols |= cMask;
  97636. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  97637. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  97638. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  97639. n++;
  97640. }
  97641. }
  97642. }
  97643. assert( (u32)n==pLevel->plan.nEq );
  97644. /* Add additional columns needed to make the automatic index into
  97645. ** a covering index */
  97646. for(i=0; i<mxBitCol; i++){
  97647. if( extraCols & (((Bitmask)1)<<i) ){
  97648. pIdx->aiColumn[n] = i;
  97649. pIdx->azColl[n] = "BINARY";
  97650. n++;
  97651. }
  97652. }
  97653. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  97654. for(i=BMS-1; i<pTable->nCol; i++){
  97655. pIdx->aiColumn[n] = i;
  97656. pIdx->azColl[n] = "BINARY";
  97657. n++;
  97658. }
  97659. }
  97660. assert( n==nColumn );
  97661. /* Create the automatic index */
  97662. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  97663. assert( pLevel->iIdxCur>=0 );
  97664. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  97665. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  97666. VdbeComment((v, "for %s", pTable->zName));
  97667. /* Fill the automatic index with content */
  97668. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  97669. regRecord = sqlite3GetTempReg(pParse);
  97670. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
  97671. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  97672. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  97673. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  97674. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  97675. sqlite3VdbeJumpHere(v, addrTop);
  97676. sqlite3ReleaseTempReg(pParse, regRecord);
  97677. /* Jump here when skipping the initialization */
  97678. sqlite3VdbeJumpHere(v, addrInit);
  97679. }
  97680. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  97681. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97682. /*
  97683. ** Allocate and populate an sqlite3_index_info structure. It is the
  97684. ** responsibility of the caller to eventually release the structure
  97685. ** by passing the pointer returned by this function to sqlite3_free().
  97686. */
  97687. static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
  97688. Parse *pParse = p->pParse;
  97689. WhereClause *pWC = p->pWC;
  97690. struct SrcList_item *pSrc = p->pSrc;
  97691. ExprList *pOrderBy = p->pOrderBy;
  97692. int i, j;
  97693. int nTerm;
  97694. struct sqlite3_index_constraint *pIdxCons;
  97695. struct sqlite3_index_orderby *pIdxOrderBy;
  97696. struct sqlite3_index_constraint_usage *pUsage;
  97697. WhereTerm *pTerm;
  97698. int nOrderBy;
  97699. sqlite3_index_info *pIdxInfo;
  97700. WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
  97701. /* Count the number of possible WHERE clause constraints referring
  97702. ** to this virtual table */
  97703. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  97704. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  97705. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  97706. testcase( pTerm->eOperator==WO_IN );
  97707. testcase( pTerm->eOperator==WO_ISNULL );
  97708. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  97709. if( pTerm->wtFlags & TERM_VNULL ) continue;
  97710. nTerm++;
  97711. }
  97712. /* If the ORDER BY clause contains only columns in the current
  97713. ** virtual table then allocate space for the aOrderBy part of
  97714. ** the sqlite3_index_info structure.
  97715. */
  97716. nOrderBy = 0;
  97717. if( pOrderBy ){
  97718. int n = pOrderBy->nExpr;
  97719. for(i=0; i<n; i++){
  97720. Expr *pExpr = pOrderBy->a[i].pExpr;
  97721. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  97722. }
  97723. if( i==n){
  97724. nOrderBy = n;
  97725. }
  97726. }
  97727. /* Allocate the sqlite3_index_info structure
  97728. */
  97729. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  97730. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  97731. + sizeof(*pIdxOrderBy)*nOrderBy );
  97732. if( pIdxInfo==0 ){
  97733. sqlite3ErrorMsg(pParse, "out of memory");
  97734. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  97735. return 0;
  97736. }
  97737. /* Initialize the structure. The sqlite3_index_info structure contains
  97738. ** many fields that are declared "const" to prevent xBestIndex from
  97739. ** changing them. We have to do some funky casting in order to
  97740. ** initialize those fields.
  97741. */
  97742. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  97743. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  97744. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  97745. *(int*)&pIdxInfo->nConstraint = nTerm;
  97746. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  97747. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  97748. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  97749. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  97750. pUsage;
  97751. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  97752. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  97753. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  97754. testcase( pTerm->eOperator==WO_IN );
  97755. testcase( pTerm->eOperator==WO_ISNULL );
  97756. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  97757. if( pTerm->wtFlags & TERM_VNULL ) continue;
  97758. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  97759. pIdxCons[j].iTermOffset = i;
  97760. pIdxCons[j].op = (u8)pTerm->eOperator;
  97761. /* The direct assignment in the previous line is possible only because
  97762. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  97763. ** following asserts verify this fact. */
  97764. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  97765. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  97766. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  97767. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  97768. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  97769. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  97770. assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  97771. j++;
  97772. }
  97773. for(i=0; i<nOrderBy; i++){
  97774. Expr *pExpr = pOrderBy->a[i].pExpr;
  97775. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  97776. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  97777. }
  97778. return pIdxInfo;
  97779. }
  97780. /*
  97781. ** The table object reference passed as the second argument to this function
  97782. ** must represent a virtual table. This function invokes the xBestIndex()
  97783. ** method of the virtual table with the sqlite3_index_info pointer passed
  97784. ** as the argument.
  97785. **
  97786. ** If an error occurs, pParse is populated with an error message and a
  97787. ** non-zero value is returned. Otherwise, 0 is returned and the output
  97788. ** part of the sqlite3_index_info structure is left populated.
  97789. **
  97790. ** Whether or not an error is returned, it is the responsibility of the
  97791. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  97792. ** that this is required.
  97793. */
  97794. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  97795. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  97796. int i;
  97797. int rc;
  97798. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  97799. TRACE_IDX_INPUTS(p);
  97800. rc = pVtab->pModule->xBestIndex(pVtab, p);
  97801. TRACE_IDX_OUTPUTS(p);
  97802. if( rc!=SQLITE_OK ){
  97803. if( rc==SQLITE_NOMEM ){
  97804. pParse->db->mallocFailed = 1;
  97805. }else if( !pVtab->zErrMsg ){
  97806. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  97807. }else{
  97808. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  97809. }
  97810. }
  97811. sqlite3_free(pVtab->zErrMsg);
  97812. pVtab->zErrMsg = 0;
  97813. for(i=0; i<p->nConstraint; i++){
  97814. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  97815. sqlite3ErrorMsg(pParse,
  97816. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  97817. }
  97818. }
  97819. return pParse->nErr;
  97820. }
  97821. /*
  97822. ** Compute the best index for a virtual table.
  97823. **
  97824. ** The best index is computed by the xBestIndex method of the virtual
  97825. ** table module. This routine is really just a wrapper that sets up
  97826. ** the sqlite3_index_info structure that is used to communicate with
  97827. ** xBestIndex.
  97828. **
  97829. ** In a join, this routine might be called multiple times for the
  97830. ** same virtual table. The sqlite3_index_info structure is created
  97831. ** and initialized on the first invocation and reused on all subsequent
  97832. ** invocations. The sqlite3_index_info structure is also used when
  97833. ** code is generated to access the virtual table. The whereInfoDelete()
  97834. ** routine takes care of freeing the sqlite3_index_info structure after
  97835. ** everybody has finished with it.
  97836. */
  97837. static void bestVirtualIndex(WhereBestIdx *p){
  97838. Parse *pParse = p->pParse; /* The parsing context */
  97839. WhereClause *pWC = p->pWC; /* The WHERE clause */
  97840. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  97841. Table *pTab = pSrc->pTab;
  97842. sqlite3_index_info *pIdxInfo;
  97843. struct sqlite3_index_constraint *pIdxCons;
  97844. struct sqlite3_index_constraint_usage *pUsage;
  97845. WhereTerm *pTerm;
  97846. int i, j;
  97847. int nOrderBy;
  97848. double rCost;
  97849. /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
  97850. ** malloc in allocateIndexInfo() fails and this function returns leaving
  97851. ** wsFlags in an uninitialized state, the caller may behave unpredictably.
  97852. */
  97853. memset(&p->cost, 0, sizeof(p->cost));
  97854. p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
  97855. /* If the sqlite3_index_info structure has not been previously
  97856. ** allocated and initialized, then allocate and initialize it now.
  97857. */
  97858. pIdxInfo = *p->ppIdxInfo;
  97859. if( pIdxInfo==0 ){
  97860. *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
  97861. }
  97862. if( pIdxInfo==0 ){
  97863. return;
  97864. }
  97865. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  97866. ** to will have been initialized, either during the current invocation or
  97867. ** during some prior invocation. Now we just have to customize the
  97868. ** details of pIdxInfo for the current invocation and pass it to
  97869. ** xBestIndex.
  97870. */
  97871. /* The module name must be defined. Also, by this point there must
  97872. ** be a pointer to an sqlite3_vtab structure. Otherwise
  97873. ** sqlite3ViewGetColumnNames() would have picked up the error.
  97874. */
  97875. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  97876. assert( sqlite3GetVTable(pParse->db, pTab) );
  97877. /* Set the aConstraint[].usable fields and initialize all
  97878. ** output variables to zero.
  97879. **
  97880. ** aConstraint[].usable is true for constraints where the right-hand
  97881. ** side contains only references to tables to the left of the current
  97882. ** table. In other words, if the constraint is of the form:
  97883. **
  97884. ** column = expr
  97885. **
  97886. ** and we are evaluating a join, then the constraint on column is
  97887. ** only valid if all tables referenced in expr occur to the left
  97888. ** of the table containing column.
  97889. **
  97890. ** The aConstraints[] array contains entries for all constraints
  97891. ** on the current table. That way we only have to compute it once
  97892. ** even though we might try to pick the best index multiple times.
  97893. ** For each attempt at picking an index, the order of tables in the
  97894. ** join might be different so we have to recompute the usable flag
  97895. ** each time.
  97896. */
  97897. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  97898. pUsage = pIdxInfo->aConstraintUsage;
  97899. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  97900. j = pIdxCons->iTermOffset;
  97901. pTerm = &pWC->a[j];
  97902. pIdxCons->usable = (pTerm->prereqRight&p->notReady) ? 0 : 1;
  97903. }
  97904. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  97905. if( pIdxInfo->needToFreeIdxStr ){
  97906. sqlite3_free(pIdxInfo->idxStr);
  97907. }
  97908. pIdxInfo->idxStr = 0;
  97909. pIdxInfo->idxNum = 0;
  97910. pIdxInfo->needToFreeIdxStr = 0;
  97911. pIdxInfo->orderByConsumed = 0;
  97912. /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  97913. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
  97914. nOrderBy = pIdxInfo->nOrderBy;
  97915. if( !p->pOrderBy ){
  97916. pIdxInfo->nOrderBy = 0;
  97917. }
  97918. if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
  97919. return;
  97920. }
  97921. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  97922. for(i=0; i<pIdxInfo->nConstraint; i++){
  97923. if( pUsage[i].argvIndex>0 ){
  97924. p->cost.used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
  97925. }
  97926. }
  97927. /* If there is an ORDER BY clause, and the selected virtual table index
  97928. ** does not satisfy it, increase the cost of the scan accordingly. This
  97929. ** matches the processing for non-virtual tables in bestBtreeIndex().
  97930. */
  97931. rCost = pIdxInfo->estimatedCost;
  97932. if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
  97933. rCost += estLog(rCost)*rCost;
  97934. }
  97935. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  97936. ** inital value of lowestCost in this loop. If it is, then the
  97937. ** (cost<lowestCost) test below will never be true.
  97938. **
  97939. ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
  97940. ** is defined.
  97941. */
  97942. if( (SQLITE_BIG_DBL/((double)2))<rCost ){
  97943. p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
  97944. }else{
  97945. p->cost.rCost = rCost;
  97946. }
  97947. p->cost.plan.u.pVtabIdx = pIdxInfo;
  97948. if( pIdxInfo->orderByConsumed ){
  97949. p->cost.plan.wsFlags |= WHERE_ORDERED;
  97950. p->cost.plan.nOBSat = nOrderBy;
  97951. }else{
  97952. p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
  97953. }
  97954. p->cost.plan.nEq = 0;
  97955. pIdxInfo->nOrderBy = nOrderBy;
  97956. /* Try to find a more efficient access pattern by using multiple indexes
  97957. ** to optimize an OR expression within the WHERE clause.
  97958. */
  97959. bestOrClauseIndex(p);
  97960. }
  97961. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  97962. #ifdef SQLITE_ENABLE_STAT3
  97963. /*
  97964. ** Estimate the location of a particular key among all keys in an
  97965. ** index. Store the results in aStat as follows:
  97966. **
  97967. ** aStat[0] Est. number of rows less than pVal
  97968. ** aStat[1] Est. number of rows equal to pVal
  97969. **
  97970. ** Return SQLITE_OK on success.
  97971. */
  97972. static int whereKeyStats(
  97973. Parse *pParse, /* Database connection */
  97974. Index *pIdx, /* Index to consider domain of */
  97975. sqlite3_value *pVal, /* Value to consider */
  97976. int roundUp, /* Round up if true. Round down if false */
  97977. tRowcnt *aStat /* OUT: stats written here */
  97978. ){
  97979. tRowcnt n;
  97980. IndexSample *aSample;
  97981. int i, eType;
  97982. int isEq = 0;
  97983. i64 v;
  97984. double r, rS;
  97985. assert( roundUp==0 || roundUp==1 );
  97986. assert( pIdx->nSample>0 );
  97987. if( pVal==0 ) return SQLITE_ERROR;
  97988. n = pIdx->aiRowEst[0];
  97989. aSample = pIdx->aSample;
  97990. eType = sqlite3_value_type(pVal);
  97991. if( eType==SQLITE_INTEGER ){
  97992. v = sqlite3_value_int64(pVal);
  97993. r = (i64)v;
  97994. for(i=0; i<pIdx->nSample; i++){
  97995. if( aSample[i].eType==SQLITE_NULL ) continue;
  97996. if( aSample[i].eType>=SQLITE_TEXT ) break;
  97997. if( aSample[i].eType==SQLITE_INTEGER ){
  97998. if( aSample[i].u.i>=v ){
  97999. isEq = aSample[i].u.i==v;
  98000. break;
  98001. }
  98002. }else{
  98003. assert( aSample[i].eType==SQLITE_FLOAT );
  98004. if( aSample[i].u.r>=r ){
  98005. isEq = aSample[i].u.r==r;
  98006. break;
  98007. }
  98008. }
  98009. }
  98010. }else if( eType==SQLITE_FLOAT ){
  98011. r = sqlite3_value_double(pVal);
  98012. for(i=0; i<pIdx->nSample; i++){
  98013. if( aSample[i].eType==SQLITE_NULL ) continue;
  98014. if( aSample[i].eType>=SQLITE_TEXT ) break;
  98015. if( aSample[i].eType==SQLITE_FLOAT ){
  98016. rS = aSample[i].u.r;
  98017. }else{
  98018. rS = aSample[i].u.i;
  98019. }
  98020. if( rS>=r ){
  98021. isEq = rS==r;
  98022. break;
  98023. }
  98024. }
  98025. }else if( eType==SQLITE_NULL ){
  98026. i = 0;
  98027. if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
  98028. }else{
  98029. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  98030. for(i=0; i<pIdx->nSample; i++){
  98031. if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
  98032. break;
  98033. }
  98034. }
  98035. if( i<pIdx->nSample ){
  98036. sqlite3 *db = pParse->db;
  98037. CollSeq *pColl;
  98038. const u8 *z;
  98039. if( eType==SQLITE_BLOB ){
  98040. z = (const u8 *)sqlite3_value_blob(pVal);
  98041. pColl = db->pDfltColl;
  98042. assert( pColl->enc==SQLITE_UTF8 );
  98043. }else{
  98044. pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
  98045. if( pColl==0 ){
  98046. return SQLITE_ERROR;
  98047. }
  98048. z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
  98049. if( !z ){
  98050. return SQLITE_NOMEM;
  98051. }
  98052. assert( z && pColl && pColl->xCmp );
  98053. }
  98054. n = sqlite3ValueBytes(pVal, pColl->enc);
  98055. for(; i<pIdx->nSample; i++){
  98056. int c;
  98057. int eSampletype = aSample[i].eType;
  98058. if( eSampletype<eType ) continue;
  98059. if( eSampletype!=eType ) break;
  98060. #ifndef SQLITE_OMIT_UTF16
  98061. if( pColl->enc!=SQLITE_UTF8 ){
  98062. int nSample;
  98063. char *zSample = sqlite3Utf8to16(
  98064. db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
  98065. );
  98066. if( !zSample ){
  98067. assert( db->mallocFailed );
  98068. return SQLITE_NOMEM;
  98069. }
  98070. c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
  98071. sqlite3DbFree(db, zSample);
  98072. }else
  98073. #endif
  98074. {
  98075. c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
  98076. }
  98077. if( c>=0 ){
  98078. if( c==0 ) isEq = 1;
  98079. break;
  98080. }
  98081. }
  98082. }
  98083. }
  98084. /* At this point, aSample[i] is the first sample that is greater than
  98085. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  98086. ** than pVal. If aSample[i]==pVal, then isEq==1.
  98087. */
  98088. if( isEq ){
  98089. assert( i<pIdx->nSample );
  98090. aStat[0] = aSample[i].nLt;
  98091. aStat[1] = aSample[i].nEq;
  98092. }else{
  98093. tRowcnt iLower, iUpper, iGap;
  98094. if( i==0 ){
  98095. iLower = 0;
  98096. iUpper = aSample[0].nLt;
  98097. }else{
  98098. iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
  98099. iLower = aSample[i-1].nEq + aSample[i-1].nLt;
  98100. }
  98101. aStat[1] = pIdx->avgEq;
  98102. if( iLower>=iUpper ){
  98103. iGap = 0;
  98104. }else{
  98105. iGap = iUpper - iLower;
  98106. }
  98107. if( roundUp ){
  98108. iGap = (iGap*2)/3;
  98109. }else{
  98110. iGap = iGap/3;
  98111. }
  98112. aStat[0] = iLower + iGap;
  98113. }
  98114. return SQLITE_OK;
  98115. }
  98116. #endif /* SQLITE_ENABLE_STAT3 */
  98117. /*
  98118. ** If expression pExpr represents a literal value, set *pp to point to
  98119. ** an sqlite3_value structure containing the same value, with affinity
  98120. ** aff applied to it, before returning. It is the responsibility of the
  98121. ** caller to eventually release this structure by passing it to
  98122. ** sqlite3ValueFree().
  98123. **
  98124. ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
  98125. ** is an SQL variable that currently has a non-NULL value bound to it,
  98126. ** create an sqlite3_value structure containing this value, again with
  98127. ** affinity aff applied to it, instead.
  98128. **
  98129. ** If neither of the above apply, set *pp to NULL.
  98130. **
  98131. ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
  98132. */
  98133. #ifdef SQLITE_ENABLE_STAT3
  98134. static int valueFromExpr(
  98135. Parse *pParse,
  98136. Expr *pExpr,
  98137. u8 aff,
  98138. sqlite3_value **pp
  98139. ){
  98140. if( pExpr->op==TK_VARIABLE
  98141. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  98142. ){
  98143. int iVar = pExpr->iColumn;
  98144. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  98145. *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
  98146. return SQLITE_OK;
  98147. }
  98148. return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
  98149. }
  98150. #endif
  98151. /*
  98152. ** This function is used to estimate the number of rows that will be visited
  98153. ** by scanning an index for a range of values. The range may have an upper
  98154. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  98155. ** and lower bounds are represented by pLower and pUpper respectively. For
  98156. ** example, assuming that index p is on t1(a):
  98157. **
  98158. ** ... FROM t1 WHERE a > ? AND a < ? ...
  98159. ** |_____| |_____|
  98160. ** | |
  98161. ** pLower pUpper
  98162. **
  98163. ** If either of the upper or lower bound is not present, then NULL is passed in
  98164. ** place of the corresponding WhereTerm.
  98165. **
  98166. ** The nEq parameter is passed the index of the index column subject to the
  98167. ** range constraint. Or, equivalently, the number of equality constraints
  98168. ** optimized by the proposed index scan. For example, assuming index p is
  98169. ** on t1(a, b), and the SQL query is:
  98170. **
  98171. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  98172. **
  98173. ** then nEq should be passed the value 1 (as the range restricted column,
  98174. ** b, is the second left-most column of the index). Or, if the query is:
  98175. **
  98176. ** ... FROM t1 WHERE a > ? AND a < ? ...
  98177. **
  98178. ** then nEq should be passed 0.
  98179. **
  98180. ** The returned value is an integer divisor to reduce the estimated
  98181. ** search space. A return value of 1 means that range constraints are
  98182. ** no help at all. A return value of 2 means range constraints are
  98183. ** expected to reduce the search space by half. And so forth...
  98184. **
  98185. ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
  98186. ** reduces the search space by a factor of 4. Hence a single constraint (x>?)
  98187. ** results in a return of 4 and a range constraint (x>? AND x<?) results
  98188. ** in a return of 16.
  98189. */
  98190. static int whereRangeScanEst(
  98191. Parse *pParse, /* Parsing & code generating context */
  98192. Index *p, /* The index containing the range-compared column; "x" */
  98193. int nEq, /* index into p->aCol[] of the range-compared column */
  98194. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  98195. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  98196. double *pRangeDiv /* OUT: Reduce search space by this divisor */
  98197. ){
  98198. int rc = SQLITE_OK;
  98199. #ifdef SQLITE_ENABLE_STAT3
  98200. if( nEq==0 && p->nSample ){
  98201. sqlite3_value *pRangeVal;
  98202. tRowcnt iLower = 0;
  98203. tRowcnt iUpper = p->aiRowEst[0];
  98204. tRowcnt a[2];
  98205. u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  98206. if( pLower ){
  98207. Expr *pExpr = pLower->pExpr->pRight;
  98208. rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
  98209. assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
  98210. if( rc==SQLITE_OK
  98211. && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
  98212. ){
  98213. iLower = a[0];
  98214. if( pLower->eOperator==WO_GT ) iLower += a[1];
  98215. }
  98216. sqlite3ValueFree(pRangeVal);
  98217. }
  98218. if( rc==SQLITE_OK && pUpper ){
  98219. Expr *pExpr = pUpper->pExpr->pRight;
  98220. rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
  98221. assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
  98222. if( rc==SQLITE_OK
  98223. && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
  98224. ){
  98225. iUpper = a[0];
  98226. if( pUpper->eOperator==WO_LE ) iUpper += a[1];
  98227. }
  98228. sqlite3ValueFree(pRangeVal);
  98229. }
  98230. if( rc==SQLITE_OK ){
  98231. if( iUpper<=iLower ){
  98232. *pRangeDiv = (double)p->aiRowEst[0];
  98233. }else{
  98234. *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
  98235. }
  98236. WHERETRACE(("range scan regions: %u..%u div=%g\n",
  98237. (u32)iLower, (u32)iUpper, *pRangeDiv));
  98238. return SQLITE_OK;
  98239. }
  98240. }
  98241. #else
  98242. UNUSED_PARAMETER(pParse);
  98243. UNUSED_PARAMETER(p);
  98244. UNUSED_PARAMETER(nEq);
  98245. #endif
  98246. assert( pLower || pUpper );
  98247. *pRangeDiv = (double)1;
  98248. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
  98249. if( pUpper ) *pRangeDiv *= (double)4;
  98250. return rc;
  98251. }
  98252. #ifdef SQLITE_ENABLE_STAT3
  98253. /*
  98254. ** Estimate the number of rows that will be returned based on
  98255. ** an equality constraint x=VALUE and where that VALUE occurs in
  98256. ** the histogram data. This only works when x is the left-most
  98257. ** column of an index and sqlite_stat3 histogram data is available
  98258. ** for that index. When pExpr==NULL that means the constraint is
  98259. ** "x IS NULL" instead of "x=VALUE".
  98260. **
  98261. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  98262. ** If unable to make an estimate, leave *pnRow unchanged and return
  98263. ** non-zero.
  98264. **
  98265. ** This routine can fail if it is unable to load a collating sequence
  98266. ** required for string comparison, or if unable to allocate memory
  98267. ** for a UTF conversion required for comparison. The error is stored
  98268. ** in the pParse structure.
  98269. */
  98270. static int whereEqualScanEst(
  98271. Parse *pParse, /* Parsing & code generating context */
  98272. Index *p, /* The index whose left-most column is pTerm */
  98273. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  98274. double *pnRow /* Write the revised row estimate here */
  98275. ){
  98276. sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
  98277. u8 aff; /* Column affinity */
  98278. int rc; /* Subfunction return code */
  98279. tRowcnt a[2]; /* Statistics */
  98280. assert( p->aSample!=0 );
  98281. assert( p->nSample>0 );
  98282. aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  98283. if( pExpr ){
  98284. rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
  98285. if( rc ) goto whereEqualScanEst_cancel;
  98286. }else{
  98287. pRhs = sqlite3ValueNew(pParse->db);
  98288. }
  98289. if( pRhs==0 ) return SQLITE_NOTFOUND;
  98290. rc = whereKeyStats(pParse, p, pRhs, 0, a);
  98291. if( rc==SQLITE_OK ){
  98292. WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
  98293. *pnRow = a[1];
  98294. }
  98295. whereEqualScanEst_cancel:
  98296. sqlite3ValueFree(pRhs);
  98297. return rc;
  98298. }
  98299. #endif /* defined(SQLITE_ENABLE_STAT3) */
  98300. #ifdef SQLITE_ENABLE_STAT3
  98301. /*
  98302. ** Estimate the number of rows that will be returned based on
  98303. ** an IN constraint where the right-hand side of the IN operator
  98304. ** is a list of values. Example:
  98305. **
  98306. ** WHERE x IN (1,2,3,4)
  98307. **
  98308. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  98309. ** If unable to make an estimate, leave *pnRow unchanged and return
  98310. ** non-zero.
  98311. **
  98312. ** This routine can fail if it is unable to load a collating sequence
  98313. ** required for string comparison, or if unable to allocate memory
  98314. ** for a UTF conversion required for comparison. The error is stored
  98315. ** in the pParse structure.
  98316. */
  98317. static int whereInScanEst(
  98318. Parse *pParse, /* Parsing & code generating context */
  98319. Index *p, /* The index whose left-most column is pTerm */
  98320. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  98321. double *pnRow /* Write the revised row estimate here */
  98322. ){
  98323. int rc = SQLITE_OK; /* Subfunction return code */
  98324. double nEst; /* Number of rows for a single term */
  98325. double nRowEst = (double)0; /* New estimate of the number of rows */
  98326. int i; /* Loop counter */
  98327. assert( p->aSample!=0 );
  98328. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  98329. nEst = p->aiRowEst[0];
  98330. rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
  98331. nRowEst += nEst;
  98332. }
  98333. if( rc==SQLITE_OK ){
  98334. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  98335. *pnRow = nRowEst;
  98336. WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
  98337. }
  98338. return rc;
  98339. }
  98340. #endif /* defined(SQLITE_ENABLE_STAT3) */
  98341. /*
  98342. ** Check to see if column iCol of the table with cursor iTab will appear
  98343. ** in sorted order according to the current query plan.
  98344. **
  98345. ** Return values:
  98346. **
  98347. ** 0 iCol is not ordered
  98348. ** 1 iCol has only a single value
  98349. ** 2 iCol is in ASC order
  98350. ** 3 iCol is in DESC order
  98351. */
  98352. static int isOrderedColumn(
  98353. WhereBestIdx *p,
  98354. int iTab,
  98355. int iCol
  98356. ){
  98357. int i, j;
  98358. WhereLevel *pLevel = &p->aLevel[p->i-1];
  98359. Index *pIdx;
  98360. u8 sortOrder;
  98361. for(i=p->i-1; i>=0; i--, pLevel--){
  98362. if( pLevel->iTabCur!=iTab ) continue;
  98363. if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  98364. return 1;
  98365. }
  98366. assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
  98367. if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
  98368. if( iCol<0 ){
  98369. sortOrder = 0;
  98370. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  98371. }else{
  98372. int n = pIdx->nColumn;
  98373. for(j=0; j<n; j++){
  98374. if( iCol==pIdx->aiColumn[j] ) break;
  98375. }
  98376. if( j>=n ) return 0;
  98377. sortOrder = pIdx->aSortOrder[j];
  98378. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  98379. }
  98380. }else{
  98381. if( iCol!=(-1) ) return 0;
  98382. sortOrder = 0;
  98383. testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
  98384. }
  98385. if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
  98386. assert( sortOrder==0 || sortOrder==1 );
  98387. testcase( sortOrder==1 );
  98388. sortOrder = 1 - sortOrder;
  98389. }
  98390. return sortOrder+2;
  98391. }
  98392. return 0;
  98393. }
  98394. /*
  98395. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  98396. ** clause, either in whole or in part. The return value is the
  98397. ** cumulative number of terms in the ORDER BY clause that are satisfied
  98398. ** by the index pIdx and other indices in outer loops.
  98399. **
  98400. ** The table being queried has a cursor number of "base". pIdx is the
  98401. ** index that is postulated for use to access the table.
  98402. **
  98403. ** The *pbRev value is set to 0 order 1 depending on whether or not
  98404. ** pIdx should be run in the forward order or in reverse order.
  98405. */
  98406. static int isSortingIndex(
  98407. WhereBestIdx *p, /* Best index search context */
  98408. Index *pIdx, /* The index we are testing */
  98409. int base, /* Cursor number for the table to be sorted */
  98410. int *pbRev /* Set to 1 for reverse-order scan of pIdx */
  98411. ){
  98412. int i; /* Number of pIdx terms used */
  98413. int j; /* Number of ORDER BY terms satisfied */
  98414. int sortOrder = 2; /* 0: forward. 1: backward. 2: unknown */
  98415. int nTerm; /* Number of ORDER BY terms */
  98416. struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
  98417. Table *pTab = pIdx->pTable; /* Table that owns index pIdx */
  98418. ExprList *pOrderBy; /* The ORDER BY clause */
  98419. Parse *pParse = p->pParse; /* Parser context */
  98420. sqlite3 *db = pParse->db; /* Database connection */
  98421. int nPriorSat; /* ORDER BY terms satisfied by outer loops */
  98422. int seenRowid = 0; /* True if an ORDER BY rowid term is seen */
  98423. int uniqueNotNull; /* pIdx is UNIQUE with all terms are NOT NULL */
  98424. if( p->i==0 ){
  98425. nPriorSat = 0;
  98426. }else{
  98427. nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
  98428. if( (p->aLevel[p->i-1].plan.wsFlags & WHERE_ORDERED)==0 ){
  98429. /* This loop cannot be ordered unless the next outer loop is
  98430. ** also ordered */
  98431. return nPriorSat;
  98432. }
  98433. if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
  98434. /* Only look at the outer-most loop if the OrderByIdxJoin
  98435. ** optimization is disabled */
  98436. return nPriorSat;
  98437. }
  98438. }
  98439. pOrderBy = p->pOrderBy;
  98440. assert( pOrderBy!=0 );
  98441. if( pIdx->bUnordered ){
  98442. /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
  98443. ** be used for sorting */
  98444. return nPriorSat;
  98445. }
  98446. nTerm = pOrderBy->nExpr;
  98447. uniqueNotNull = pIdx->onError!=OE_None;
  98448. assert( nTerm>0 );
  98449. /* Argument pIdx must either point to a 'real' named index structure,
  98450. ** or an index structure allocated on the stack by bestBtreeIndex() to
  98451. ** represent the rowid index that is part of every table. */
  98452. assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
  98453. /* Match terms of the ORDER BY clause against columns of
  98454. ** the index.
  98455. **
  98456. ** Note that indices have pIdx->nColumn regular columns plus
  98457. ** one additional column containing the rowid. The rowid column
  98458. ** of the index is also allowed to match against the ORDER BY
  98459. ** clause.
  98460. */
  98461. j = nPriorSat;
  98462. for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
  98463. Expr *pOBExpr; /* The expression of the ORDER BY pOBItem */
  98464. CollSeq *pColl; /* The collating sequence of pOBExpr */
  98465. int termSortOrder; /* Sort order for this term */
  98466. int iColumn; /* The i-th column of the index. -1 for rowid */
  98467. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  98468. int isEq; /* Subject to an == or IS NULL constraint */
  98469. int isMatch; /* ORDER BY term matches the index term */
  98470. const char *zColl; /* Name of collating sequence for i-th index term */
  98471. WhereTerm *pConstraint; /* A constraint in the WHERE clause */
  98472. /* If the next term of the ORDER BY clause refers to anything other than
  98473. ** a column in the "base" table, then this index will not be of any
  98474. ** further use in handling the ORDER BY. */
  98475. pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
  98476. if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
  98477. break;
  98478. }
  98479. /* Find column number and collating sequence for the next entry
  98480. ** in the index */
  98481. if( pIdx->zName && i<pIdx->nColumn ){
  98482. iColumn = pIdx->aiColumn[i];
  98483. if( iColumn==pIdx->pTable->iPKey ){
  98484. iColumn = -1;
  98485. }
  98486. iSortOrder = pIdx->aSortOrder[i];
  98487. zColl = pIdx->azColl[i];
  98488. assert( zColl!=0 );
  98489. }else{
  98490. iColumn = -1;
  98491. iSortOrder = 0;
  98492. zColl = 0;
  98493. }
  98494. /* Check to see if the column number and collating sequence of the
  98495. ** index match the column number and collating sequence of the ORDER BY
  98496. ** clause entry. Set isMatch to 1 if they both match. */
  98497. if( pOBExpr->iColumn==iColumn ){
  98498. if( zColl ){
  98499. pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
  98500. if( !pColl ) pColl = db->pDfltColl;
  98501. isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
  98502. }else{
  98503. isMatch = 1;
  98504. }
  98505. }else{
  98506. isMatch = 0;
  98507. }
  98508. /* termSortOrder is 0 or 1 for whether or not the access loop should
  98509. ** run forward or backwards (respectively) in order to satisfy this
  98510. ** term of the ORDER BY clause. */
  98511. assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
  98512. assert( iSortOrder==0 || iSortOrder==1 );
  98513. termSortOrder = iSortOrder ^ pOBItem->sortOrder;
  98514. /* If X is the column in the index and ORDER BY clause, check to see
  98515. ** if there are any X= or X IS NULL constraints in the WHERE clause. */
  98516. pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
  98517. WO_EQ|WO_ISNULL|WO_IN, pIdx);
  98518. if( pConstraint==0 ){
  98519. isEq = 0;
  98520. }else if( pConstraint->eOperator==WO_IN ){
  98521. /* Constraints of the form: "X IN ..." cannot be used with an ORDER BY
  98522. ** because we do not know in what order the values on the RHS of the IN
  98523. ** operator will occur. */
  98524. break;
  98525. }else if( pConstraint->eOperator==WO_ISNULL ){
  98526. uniqueNotNull = 0;
  98527. isEq = 1; /* "X IS NULL" means X has only a single value */
  98528. }else if( pConstraint->prereqRight==0 ){
  98529. isEq = 1; /* Constraint "X=constant" means X has only a single value */
  98530. }else{
  98531. Expr *pRight = pConstraint->pExpr->pRight;
  98532. if( pRight->op==TK_COLUMN ){
  98533. WHERETRACE((" .. isOrderedColumn(tab=%d,col=%d)",
  98534. pRight->iTable, pRight->iColumn));
  98535. isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
  98536. WHERETRACE((" -> isEq=%d\n", isEq));
  98537. /* If the constraint is of the form X=Y where Y is an ordered value
  98538. ** in an outer loop, then make sure the sort order of Y matches the
  98539. ** sort order required for X. */
  98540. if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
  98541. testcase( isEq==2 );
  98542. testcase( isEq==3 );
  98543. break;
  98544. }
  98545. }else{
  98546. isEq = 0; /* "X=expr" places no ordering constraints on X */
  98547. }
  98548. }
  98549. if( !isMatch ){
  98550. if( isEq==0 ){
  98551. break;
  98552. }else{
  98553. continue;
  98554. }
  98555. }else if( isEq!=1 ){
  98556. if( sortOrder==2 ){
  98557. sortOrder = termSortOrder;
  98558. }else if( termSortOrder!=sortOrder ){
  98559. break;
  98560. }
  98561. }
  98562. j++;
  98563. pOBItem++;
  98564. if( iColumn<0 ){
  98565. seenRowid = 1;
  98566. break;
  98567. }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
  98568. testcase( isEq==0 );
  98569. testcase( isEq==2 );
  98570. testcase( isEq==3 );
  98571. uniqueNotNull = 0;
  98572. }
  98573. }
  98574. /* If we have not found at least one ORDER BY term that matches the
  98575. ** index, then show no progress. */
  98576. if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
  98577. /* Return the necessary scan order back to the caller */
  98578. *pbRev = sortOrder & 1;
  98579. /* If there was an "ORDER BY rowid" term that matched, or it is only
  98580. ** possible for a single row from this table to match, then skip over
  98581. ** any additional ORDER BY terms dealing with this table.
  98582. */
  98583. if( seenRowid || (uniqueNotNull && i>=pIdx->nColumn) ){
  98584. /* Advance j over additional ORDER BY terms associated with base */
  98585. WhereMaskSet *pMS = p->pWC->pMaskSet;
  98586. Bitmask m = ~getMask(pMS, base);
  98587. while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
  98588. j++;
  98589. }
  98590. }
  98591. return j;
  98592. }
  98593. /*
  98594. ** Find the best query plan for accessing a particular table. Write the
  98595. ** best query plan and its cost into the p->cost.
  98596. **
  98597. ** The lowest cost plan wins. The cost is an estimate of the amount of
  98598. ** CPU and disk I/O needed to process the requested result.
  98599. ** Factors that influence cost include:
  98600. **
  98601. ** * The estimated number of rows that will be retrieved. (The
  98602. ** fewer the better.)
  98603. **
  98604. ** * Whether or not sorting must occur.
  98605. **
  98606. ** * Whether or not there must be separate lookups in the
  98607. ** index and in the main table.
  98608. **
  98609. ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
  98610. ** the SQL statement, then this function only considers plans using the
  98611. ** named index. If no such plan is found, then the returned cost is
  98612. ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
  98613. ** then the cost is calculated in the usual way.
  98614. **
  98615. ** If a NOT INDEXED clause was attached to the table
  98616. ** in the SELECT statement, then no indexes are considered. However, the
  98617. ** selected plan may still take advantage of the built-in rowid primary key
  98618. ** index.
  98619. */
  98620. static void bestBtreeIndex(WhereBestIdx *p){
  98621. Parse *pParse = p->pParse; /* The parsing context */
  98622. WhereClause *pWC = p->pWC; /* The WHERE clause */
  98623. struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
  98624. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  98625. Index *pProbe; /* An index we are evaluating */
  98626. Index *pIdx; /* Copy of pProbe, or zero for IPK index */
  98627. int eqTermMask; /* Current mask of valid equality operators */
  98628. int idxEqTermMask; /* Index mask of valid equality operators */
  98629. Index sPk; /* A fake index object for the primary key */
  98630. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  98631. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  98632. int wsFlagMask; /* Allowed flags in p->cost.plan.wsFlag */
  98633. int nPriorSat; /* ORDER BY terms satisfied by outer loops */
  98634. int nOrderBy; /* Number of ORDER BY terms */
  98635. char bSortInit; /* Initializer for bSort in inner loop */
  98636. char bDistInit; /* Initializer for bDist in inner loop */
  98637. /* Initialize the cost to a worst-case value */
  98638. memset(&p->cost, 0, sizeof(p->cost));
  98639. p->cost.rCost = SQLITE_BIG_DBL;
  98640. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  98641. ** use an index to satisfy IS NULL constraints on that table. This is
  98642. ** because columns might end up being NULL if the table does not match -
  98643. ** a circumstance which the index cannot help us discover. Ticket #2177.
  98644. */
  98645. if( pSrc->jointype & JT_LEFT ){
  98646. idxEqTermMask = WO_EQ|WO_IN;
  98647. }else{
  98648. idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  98649. }
  98650. if( pSrc->pIndex ){
  98651. /* An INDEXED BY clause specifies a particular index to use */
  98652. pIdx = pProbe = pSrc->pIndex;
  98653. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  98654. eqTermMask = idxEqTermMask;
  98655. }else{
  98656. /* There is no INDEXED BY clause. Create a fake Index object in local
  98657. ** variable sPk to represent the rowid primary key index. Make this
  98658. ** fake index the first in a chain of Index objects with all of the real
  98659. ** indices to follow */
  98660. Index *pFirst; /* First of real indices on the table */
  98661. memset(&sPk, 0, sizeof(Index));
  98662. sPk.nColumn = 1;
  98663. sPk.aiColumn = &aiColumnPk;
  98664. sPk.aiRowEst = aiRowEstPk;
  98665. sPk.onError = OE_Replace;
  98666. sPk.pTable = pSrc->pTab;
  98667. aiRowEstPk[0] = pSrc->pTab->nRowEst;
  98668. aiRowEstPk[1] = 1;
  98669. pFirst = pSrc->pTab->pIndex;
  98670. if( pSrc->notIndexed==0 ){
  98671. /* The real indices of the table are only considered if the
  98672. ** NOT INDEXED qualifier is omitted from the FROM clause */
  98673. sPk.pNext = pFirst;
  98674. }
  98675. pProbe = &sPk;
  98676. wsFlagMask = ~(
  98677. WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
  98678. );
  98679. eqTermMask = WO_EQ|WO_IN;
  98680. pIdx = 0;
  98681. }
  98682. nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
  98683. if( p->i ){
  98684. nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
  98685. bSortInit = nPriorSat<nOrderBy;
  98686. bDistInit = 0;
  98687. }else{
  98688. nPriorSat = 0;
  98689. bSortInit = nOrderBy>0;
  98690. bDistInit = p->pDistinct!=0;
  98691. }
  98692. /* Loop over all indices looking for the best one to use
  98693. */
  98694. for(; pProbe; pIdx=pProbe=pProbe->pNext){
  98695. const tRowcnt * const aiRowEst = pProbe->aiRowEst;
  98696. WhereCost pc; /* Cost of using pProbe */
  98697. double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
  98698. /* The following variables are populated based on the properties of
  98699. ** index being evaluated. They are then used to determine the expected
  98700. ** cost and number of rows returned.
  98701. **
  98702. ** pc.plan.nEq:
  98703. ** Number of equality terms that can be implemented using the index.
  98704. ** In other words, the number of initial fields in the index that
  98705. ** are used in == or IN or NOT NULL constraints of the WHERE clause.
  98706. **
  98707. ** nInMul:
  98708. ** The "in-multiplier". This is an estimate of how many seek operations
  98709. ** SQLite must perform on the index in question. For example, if the
  98710. ** WHERE clause is:
  98711. **
  98712. ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
  98713. **
  98714. ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
  98715. ** set to 9. Given the same schema and either of the following WHERE
  98716. ** clauses:
  98717. **
  98718. ** WHERE a = 1
  98719. ** WHERE a >= 2
  98720. **
  98721. ** nInMul is set to 1.
  98722. **
  98723. ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
  98724. ** the sub-select is assumed to return 25 rows for the purposes of
  98725. ** determining nInMul.
  98726. **
  98727. ** bInEst:
  98728. ** Set to true if there was at least one "x IN (SELECT ...)" term used
  98729. ** in determining the value of nInMul. Note that the RHS of the
  98730. ** IN operator must be a SELECT, not a value list, for this variable
  98731. ** to be true.
  98732. **
  98733. ** rangeDiv:
  98734. ** An estimate of a divisor by which to reduce the search space due
  98735. ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
  98736. ** data, a single inequality reduces the search space to 1/4rd its
  98737. ** original size (rangeDiv==4). Two inequalities reduce the search
  98738. ** space to 1/16th of its original size (rangeDiv==16).
  98739. **
  98740. ** bSort:
  98741. ** Boolean. True if there is an ORDER BY clause that will require an
  98742. ** external sort (i.e. scanning the index being evaluated will not
  98743. ** correctly order records).
  98744. **
  98745. ** bDist:
  98746. ** Boolean. True if there is a DISTINCT clause that will require an
  98747. ** external btree.
  98748. **
  98749. ** bLookup:
  98750. ** Boolean. True if a table lookup is required for each index entry
  98751. ** visited. In other words, true if this is not a covering index.
  98752. ** This is always false for the rowid primary key index of a table.
  98753. ** For other indexes, it is true unless all the columns of the table
  98754. ** used by the SELECT statement are present in the index (such an
  98755. ** index is sometimes described as a covering index).
  98756. ** For example, given the index on (a, b), the second of the following
  98757. ** two queries requires table b-tree lookups in order to find the value
  98758. ** of column c, but the first does not because columns a and b are
  98759. ** both available in the index.
  98760. **
  98761. ** SELECT a, b FROM tbl WHERE a = 1;
  98762. ** SELECT a, b, c FROM tbl WHERE a = 1;
  98763. */
  98764. int bInEst = 0; /* True if "x IN (SELECT...)" seen */
  98765. int nInMul = 1; /* Number of distinct equalities to lookup */
  98766. double rangeDiv = (double)1; /* Estimated reduction in search space */
  98767. int nBound = 0; /* Number of range constraints seen */
  98768. char bSort = bSortInit; /* True if external sort required */
  98769. char bDist = bDistInit; /* True if index cannot help with DISTINCT */
  98770. char bLookup = 0; /* True if not a covering index */
  98771. WhereTerm *pTerm; /* A single term of the WHERE clause */
  98772. #ifdef SQLITE_ENABLE_STAT3
  98773. WhereTerm *pFirstTerm = 0; /* First term matching the index */
  98774. #endif
  98775. WHERETRACE((
  98776. " %s(%s):\n",
  98777. pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
  98778. ));
  98779. memset(&pc, 0, sizeof(pc));
  98780. pc.plan.nOBSat = nPriorSat;
  98781. /* Determine the values of pc.plan.nEq and nInMul */
  98782. for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
  98783. int j = pProbe->aiColumn[pc.plan.nEq];
  98784. pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
  98785. if( pTerm==0 ) break;
  98786. pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
  98787. testcase( pTerm->pWC!=pWC );
  98788. if( pTerm->eOperator & WO_IN ){
  98789. Expr *pExpr = pTerm->pExpr;
  98790. pc.plan.wsFlags |= WHERE_COLUMN_IN;
  98791. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  98792. /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
  98793. nInMul *= 25;
  98794. bInEst = 1;
  98795. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  98796. /* "x IN (value, value, ...)" */
  98797. nInMul *= pExpr->x.pList->nExpr;
  98798. }
  98799. }else if( pTerm->eOperator & WO_ISNULL ){
  98800. pc.plan.wsFlags |= WHERE_COLUMN_NULL;
  98801. }
  98802. #ifdef SQLITE_ENABLE_STAT3
  98803. if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
  98804. #endif
  98805. pc.used |= pTerm->prereqRight;
  98806. }
  98807. /* If the index being considered is UNIQUE, and there is an equality
  98808. ** constraint for all columns in the index, then this search will find
  98809. ** at most a single row. In this case set the WHERE_UNIQUE flag to
  98810. ** indicate this to the caller.
  98811. **
  98812. ** Otherwise, if the search may find more than one row, test to see if
  98813. ** there is a range constraint on indexed column (pc.plan.nEq+1) that can be
  98814. ** optimized using the index.
  98815. */
  98816. if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
  98817. testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
  98818. testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
  98819. if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
  98820. pc.plan.wsFlags |= WHERE_UNIQUE;
  98821. if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  98822. pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
  98823. }
  98824. }
  98825. }else if( pProbe->bUnordered==0 ){
  98826. int j;
  98827. j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
  98828. if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
  98829. WhereTerm *pTop, *pBtm;
  98830. pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
  98831. pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
  98832. whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
  98833. if( pTop ){
  98834. nBound = 1;
  98835. pc.plan.wsFlags |= WHERE_TOP_LIMIT;
  98836. pc.used |= pTop->prereqRight;
  98837. testcase( pTop->pWC!=pWC );
  98838. }
  98839. if( pBtm ){
  98840. nBound++;
  98841. pc.plan.wsFlags |= WHERE_BTM_LIMIT;
  98842. pc.used |= pBtm->prereqRight;
  98843. testcase( pBtm->pWC!=pWC );
  98844. }
  98845. pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
  98846. }
  98847. }
  98848. /* If there is an ORDER BY clause and the index being considered will
  98849. ** naturally scan rows in the required order, set the appropriate flags
  98850. ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
  98851. ** the index will scan rows in a different order, set the bSort
  98852. ** variable. */
  98853. if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
  98854. int bRev = 2;
  98855. WHERETRACE((" --> before isSortingIndex: nPriorSat=%d\n",nPriorSat));
  98856. pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev);
  98857. WHERETRACE((" --> after isSortingIndex: bRev=%d nOBSat=%d\n",
  98858. bRev, pc.plan.nOBSat));
  98859. if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
  98860. pc.plan.wsFlags |= WHERE_ORDERED;
  98861. }
  98862. if( nOrderBy==pc.plan.nOBSat ){
  98863. bSort = 0;
  98864. pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
  98865. }
  98866. if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
  98867. }
  98868. /* If there is a DISTINCT qualifier and this index will scan rows in
  98869. ** order of the DISTINCT expressions, clear bDist and set the appropriate
  98870. ** flags in pc.plan.wsFlags. */
  98871. if( bDist
  98872. && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
  98873. && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
  98874. ){
  98875. bDist = 0;
  98876. pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
  98877. }
  98878. /* If currently calculating the cost of using an index (not the IPK
  98879. ** index), determine if all required column data may be obtained without
  98880. ** using the main table (i.e. if the index is a covering
  98881. ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
  98882. ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true. */
  98883. if( pIdx ){
  98884. Bitmask m = pSrc->colUsed;
  98885. int j;
  98886. for(j=0; j<pIdx->nColumn; j++){
  98887. int x = pIdx->aiColumn[j];
  98888. if( x<BMS-1 ){
  98889. m &= ~(((Bitmask)1)<<x);
  98890. }
  98891. }
  98892. if( m==0 ){
  98893. pc.plan.wsFlags |= WHERE_IDX_ONLY;
  98894. }else{
  98895. bLookup = 1;
  98896. }
  98897. }
  98898. /*
  98899. ** Estimate the number of rows of output. For an "x IN (SELECT...)"
  98900. ** constraint, do not let the estimate exceed half the rows in the table.
  98901. */
  98902. pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
  98903. if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
  98904. pc.plan.nRow = aiRowEst[0]/2;
  98905. nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
  98906. }
  98907. #ifdef SQLITE_ENABLE_STAT3
  98908. /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
  98909. ** and we do not think that values of x are unique and if histogram
  98910. ** data is available for column x, then it might be possible
  98911. ** to get a better estimate on the number of rows based on
  98912. ** VALUE and how common that value is according to the histogram.
  98913. */
  98914. if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
  98915. && pFirstTerm!=0 && aiRowEst[1]>1 ){
  98916. assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
  98917. if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
  98918. testcase( pFirstTerm->eOperator==WO_EQ );
  98919. testcase( pFirstTerm->eOperator==WO_ISNULL );
  98920. whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
  98921. &pc.plan.nRow);
  98922. }else if( bInEst==0 ){
  98923. assert( pFirstTerm->eOperator==WO_IN );
  98924. whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
  98925. &pc.plan.nRow);
  98926. }
  98927. }
  98928. #endif /* SQLITE_ENABLE_STAT3 */
  98929. /* Adjust the number of output rows and downward to reflect rows
  98930. ** that are excluded by range constraints.
  98931. */
  98932. pc.plan.nRow = pc.plan.nRow/rangeDiv;
  98933. if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
  98934. /* Experiments run on real SQLite databases show that the time needed
  98935. ** to do a binary search to locate a row in a table or index is roughly
  98936. ** log10(N) times the time to move from one row to the next row within
  98937. ** a table or index. The actual times can vary, with the size of
  98938. ** records being an important factor. Both moves and searches are
  98939. ** slower with larger records, presumably because fewer records fit
  98940. ** on one page and hence more pages have to be fetched.
  98941. **
  98942. ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
  98943. ** not give us data on the relative sizes of table and index records.
  98944. ** So this computation assumes table records are about twice as big
  98945. ** as index records
  98946. */
  98947. if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED))==WHERE_IDX_ONLY
  98948. && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  98949. && sqlite3GlobalConfig.bUseCis
  98950. && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
  98951. ){
  98952. /* This index is not useful for indexing, but it is a covering index.
  98953. ** A full-scan of the index might be a little faster than a full-scan
  98954. ** of the table, so give this case a cost slightly less than a table
  98955. ** scan. */
  98956. pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
  98957. pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
  98958. }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  98959. /* The cost of a full table scan is a number of move operations equal
  98960. ** to the number of rows in the table.
  98961. **
  98962. ** We add an additional 4x penalty to full table scans. This causes
  98963. ** the cost function to err on the side of choosing an index over
  98964. ** choosing a full scan. This 4x full-scan penalty is an arguable
  98965. ** decision and one which we expect to revisit in the future. But
  98966. ** it seems to be working well enough at the moment.
  98967. */
  98968. pc.rCost = aiRowEst[0]*4;
  98969. pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
  98970. if( pIdx ){
  98971. pc.plan.wsFlags &= ~WHERE_ORDERED;
  98972. pc.plan.nOBSat = nPriorSat;
  98973. }
  98974. }else{
  98975. log10N = estLog(aiRowEst[0]);
  98976. pc.rCost = pc.plan.nRow;
  98977. if( pIdx ){
  98978. if( bLookup ){
  98979. /* For an index lookup followed by a table lookup:
  98980. ** nInMul index searches to find the start of each index range
  98981. ** + nRow steps through the index
  98982. ** + nRow table searches to lookup the table entry using the rowid
  98983. */
  98984. pc.rCost += (nInMul + pc.plan.nRow)*log10N;
  98985. }else{
  98986. /* For a covering index:
  98987. ** nInMul index searches to find the initial entry
  98988. ** + nRow steps through the index
  98989. */
  98990. pc.rCost += nInMul*log10N;
  98991. }
  98992. }else{
  98993. /* For a rowid primary key lookup:
  98994. ** nInMult table searches to find the initial entry for each range
  98995. ** + nRow steps through the table
  98996. */
  98997. pc.rCost += nInMul*log10N;
  98998. }
  98999. }
  99000. /* Add in the estimated cost of sorting the result. Actual experimental
  99001. ** measurements of sorting performance in SQLite show that sorting time
  99002. ** adds C*N*log10(N) to the cost, where N is the number of rows to be
  99003. ** sorted and C is a factor between 1.95 and 4.3. We will split the
  99004. ** difference and select C of 3.0.
  99005. */
  99006. if( bSort ){
  99007. double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
  99008. m *= (double)(pc.plan.nOBSat ? 2 : 3);
  99009. pc.rCost += pc.plan.nRow*m;
  99010. }
  99011. if( bDist ){
  99012. pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
  99013. }
  99014. /**** Cost of using this index has now been computed ****/
  99015. /* If there are additional constraints on this table that cannot
  99016. ** be used with the current index, but which might lower the number
  99017. ** of output rows, adjust the nRow value accordingly. This only
  99018. ** matters if the current index is the least costly, so do not bother
  99019. ** with this step if we already know this index will not be chosen.
  99020. ** Also, never reduce the output row count below 2 using this step.
  99021. **
  99022. ** It is critical that the notValid mask be used here instead of
  99023. ** the notReady mask. When computing an "optimal" index, the notReady
  99024. ** mask will only have one bit set - the bit for the current table.
  99025. ** The notValid mask, on the other hand, always has all bits set for
  99026. ** tables that are not in outer loops. If notReady is used here instead
  99027. ** of notValid, then a optimal index that depends on inner joins loops
  99028. ** might be selected even when there exists an optimal index that has
  99029. ** no such dependency.
  99030. */
  99031. if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
  99032. int k; /* Loop counter */
  99033. int nSkipEq = pc.plan.nEq; /* Number of == constraints to skip */
  99034. int nSkipRange = nBound; /* Number of < constraints to skip */
  99035. Bitmask thisTab; /* Bitmap for pSrc */
  99036. thisTab = getMask(pWC->pMaskSet, iCur);
  99037. for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
  99038. if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
  99039. if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
  99040. if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
  99041. if( nSkipEq ){
  99042. /* Ignore the first pc.plan.nEq equality matches since the index
  99043. ** has already accounted for these */
  99044. nSkipEq--;
  99045. }else{
  99046. /* Assume each additional equality match reduces the result
  99047. ** set size by a factor of 10 */
  99048. pc.plan.nRow /= 10;
  99049. }
  99050. }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
  99051. if( nSkipRange ){
  99052. /* Ignore the first nSkipRange range constraints since the index
  99053. ** has already accounted for these */
  99054. nSkipRange--;
  99055. }else{
  99056. /* Assume each additional range constraint reduces the result
  99057. ** set size by a factor of 3. Indexed range constraints reduce
  99058. ** the search space by a larger factor: 4. We make indexed range
  99059. ** more selective intentionally because of the subjective
  99060. ** observation that indexed range constraints really are more
  99061. ** selective in practice, on average. */
  99062. pc.plan.nRow /= 3;
  99063. }
  99064. }else if( pTerm->eOperator!=WO_NOOP ){
  99065. /* Any other expression lowers the output row count by half */
  99066. pc.plan.nRow /= 2;
  99067. }
  99068. }
  99069. if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
  99070. }
  99071. WHERETRACE((
  99072. " nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
  99073. " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
  99074. " used=0x%llx nOBSat=%d\n",
  99075. pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
  99076. p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
  99077. pc.plan.nOBSat
  99078. ));
  99079. /* If this index is the best we have seen so far, then record this
  99080. ** index and its cost in the p->cost structure.
  99081. */
  99082. if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
  99083. p->cost = pc;
  99084. p->cost.plan.wsFlags &= wsFlagMask;
  99085. p->cost.plan.u.pIdx = pIdx;
  99086. }
  99087. /* If there was an INDEXED BY clause, then only that one index is
  99088. ** considered. */
  99089. if( pSrc->pIndex ) break;
  99090. /* Reset masks for the next index in the loop */
  99091. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  99092. eqTermMask = idxEqTermMask;
  99093. }
  99094. /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
  99095. ** is set, then reverse the order that the index will be scanned
  99096. ** in. This is used for application testing, to help find cases
  99097. ** where application behaviour depends on the (undefined) order that
  99098. ** SQLite outputs rows in in the absence of an ORDER BY clause. */
  99099. if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
  99100. p->cost.plan.wsFlags |= WHERE_REVERSE;
  99101. }
  99102. assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
  99103. assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
  99104. assert( pSrc->pIndex==0
  99105. || p->cost.plan.u.pIdx==0
  99106. || p->cost.plan.u.pIdx==pSrc->pIndex
  99107. );
  99108. WHERETRACE((" best index is: %s\n",
  99109. p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk"));
  99110. bestOrClauseIndex(p);
  99111. bestAutomaticIndex(p);
  99112. p->cost.plan.wsFlags |= eqTermMask;
  99113. }
  99114. /*
  99115. ** Find the query plan for accessing table pSrc->pTab. Write the
  99116. ** best query plan and its cost into the WhereCost object supplied
  99117. ** as the last parameter. This function may calculate the cost of
  99118. ** both real and virtual table scans.
  99119. **
  99120. ** This function does not take ORDER BY or DISTINCT into account. Nor
  99121. ** does it remember the virtual table query plan. All it does is compute
  99122. ** the cost while determining if an OR optimization is applicable. The
  99123. ** details will be reconsidered later if the optimization is found to be
  99124. ** applicable.
  99125. */
  99126. static void bestIndex(WhereBestIdx *p){
  99127. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99128. if( IsVirtual(p->pSrc->pTab) ){
  99129. sqlite3_index_info *pIdxInfo = 0;
  99130. p->ppIdxInfo = &pIdxInfo;
  99131. bestVirtualIndex(p);
  99132. if( pIdxInfo->needToFreeIdxStr ){
  99133. sqlite3_free(pIdxInfo->idxStr);
  99134. }
  99135. sqlite3DbFree(p->pParse->db, pIdxInfo);
  99136. }else
  99137. #endif
  99138. {
  99139. bestBtreeIndex(p);
  99140. }
  99141. }
  99142. /*
  99143. ** Disable a term in the WHERE clause. Except, do not disable the term
  99144. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  99145. ** or USING clause of that join.
  99146. **
  99147. ** Consider the term t2.z='ok' in the following queries:
  99148. **
  99149. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  99150. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  99151. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  99152. **
  99153. ** The t2.z='ok' is disabled in the in (2) because it originates
  99154. ** in the ON clause. The term is disabled in (3) because it is not part
  99155. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  99156. **
  99157. ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
  99158. ** completely satisfied by indices.
  99159. **
  99160. ** Disabling a term causes that term to not be tested in the inner loop
  99161. ** of the join. Disabling is an optimization. When terms are satisfied
  99162. ** by indices, we disable them to prevent redundant tests in the inner
  99163. ** loop. We would get the correct results if nothing were ever disabled,
  99164. ** but joins might run a little slower. The trick is to disable as much
  99165. ** as we can without disabling too much. If we disabled in (1), we'd get
  99166. ** the wrong answer. See ticket #813.
  99167. */
  99168. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  99169. if( pTerm
  99170. && (pTerm->wtFlags & TERM_CODED)==0
  99171. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  99172. ){
  99173. pTerm->wtFlags |= TERM_CODED;
  99174. if( pTerm->iParent>=0 ){
  99175. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  99176. if( (--pOther->nChild)==0 ){
  99177. disableTerm(pLevel, pOther);
  99178. }
  99179. }
  99180. }
  99181. }
  99182. /*
  99183. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  99184. ** to the n registers starting at base.
  99185. **
  99186. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  99187. ** beginning and end of zAff are ignored. If all entries in zAff are
  99188. ** SQLITE_AFF_NONE, then no code gets generated.
  99189. **
  99190. ** This routine makes its own copy of zAff so that the caller is free
  99191. ** to modify zAff after this routine returns.
  99192. */
  99193. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  99194. Vdbe *v = pParse->pVdbe;
  99195. if( zAff==0 ){
  99196. assert( pParse->db->mallocFailed );
  99197. return;
  99198. }
  99199. assert( v!=0 );
  99200. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  99201. ** and end of the affinity string.
  99202. */
  99203. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  99204. n--;
  99205. base++;
  99206. zAff++;
  99207. }
  99208. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  99209. n--;
  99210. }
  99211. /* Code the OP_Affinity opcode if there is anything left to do. */
  99212. if( n>0 ){
  99213. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  99214. sqlite3VdbeChangeP4(v, -1, zAff, n);
  99215. sqlite3ExprCacheAffinityChange(pParse, base, n);
  99216. }
  99217. }
  99218. /*
  99219. ** Generate code for a single equality term of the WHERE clause. An equality
  99220. ** term can be either X=expr or X IN (...). pTerm is the term to be
  99221. ** coded.
  99222. **
  99223. ** The current value for the constraint is left in register iReg.
  99224. **
  99225. ** For a constraint of the form X=expr, the expression is evaluated and its
  99226. ** result is left on the stack. For constraints of the form X IN (...)
  99227. ** this routine sets up a loop that will iterate over all values of X.
  99228. */
  99229. static int codeEqualityTerm(
  99230. Parse *pParse, /* The parsing context */
  99231. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  99232. WhereLevel *pLevel, /* When level of the FROM clause we are working on */
  99233. int iTarget /* Attempt to leave results in this register */
  99234. ){
  99235. Expr *pX = pTerm->pExpr;
  99236. Vdbe *v = pParse->pVdbe;
  99237. int iReg; /* Register holding results */
  99238. assert( iTarget>0 );
  99239. if( pX->op==TK_EQ ){
  99240. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  99241. }else if( pX->op==TK_ISNULL ){
  99242. iReg = iTarget;
  99243. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  99244. #ifndef SQLITE_OMIT_SUBQUERY
  99245. }else{
  99246. int eType;
  99247. int iTab;
  99248. struct InLoop *pIn;
  99249. assert( pX->op==TK_IN );
  99250. iReg = iTarget;
  99251. eType = sqlite3FindInIndex(pParse, pX, 0);
  99252. iTab = pX->iTable;
  99253. sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  99254. assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
  99255. if( pLevel->u.in.nIn==0 ){
  99256. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  99257. }
  99258. pLevel->u.in.nIn++;
  99259. pLevel->u.in.aInLoop =
  99260. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  99261. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  99262. pIn = pLevel->u.in.aInLoop;
  99263. if( pIn ){
  99264. pIn += pLevel->u.in.nIn - 1;
  99265. pIn->iCur = iTab;
  99266. if( eType==IN_INDEX_ROWID ){
  99267. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  99268. }else{
  99269. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  99270. }
  99271. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  99272. }else{
  99273. pLevel->u.in.nIn = 0;
  99274. }
  99275. #endif
  99276. }
  99277. disableTerm(pLevel, pTerm);
  99278. return iReg;
  99279. }
  99280. /*
  99281. ** Generate code that will evaluate all == and IN constraints for an
  99282. ** index.
  99283. **
  99284. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  99285. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  99286. ** The index has as many as three equality constraints, but in this
  99287. ** example, the third "c" value is an inequality. So only two
  99288. ** constraints are coded. This routine will generate code to evaluate
  99289. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  99290. ** in consecutive registers and the index of the first register is returned.
  99291. **
  99292. ** In the example above nEq==2. But this subroutine works for any value
  99293. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  99294. ** The only thing it does is allocate the pLevel->iMem memory cell and
  99295. ** compute the affinity string.
  99296. **
  99297. ** This routine always allocates at least one memory cell and returns
  99298. ** the index of that memory cell. The code that
  99299. ** calls this routine will use that memory cell to store the termination
  99300. ** key value of the loop. If one or more IN operators appear, then
  99301. ** this routine allocates an additional nEq memory cells for internal
  99302. ** use.
  99303. **
  99304. ** Before returning, *pzAff is set to point to a buffer containing a
  99305. ** copy of the column affinity string of the index allocated using
  99306. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  99307. ** with equality constraints that use NONE affinity are set to
  99308. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  99309. **
  99310. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  99311. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  99312. **
  99313. ** In the example above, the index on t1(a) has TEXT affinity. But since
  99314. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  99315. ** no conversion should be attempted before using a t2.b value as part of
  99316. ** a key to search the index. Hence the first byte in the returned affinity
  99317. ** string in this example would be set to SQLITE_AFF_NONE.
  99318. */
  99319. static int codeAllEqualityTerms(
  99320. Parse *pParse, /* Parsing context */
  99321. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  99322. WhereClause *pWC, /* The WHERE clause */
  99323. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  99324. int nExtraReg, /* Number of extra registers to allocate */
  99325. char **pzAff /* OUT: Set to point to affinity string */
  99326. ){
  99327. int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
  99328. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  99329. Index *pIdx; /* The index being used for this loop */
  99330. int iCur = pLevel->iTabCur; /* The cursor of the table */
  99331. WhereTerm *pTerm; /* A single constraint term */
  99332. int j; /* Loop counter */
  99333. int regBase; /* Base register */
  99334. int nReg; /* Number of registers to allocate */
  99335. char *zAff; /* Affinity string to return */
  99336. /* This module is only called on query plans that use an index. */
  99337. assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  99338. pIdx = pLevel->plan.u.pIdx;
  99339. /* Figure out how many memory cells we will need then allocate them.
  99340. */
  99341. regBase = pParse->nMem + 1;
  99342. nReg = pLevel->plan.nEq + nExtraReg;
  99343. pParse->nMem += nReg;
  99344. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  99345. if( !zAff ){
  99346. pParse->db->mallocFailed = 1;
  99347. }
  99348. /* Evaluate the equality constraints
  99349. */
  99350. assert( pIdx->nColumn>=nEq );
  99351. for(j=0; j<nEq; j++){
  99352. int r1;
  99353. int k = pIdx->aiColumn[j];
  99354. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
  99355. if( pTerm==0 ) break;
  99356. /* The following true for indices with redundant columns.
  99357. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  99358. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  99359. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99360. r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
  99361. if( r1!=regBase+j ){
  99362. if( nReg==1 ){
  99363. sqlite3ReleaseTempReg(pParse, regBase);
  99364. regBase = r1;
  99365. }else{
  99366. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  99367. }
  99368. }
  99369. testcase( pTerm->eOperator & WO_ISNULL );
  99370. testcase( pTerm->eOperator & WO_IN );
  99371. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  99372. Expr *pRight = pTerm->pExpr->pRight;
  99373. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  99374. if( zAff ){
  99375. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  99376. zAff[j] = SQLITE_AFF_NONE;
  99377. }
  99378. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  99379. zAff[j] = SQLITE_AFF_NONE;
  99380. }
  99381. }
  99382. }
  99383. }
  99384. *pzAff = zAff;
  99385. return regBase;
  99386. }
  99387. #ifndef SQLITE_OMIT_EXPLAIN
  99388. /*
  99389. ** This routine is a helper for explainIndexRange() below
  99390. **
  99391. ** pStr holds the text of an expression that we are building up one term
  99392. ** at a time. This routine adds a new term to the end of the expression.
  99393. ** Terms are separated by AND so add the "AND" text for second and subsequent
  99394. ** terms only.
  99395. */
  99396. static void explainAppendTerm(
  99397. StrAccum *pStr, /* The text expression being built */
  99398. int iTerm, /* Index of this term. First is zero */
  99399. const char *zColumn, /* Name of the column */
  99400. const char *zOp /* Name of the operator */
  99401. ){
  99402. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  99403. sqlite3StrAccumAppend(pStr, zColumn, -1);
  99404. sqlite3StrAccumAppend(pStr, zOp, 1);
  99405. sqlite3StrAccumAppend(pStr, "?", 1);
  99406. }
  99407. /*
  99408. ** Argument pLevel describes a strategy for scanning table pTab. This
  99409. ** function returns a pointer to a string buffer containing a description
  99410. ** of the subset of table rows scanned by the strategy in the form of an
  99411. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  99412. **
  99413. ** For example, if the query:
  99414. **
  99415. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  99416. **
  99417. ** is run and there is an index on (a, b), then this function returns a
  99418. ** string similar to:
  99419. **
  99420. ** "a=? AND b>?"
  99421. **
  99422. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  99423. ** It is the responsibility of the caller to free the buffer when it is
  99424. ** no longer required.
  99425. */
  99426. static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
  99427. WherePlan *pPlan = &pLevel->plan;
  99428. Index *pIndex = pPlan->u.pIdx;
  99429. int nEq = pPlan->nEq;
  99430. int i, j;
  99431. Column *aCol = pTab->aCol;
  99432. int *aiColumn = pIndex->aiColumn;
  99433. StrAccum txt;
  99434. if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  99435. return 0;
  99436. }
  99437. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  99438. txt.db = db;
  99439. sqlite3StrAccumAppend(&txt, " (", 2);
  99440. for(i=0; i<nEq; i++){
  99441. explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
  99442. }
  99443. j = i;
  99444. if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
  99445. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  99446. explainAppendTerm(&txt, i++, z, ">");
  99447. }
  99448. if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
  99449. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  99450. explainAppendTerm(&txt, i, z, "<");
  99451. }
  99452. sqlite3StrAccumAppend(&txt, ")", 1);
  99453. return sqlite3StrAccumFinish(&txt);
  99454. }
  99455. /*
  99456. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  99457. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  99458. ** record is added to the output to describe the table scan strategy in
  99459. ** pLevel.
  99460. */
  99461. static void explainOneScan(
  99462. Parse *pParse, /* Parse context */
  99463. SrcList *pTabList, /* Table list this loop refers to */
  99464. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  99465. int iLevel, /* Value for "level" column of output */
  99466. int iFrom, /* Value for "from" column of output */
  99467. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  99468. ){
  99469. if( pParse->explain==2 ){
  99470. u32 flags = pLevel->plan.wsFlags;
  99471. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  99472. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  99473. sqlite3 *db = pParse->db; /* Database handle */
  99474. char *zMsg; /* Text to add to EQP output */
  99475. sqlite3_int64 nRow; /* Expected number of rows visited by scan */
  99476. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  99477. int isSearch; /* True for a SEARCH. False for SCAN. */
  99478. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  99479. isSearch = (pLevel->plan.nEq>0)
  99480. || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  99481. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  99482. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  99483. if( pItem->pSelect ){
  99484. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  99485. }else{
  99486. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  99487. }
  99488. if( pItem->zAlias ){
  99489. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  99490. }
  99491. if( (flags & WHERE_INDEXED)!=0 ){
  99492. char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
  99493. zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
  99494. ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
  99495. ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
  99496. ((flags & WHERE_TEMP_INDEX)?"":" "),
  99497. ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
  99498. zWhere
  99499. );
  99500. sqlite3DbFree(db, zWhere);
  99501. }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  99502. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  99503. if( flags&WHERE_ROWID_EQ ){
  99504. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  99505. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  99506. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  99507. }else if( flags&WHERE_BTM_LIMIT ){
  99508. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  99509. }else if( flags&WHERE_TOP_LIMIT ){
  99510. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  99511. }
  99512. }
  99513. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99514. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  99515. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  99516. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  99517. pVtabIdx->idxNum, pVtabIdx->idxStr);
  99518. }
  99519. #endif
  99520. if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
  99521. testcase( wctrlFlags & WHERE_ORDERBY_MIN );
  99522. nRow = 1;
  99523. }else{
  99524. nRow = (sqlite3_int64)pLevel->plan.nRow;
  99525. }
  99526. zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
  99527. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  99528. }
  99529. }
  99530. #else
  99531. # define explainOneScan(u,v,w,x,y,z)
  99532. #endif /* SQLITE_OMIT_EXPLAIN */
  99533. /*
  99534. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  99535. ** implementation described by pWInfo.
  99536. */
  99537. static Bitmask codeOneLoopStart(
  99538. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  99539. int iLevel, /* Which level of pWInfo->a[] should be coded */
  99540. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  99541. Bitmask notReady /* Which tables are currently available */
  99542. ){
  99543. int j, k; /* Loop counters */
  99544. int iCur; /* The VDBE cursor for the table */
  99545. int addrNxt; /* Where to jump to continue with the next IN case */
  99546. int omitTable; /* True if we use the index only */
  99547. int bRev; /* True if we need to scan in reverse order */
  99548. WhereLevel *pLevel; /* The where level to be coded */
  99549. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  99550. WhereTerm *pTerm; /* A WHERE clause term */
  99551. Parse *pParse; /* Parsing context */
  99552. Vdbe *v; /* The prepared stmt under constructions */
  99553. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  99554. int addrBrk; /* Jump here to break out of the loop */
  99555. int addrCont; /* Jump here to continue with next cycle */
  99556. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  99557. int iReleaseReg = 0; /* Temp register to free before returning */
  99558. pParse = pWInfo->pParse;
  99559. v = pParse->pVdbe;
  99560. pWC = pWInfo->pWC;
  99561. pLevel = &pWInfo->a[iLevel];
  99562. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  99563. iCur = pTabItem->iCursor;
  99564. bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  99565. omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
  99566. && (wctrlFlags & WHERE_FORCE_TABLE)==0;
  99567. /* Create labels for the "break" and "continue" instructions
  99568. ** for the current loop. Jump to addrBrk to break out of a loop.
  99569. ** Jump to cont to go immediately to the next iteration of the
  99570. ** loop.
  99571. **
  99572. ** When there is an IN operator, we also have a "addrNxt" label that
  99573. ** means to continue with the next IN value combination. When
  99574. ** there are no IN operators in the constraints, the "addrNxt" label
  99575. ** is the same as "addrBrk".
  99576. */
  99577. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  99578. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  99579. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  99580. ** initialize a memory cell that records if this table matches any
  99581. ** row of the left table of the join.
  99582. */
  99583. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  99584. pLevel->iLeftJoin = ++pParse->nMem;
  99585. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  99586. VdbeComment((v, "init LEFT JOIN no-match flag"));
  99587. }
  99588. /* Special case of a FROM clause subquery implemented as a co-routine */
  99589. if( pTabItem->viaCoroutine ){
  99590. int regYield = pTabItem->regReturn;
  99591. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  99592. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  99593. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  99594. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  99595. pLevel->op = OP_Goto;
  99596. }else
  99597. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99598. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  99599. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  99600. ** to access the data.
  99601. */
  99602. int iReg; /* P3 Value for OP_VFilter */
  99603. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  99604. int nConstraint = pVtabIdx->nConstraint;
  99605. struct sqlite3_index_constraint_usage *aUsage =
  99606. pVtabIdx->aConstraintUsage;
  99607. const struct sqlite3_index_constraint *aConstraint =
  99608. pVtabIdx->aConstraint;
  99609. sqlite3ExprCachePush(pParse);
  99610. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  99611. for(j=1; j<=nConstraint; j++){
  99612. for(k=0; k<nConstraint; k++){
  99613. if( aUsage[k].argvIndex==j ){
  99614. int iTerm = aConstraint[k].iTermOffset;
  99615. sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
  99616. break;
  99617. }
  99618. }
  99619. if( k==nConstraint ) break;
  99620. }
  99621. sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
  99622. sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
  99623. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
  99624. pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
  99625. pVtabIdx->needToFreeIdxStr = 0;
  99626. for(j=0; j<nConstraint; j++){
  99627. if( aUsage[j].omit ){
  99628. int iTerm = aConstraint[j].iTermOffset;
  99629. disableTerm(pLevel, &pWC->a[iTerm]);
  99630. }
  99631. }
  99632. pLevel->op = OP_VNext;
  99633. pLevel->p1 = iCur;
  99634. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  99635. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  99636. sqlite3ExprCachePop(pParse, 1);
  99637. }else
  99638. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  99639. if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
  99640. /* Case 1: We can directly reference a single row using an
  99641. ** equality comparison against the ROWID field. Or
  99642. ** we reference multiple rows using a "rowid IN (...)"
  99643. ** construct.
  99644. */
  99645. iReleaseReg = sqlite3GetTempReg(pParse);
  99646. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  99647. assert( pTerm!=0 );
  99648. assert( pTerm->pExpr!=0 );
  99649. assert( pTerm->leftCursor==iCur );
  99650. assert( omitTable==0 );
  99651. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99652. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
  99653. addrNxt = pLevel->addrNxt;
  99654. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  99655. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  99656. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  99657. VdbeComment((v, "pk"));
  99658. pLevel->op = OP_Noop;
  99659. }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
  99660. /* Case 2: We have an inequality comparison against the ROWID field.
  99661. */
  99662. int testOp = OP_Noop;
  99663. int start;
  99664. int memEndValue = 0;
  99665. WhereTerm *pStart, *pEnd;
  99666. assert( omitTable==0 );
  99667. pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
  99668. pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
  99669. if( bRev ){
  99670. pTerm = pStart;
  99671. pStart = pEnd;
  99672. pEnd = pTerm;
  99673. }
  99674. if( pStart ){
  99675. Expr *pX; /* The expression that defines the start bound */
  99676. int r1, rTemp; /* Registers for holding the start boundary */
  99677. /* The following constant maps TK_xx codes into corresponding
  99678. ** seek opcodes. It depends on a particular ordering of TK_xx
  99679. */
  99680. const u8 aMoveOp[] = {
  99681. /* TK_GT */ OP_SeekGt,
  99682. /* TK_LE */ OP_SeekLe,
  99683. /* TK_LT */ OP_SeekLt,
  99684. /* TK_GE */ OP_SeekGe
  99685. };
  99686. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  99687. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  99688. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  99689. testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99690. pX = pStart->pExpr;
  99691. assert( pX!=0 );
  99692. assert( pStart->leftCursor==iCur );
  99693. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  99694. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  99695. VdbeComment((v, "pk"));
  99696. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  99697. sqlite3ReleaseTempReg(pParse, rTemp);
  99698. disableTerm(pLevel, pStart);
  99699. }else{
  99700. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  99701. }
  99702. if( pEnd ){
  99703. Expr *pX;
  99704. pX = pEnd->pExpr;
  99705. assert( pX!=0 );
  99706. assert( pEnd->leftCursor==iCur );
  99707. testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99708. memEndValue = ++pParse->nMem;
  99709. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  99710. if( pX->op==TK_LT || pX->op==TK_GT ){
  99711. testOp = bRev ? OP_Le : OP_Ge;
  99712. }else{
  99713. testOp = bRev ? OP_Lt : OP_Gt;
  99714. }
  99715. disableTerm(pLevel, pEnd);
  99716. }
  99717. start = sqlite3VdbeCurrentAddr(v);
  99718. pLevel->op = bRev ? OP_Prev : OP_Next;
  99719. pLevel->p1 = iCur;
  99720. pLevel->p2 = start;
  99721. if( pStart==0 && pEnd==0 ){
  99722. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  99723. }else{
  99724. assert( pLevel->p5==0 );
  99725. }
  99726. if( testOp!=OP_Noop ){
  99727. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  99728. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  99729. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  99730. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  99731. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  99732. }
  99733. }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
  99734. /* Case 3: A scan using an index.
  99735. **
  99736. ** The WHERE clause may contain zero or more equality
  99737. ** terms ("==" or "IN" operators) that refer to the N
  99738. ** left-most columns of the index. It may also contain
  99739. ** inequality constraints (>, <, >= or <=) on the indexed
  99740. ** column that immediately follows the N equalities. Only
  99741. ** the right-most column can be an inequality - the rest must
  99742. ** use the "==" and "IN" operators. For example, if the
  99743. ** index is on (x,y,z), then the following clauses are all
  99744. ** optimized:
  99745. **
  99746. ** x=5
  99747. ** x=5 AND y=10
  99748. ** x=5 AND y<10
  99749. ** x=5 AND y>5 AND y<10
  99750. ** x=5 AND y=5 AND z<=10
  99751. **
  99752. ** The z<10 term of the following cannot be used, only
  99753. ** the x=5 term:
  99754. **
  99755. ** x=5 AND z<10
  99756. **
  99757. ** N may be zero if there are inequality constraints.
  99758. ** If there are no inequality constraints, then N is at
  99759. ** least one.
  99760. **
  99761. ** This case is also used when there are no WHERE clause
  99762. ** constraints but an index is selected anyway, in order
  99763. ** to force the output order to conform to an ORDER BY.
  99764. */
  99765. static const u8 aStartOp[] = {
  99766. 0,
  99767. 0,
  99768. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  99769. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  99770. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  99771. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  99772. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  99773. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  99774. };
  99775. static const u8 aEndOp[] = {
  99776. OP_Noop, /* 0: (!end_constraints) */
  99777. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  99778. OP_IdxLT /* 2: (end_constraints && bRev) */
  99779. };
  99780. int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
  99781. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  99782. int regBase; /* Base register holding constraint values */
  99783. int r1; /* Temp register */
  99784. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  99785. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  99786. int startEq; /* True if range start uses ==, >= or <= */
  99787. int endEq; /* True if range end uses ==, >= or <= */
  99788. int start_constraints; /* Start of range is constrained */
  99789. int nConstraint; /* Number of constraint terms */
  99790. Index *pIdx; /* The index we will be using */
  99791. int iIdxCur; /* The VDBE cursor for the index */
  99792. int nExtraReg = 0; /* Number of extra registers needed */
  99793. int op; /* Instruction opcode */
  99794. char *zStartAff; /* Affinity for start of range constraint */
  99795. char *zEndAff; /* Affinity for end of range constraint */
  99796. pIdx = pLevel->plan.u.pIdx;
  99797. iIdxCur = pLevel->iIdxCur;
  99798. k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
  99799. /* If this loop satisfies a sort order (pOrderBy) request that
  99800. ** was passed to this function to implement a "SELECT min(x) ..."
  99801. ** query, then the caller will only allow the loop to run for
  99802. ** a single iteration. This means that the first row returned
  99803. ** should not have a NULL value stored in 'x'. If column 'x' is
  99804. ** the first one after the nEq equality constraints in the index,
  99805. ** this requires some special handling.
  99806. */
  99807. if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
  99808. && (pLevel->plan.wsFlags&WHERE_ORDERED)
  99809. && (pIdx->nColumn>nEq)
  99810. ){
  99811. /* assert( pOrderBy->nExpr==1 ); */
  99812. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  99813. isMinQuery = 1;
  99814. nExtraReg = 1;
  99815. }
  99816. /* Find any inequality constraint terms for the start and end
  99817. ** of the range.
  99818. */
  99819. if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
  99820. pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
  99821. nExtraReg = 1;
  99822. }
  99823. if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
  99824. pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
  99825. nExtraReg = 1;
  99826. }
  99827. /* Generate code to evaluate all constraint terms using == or IN
  99828. ** and store the values of those terms in an array of registers
  99829. ** starting at regBase.
  99830. */
  99831. regBase = codeAllEqualityTerms(
  99832. pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
  99833. );
  99834. zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
  99835. addrNxt = pLevel->addrNxt;
  99836. /* If we are doing a reverse order scan on an ascending index, or
  99837. ** a forward order scan on a descending index, interchange the
  99838. ** start and end terms (pRangeStart and pRangeEnd).
  99839. */
  99840. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  99841. || (bRev && pIdx->nColumn==nEq)
  99842. ){
  99843. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  99844. }
  99845. testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
  99846. testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
  99847. testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
  99848. testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
  99849. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  99850. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  99851. start_constraints = pRangeStart || nEq>0;
  99852. /* Seek the index cursor to the start of the range. */
  99853. nConstraint = nEq;
  99854. if( pRangeStart ){
  99855. Expr *pRight = pRangeStart->pExpr->pRight;
  99856. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  99857. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  99858. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  99859. }
  99860. if( zStartAff ){
  99861. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  99862. /* Since the comparison is to be performed with no conversions
  99863. ** applied to the operands, set the affinity to apply to pRight to
  99864. ** SQLITE_AFF_NONE. */
  99865. zStartAff[nEq] = SQLITE_AFF_NONE;
  99866. }
  99867. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  99868. zStartAff[nEq] = SQLITE_AFF_NONE;
  99869. }
  99870. }
  99871. nConstraint++;
  99872. testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99873. }else if( isMinQuery ){
  99874. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  99875. nConstraint++;
  99876. startEq = 0;
  99877. start_constraints = 1;
  99878. }
  99879. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  99880. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  99881. assert( op!=0 );
  99882. testcase( op==OP_Rewind );
  99883. testcase( op==OP_Last );
  99884. testcase( op==OP_SeekGt );
  99885. testcase( op==OP_SeekGe );
  99886. testcase( op==OP_SeekLe );
  99887. testcase( op==OP_SeekLt );
  99888. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  99889. /* Load the value for the inequality constraint at the end of the
  99890. ** range (if any).
  99891. */
  99892. nConstraint = nEq;
  99893. if( pRangeEnd ){
  99894. Expr *pRight = pRangeEnd->pExpr->pRight;
  99895. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  99896. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  99897. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  99898. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  99899. }
  99900. if( zEndAff ){
  99901. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  99902. /* Since the comparison is to be performed with no conversions
  99903. ** applied to the operands, set the affinity to apply to pRight to
  99904. ** SQLITE_AFF_NONE. */
  99905. zEndAff[nEq] = SQLITE_AFF_NONE;
  99906. }
  99907. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  99908. zEndAff[nEq] = SQLITE_AFF_NONE;
  99909. }
  99910. }
  99911. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  99912. nConstraint++;
  99913. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  99914. }
  99915. sqlite3DbFree(pParse->db, zStartAff);
  99916. sqlite3DbFree(pParse->db, zEndAff);
  99917. /* Top of the loop body */
  99918. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  99919. /* Check if the index cursor is past the end of the range. */
  99920. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  99921. testcase( op==OP_Noop );
  99922. testcase( op==OP_IdxGE );
  99923. testcase( op==OP_IdxLT );
  99924. if( op!=OP_Noop ){
  99925. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  99926. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  99927. }
  99928. /* If there are inequality constraints, check that the value
  99929. ** of the table column that the inequality contrains is not NULL.
  99930. ** If it is, jump to the next iteration of the loop.
  99931. */
  99932. r1 = sqlite3GetTempReg(pParse);
  99933. testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
  99934. testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
  99935. if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  99936. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  99937. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  99938. }
  99939. sqlite3ReleaseTempReg(pParse, r1);
  99940. /* Seek the table cursor, if required */
  99941. disableTerm(pLevel, pRangeStart);
  99942. disableTerm(pLevel, pRangeEnd);
  99943. if( !omitTable ){
  99944. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  99945. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  99946. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  99947. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  99948. }
  99949. /* Record the instruction used to terminate the loop. Disable
  99950. ** WHERE clause terms made redundant by the index range scan.
  99951. */
  99952. if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
  99953. pLevel->op = OP_Noop;
  99954. }else if( bRev ){
  99955. pLevel->op = OP_Prev;
  99956. }else{
  99957. pLevel->op = OP_Next;
  99958. }
  99959. pLevel->p1 = iIdxCur;
  99960. if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
  99961. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  99962. }else{
  99963. assert( pLevel->p5==0 );
  99964. }
  99965. }else
  99966. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  99967. if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  99968. /* Case 4: Two or more separately indexed terms connected by OR
  99969. **
  99970. ** Example:
  99971. **
  99972. ** CREATE TABLE t1(a,b,c,d);
  99973. ** CREATE INDEX i1 ON t1(a);
  99974. ** CREATE INDEX i2 ON t1(b);
  99975. ** CREATE INDEX i3 ON t1(c);
  99976. **
  99977. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  99978. **
  99979. ** In the example, there are three indexed terms connected by OR.
  99980. ** The top of the loop looks like this:
  99981. **
  99982. ** Null 1 # Zero the rowset in reg 1
  99983. **
  99984. ** Then, for each indexed term, the following. The arguments to
  99985. ** RowSetTest are such that the rowid of the current row is inserted
  99986. ** into the RowSet. If it is already present, control skips the
  99987. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  99988. **
  99989. ** sqlite3WhereBegin(<term>)
  99990. ** RowSetTest # Insert rowid into rowset
  99991. ** Gosub 2 A
  99992. ** sqlite3WhereEnd()
  99993. **
  99994. ** Following the above, code to terminate the loop. Label A, the target
  99995. ** of the Gosub above, jumps to the instruction right after the Goto.
  99996. **
  99997. ** Null 1 # Zero the rowset in reg 1
  99998. ** Goto B # The loop is finished.
  99999. **
  100000. ** A: <loop body> # Return data, whatever.
  100001. **
  100002. ** Return 2 # Jump back to the Gosub
  100003. **
  100004. ** B: <after the loop>
  100005. **
  100006. */
  100007. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  100008. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  100009. Index *pCov = 0; /* Potential covering index (or NULL) */
  100010. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  100011. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  100012. int regRowset = 0; /* Register for RowSet object */
  100013. int regRowid = 0; /* Register holding rowid */
  100014. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  100015. int iRetInit; /* Address of regReturn init */
  100016. int untestedTerms = 0; /* Some terms not completely tested */
  100017. int ii; /* Loop counter */
  100018. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  100019. pTerm = pLevel->plan.u.pTerm;
  100020. assert( pTerm!=0 );
  100021. assert( pTerm->eOperator==WO_OR );
  100022. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  100023. pOrWc = &pTerm->u.pOrInfo->wc;
  100024. pLevel->op = OP_Return;
  100025. pLevel->p1 = regReturn;
  100026. /* Set up a new SrcList in pOrTab containing the table being scanned
  100027. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  100028. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  100029. */
  100030. if( pWInfo->nLevel>1 ){
  100031. int nNotReady; /* The number of notReady tables */
  100032. struct SrcList_item *origSrc; /* Original list of tables */
  100033. nNotReady = pWInfo->nLevel - iLevel - 1;
  100034. pOrTab = sqlite3StackAllocRaw(pParse->db,
  100035. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  100036. if( pOrTab==0 ) return notReady;
  100037. pOrTab->nAlloc = (i16)(nNotReady + 1);
  100038. pOrTab->nSrc = pOrTab->nAlloc;
  100039. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  100040. origSrc = pWInfo->pTabList->a;
  100041. for(k=1; k<=nNotReady; k++){
  100042. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  100043. }
  100044. }else{
  100045. pOrTab = pWInfo->pTabList;
  100046. }
  100047. /* Initialize the rowset register to contain NULL. An SQL NULL is
  100048. ** equivalent to an empty rowset.
  100049. **
  100050. ** Also initialize regReturn to contain the address of the instruction
  100051. ** immediately following the OP_Return at the bottom of the loop. This
  100052. ** is required in a few obscure LEFT JOIN cases where control jumps
  100053. ** over the top of the loop into the body of it. In this case the
  100054. ** correct response for the end-of-loop code (the OP_Return) is to
  100055. ** fall through to the next instruction, just as an OP_Next does if
  100056. ** called on an uninitialized cursor.
  100057. */
  100058. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  100059. regRowset = ++pParse->nMem;
  100060. regRowid = ++pParse->nMem;
  100061. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  100062. }
  100063. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  100064. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  100065. ** Then for every term xN, evaluate as the subexpression: xN AND z
  100066. ** That way, terms in y that are factored into the disjunction will
  100067. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  100068. **
  100069. ** Actually, each subexpression is converted to "xN AND w" where w is
  100070. ** the "interesting" terms of z - terms that did not originate in the
  100071. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  100072. ** indices.
  100073. */
  100074. if( pWC->nTerm>1 ){
  100075. int iTerm;
  100076. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  100077. Expr *pExpr = pWC->a[iTerm].pExpr;
  100078. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  100079. if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
  100080. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  100081. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  100082. pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
  100083. }
  100084. if( pAndExpr ){
  100085. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  100086. }
  100087. }
  100088. for(ii=0; ii<pOrWc->nTerm; ii++){
  100089. WhereTerm *pOrTerm = &pOrWc->a[ii];
  100090. if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
  100091. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  100092. Expr *pOrExpr = pOrTerm->pExpr;
  100093. if( pAndExpr ){
  100094. pAndExpr->pLeft = pOrExpr;
  100095. pOrExpr = pAndExpr;
  100096. }
  100097. /* Loop through table entries that match term pOrTerm. */
  100098. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  100099. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  100100. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  100101. assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
  100102. if( pSubWInfo ){
  100103. WhereLevel *pLvl;
  100104. explainOneScan(
  100105. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  100106. );
  100107. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  100108. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  100109. int r;
  100110. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  100111. regRowid, 0);
  100112. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  100113. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  100114. }
  100115. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  100116. /* The pSubWInfo->untestedTerms flag means that this OR term
  100117. ** contained one or more AND term from a notReady table. The
  100118. ** terms from the notReady table could not be tested and will
  100119. ** need to be tested later.
  100120. */
  100121. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  100122. /* If all of the OR-connected terms are optimized using the same
  100123. ** index, and the index is opened using the same cursor number
  100124. ** by each call to sqlite3WhereBegin() made by this loop, it may
  100125. ** be possible to use that index as a covering index.
  100126. **
  100127. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  100128. ** uses an index, and this is either the first OR-connected term
  100129. ** processed or the index is the same as that used by all previous
  100130. ** terms, set pCov to the candidate covering index. Otherwise, set
  100131. ** pCov to NULL to indicate that no candidate covering index will
  100132. ** be available.
  100133. */
  100134. pLvl = &pSubWInfo->a[0];
  100135. if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
  100136. && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
  100137. && (ii==0 || pLvl->plan.u.pIdx==pCov)
  100138. ){
  100139. assert( pLvl->iIdxCur==iCovCur );
  100140. pCov = pLvl->plan.u.pIdx;
  100141. }else{
  100142. pCov = 0;
  100143. }
  100144. /* Finish the loop through table entries that match term pOrTerm. */
  100145. sqlite3WhereEnd(pSubWInfo);
  100146. }
  100147. }
  100148. }
  100149. pLevel->u.pCovidx = pCov;
  100150. if( pCov ) pLevel->iIdxCur = iCovCur;
  100151. if( pAndExpr ){
  100152. pAndExpr->pLeft = 0;
  100153. sqlite3ExprDelete(pParse->db, pAndExpr);
  100154. }
  100155. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  100156. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  100157. sqlite3VdbeResolveLabel(v, iLoopBody);
  100158. if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
  100159. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  100160. }else
  100161. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  100162. {
  100163. /* Case 5: There is no usable index. We must do a complete
  100164. ** scan of the entire table.
  100165. */
  100166. static const u8 aStep[] = { OP_Next, OP_Prev };
  100167. static const u8 aStart[] = { OP_Rewind, OP_Last };
  100168. assert( bRev==0 || bRev==1 );
  100169. assert( omitTable==0 );
  100170. pLevel->op = aStep[bRev];
  100171. pLevel->p1 = iCur;
  100172. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  100173. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  100174. }
  100175. notReady &= ~getMask(pWC->pMaskSet, iCur);
  100176. /* Insert code to test every subexpression that can be completely
  100177. ** computed using the current set of tables.
  100178. **
  100179. ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
  100180. ** the use of indices become tests that are evaluated against each row of
  100181. ** the relevant input tables.
  100182. */
  100183. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  100184. Expr *pE;
  100185. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  100186. testcase( pTerm->wtFlags & TERM_CODED );
  100187. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  100188. if( (pTerm->prereqAll & notReady)!=0 ){
  100189. testcase( pWInfo->untestedTerms==0
  100190. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  100191. pWInfo->untestedTerms = 1;
  100192. continue;
  100193. }
  100194. pE = pTerm->pExpr;
  100195. assert( pE!=0 );
  100196. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  100197. continue;
  100198. }
  100199. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  100200. pTerm->wtFlags |= TERM_CODED;
  100201. }
  100202. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  100203. ** at least one row of the right table has matched the left table.
  100204. */
  100205. if( pLevel->iLeftJoin ){
  100206. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  100207. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  100208. VdbeComment((v, "record LEFT JOIN hit"));
  100209. sqlite3ExprCacheClear(pParse);
  100210. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  100211. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  100212. testcase( pTerm->wtFlags & TERM_CODED );
  100213. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  100214. if( (pTerm->prereqAll & notReady)!=0 ){
  100215. assert( pWInfo->untestedTerms );
  100216. continue;
  100217. }
  100218. assert( pTerm->pExpr );
  100219. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  100220. pTerm->wtFlags |= TERM_CODED;
  100221. }
  100222. }
  100223. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  100224. return notReady;
  100225. }
  100226. #if defined(SQLITE_TEST)
  100227. /*
  100228. ** The following variable holds a text description of query plan generated
  100229. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  100230. ** overwrites the previous. This information is used for testing and
  100231. ** analysis only.
  100232. */
  100233. SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  100234. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  100235. #endif /* SQLITE_TEST */
  100236. /*
  100237. ** Free a WhereInfo structure
  100238. */
  100239. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  100240. if( ALWAYS(pWInfo) ){
  100241. int i;
  100242. for(i=0; i<pWInfo->nLevel; i++){
  100243. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  100244. if( pInfo ){
  100245. /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
  100246. if( pInfo->needToFreeIdxStr ){
  100247. sqlite3_free(pInfo->idxStr);
  100248. }
  100249. sqlite3DbFree(db, pInfo);
  100250. }
  100251. if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
  100252. Index *pIdx = pWInfo->a[i].plan.u.pIdx;
  100253. if( pIdx ){
  100254. sqlite3DbFree(db, pIdx->zColAff);
  100255. sqlite3DbFree(db, pIdx);
  100256. }
  100257. }
  100258. }
  100259. whereClauseClear(pWInfo->pWC);
  100260. sqlite3DbFree(db, pWInfo);
  100261. }
  100262. }
  100263. /*
  100264. ** Generate the beginning of the loop used for WHERE clause processing.
  100265. ** The return value is a pointer to an opaque structure that contains
  100266. ** information needed to terminate the loop. Later, the calling routine
  100267. ** should invoke sqlite3WhereEnd() with the return value of this function
  100268. ** in order to complete the WHERE clause processing.
  100269. **
  100270. ** If an error occurs, this routine returns NULL.
  100271. **
  100272. ** The basic idea is to do a nested loop, one loop for each table in
  100273. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  100274. ** same as a SELECT with only a single table in the FROM clause.) For
  100275. ** example, if the SQL is this:
  100276. **
  100277. ** SELECT * FROM t1, t2, t3 WHERE ...;
  100278. **
  100279. ** Then the code generated is conceptually like the following:
  100280. **
  100281. ** foreach row1 in t1 do \ Code generated
  100282. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  100283. ** foreach row3 in t3 do /
  100284. ** ...
  100285. ** end \ Code generated
  100286. ** end |-- by sqlite3WhereEnd()
  100287. ** end /
  100288. **
  100289. ** Note that the loops might not be nested in the order in which they
  100290. ** appear in the FROM clause if a different order is better able to make
  100291. ** use of indices. Note also that when the IN operator appears in
  100292. ** the WHERE clause, it might result in additional nested loops for
  100293. ** scanning through all values on the right-hand side of the IN.
  100294. **
  100295. ** There are Btree cursors associated with each table. t1 uses cursor
  100296. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  100297. ** And so forth. This routine generates code to open those VDBE cursors
  100298. ** and sqlite3WhereEnd() generates the code to close them.
  100299. **
  100300. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  100301. ** in pTabList pointing at their appropriate entries. The [...] code
  100302. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  100303. ** data from the various tables of the loop.
  100304. **
  100305. ** If the WHERE clause is empty, the foreach loops must each scan their
  100306. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  100307. ** the tables have indices and there are terms in the WHERE clause that
  100308. ** refer to those indices, a complete table scan can be avoided and the
  100309. ** code will run much faster. Most of the work of this routine is checking
  100310. ** to see if there are indices that can be used to speed up the loop.
  100311. **
  100312. ** Terms of the WHERE clause are also used to limit which rows actually
  100313. ** make it to the "..." in the middle of the loop. After each "foreach",
  100314. ** terms of the WHERE clause that use only terms in that loop and outer
  100315. ** loops are evaluated and if false a jump is made around all subsequent
  100316. ** inner loops (or around the "..." if the test occurs within the inner-
  100317. ** most loop)
  100318. **
  100319. ** OUTER JOINS
  100320. **
  100321. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  100322. **
  100323. ** foreach row1 in t1 do
  100324. ** flag = 0
  100325. ** foreach row2 in t2 do
  100326. ** start:
  100327. ** ...
  100328. ** flag = 1
  100329. ** end
  100330. ** if flag==0 then
  100331. ** move the row2 cursor to a null row
  100332. ** goto start
  100333. ** fi
  100334. ** end
  100335. **
  100336. ** ORDER BY CLAUSE PROCESSING
  100337. **
  100338. ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  100339. ** if there is one. If there is no ORDER BY clause or if this routine
  100340. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  100341. **
  100342. ** If an index can be used so that the natural output order of the table
  100343. ** scan is correct for the ORDER BY clause, then that index is used and
  100344. ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
  100345. ** is an optimization that prevents an unnecessary sort of the result set
  100346. ** if an index appropriate for the ORDER BY clause already exists.
  100347. **
  100348. ** If the where clause loops cannot be arranged to provide the correct
  100349. ** output order, then WhereInfo.nOBSat is 0.
  100350. */
  100351. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  100352. Parse *pParse, /* The parser context */
  100353. SrcList *pTabList, /* A list of all tables to be scanned */
  100354. Expr *pWhere, /* The WHERE clause */
  100355. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  100356. ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
  100357. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  100358. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  100359. ){
  100360. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  100361. int nTabList; /* Number of elements in pTabList */
  100362. WhereInfo *pWInfo; /* Will become the return value of this function */
  100363. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  100364. Bitmask notReady; /* Cursors that are not yet positioned */
  100365. WhereBestIdx sWBI; /* Best index search context */
  100366. WhereMaskSet *pMaskSet; /* The expression mask set */
  100367. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  100368. int iFrom; /* First unused FROM clause element */
  100369. int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
  100370. int ii; /* Loop counter */
  100371. sqlite3 *db; /* Database connection */
  100372. /* Variable initialization */
  100373. memset(&sWBI, 0, sizeof(sWBI));
  100374. sWBI.pParse = pParse;
  100375. /* The number of tables in the FROM clause is limited by the number of
  100376. ** bits in a Bitmask
  100377. */
  100378. testcase( pTabList->nSrc==BMS );
  100379. if( pTabList->nSrc>BMS ){
  100380. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  100381. return 0;
  100382. }
  100383. /* This function normally generates a nested loop for all tables in
  100384. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  100385. ** only generate code for the first table in pTabList and assume that
  100386. ** any cursors associated with subsequent tables are uninitialized.
  100387. */
  100388. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  100389. /* Allocate and initialize the WhereInfo structure that will become the
  100390. ** return value. A single allocation is used to store the WhereInfo
  100391. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  100392. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  100393. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  100394. ** some architectures. Hence the ROUND8() below.
  100395. */
  100396. db = pParse->db;
  100397. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  100398. pWInfo = sqlite3DbMallocZero(db,
  100399. nByteWInfo +
  100400. sizeof(WhereClause) +
  100401. sizeof(WhereMaskSet)
  100402. );
  100403. if( db->mallocFailed ){
  100404. sqlite3DbFree(db, pWInfo);
  100405. pWInfo = 0;
  100406. goto whereBeginError;
  100407. }
  100408. pWInfo->nLevel = nTabList;
  100409. pWInfo->pParse = pParse;
  100410. pWInfo->pTabList = pTabList;
  100411. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  100412. pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
  100413. pWInfo->wctrlFlags = wctrlFlags;
  100414. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  100415. pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
  100416. sWBI.aLevel = pWInfo->a;
  100417. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  100418. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  100419. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
  100420. /* Split the WHERE clause into separate subexpressions where each
  100421. ** subexpression is separated by an AND operator.
  100422. */
  100423. initMaskSet(pMaskSet);
  100424. whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
  100425. sqlite3ExprCodeConstants(pParse, pWhere);
  100426. whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
  100427. /* Special case: a WHERE clause that is constant. Evaluate the
  100428. ** expression and either jump over all of the code or fall thru.
  100429. */
  100430. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  100431. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  100432. pWhere = 0;
  100433. }
  100434. /* Assign a bit from the bitmask to every term in the FROM clause.
  100435. **
  100436. ** When assigning bitmask values to FROM clause cursors, it must be
  100437. ** the case that if X is the bitmask for the N-th FROM clause term then
  100438. ** the bitmask for all FROM clause terms to the left of the N-th term
  100439. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  100440. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  100441. ** of the join. Subtracting one from the right table bitmask gives a
  100442. ** bitmask for all tables to the left of the join. Knowing the bitmask
  100443. ** for all tables to the left of a left join is important. Ticket #3015.
  100444. **
  100445. ** Configure the WhereClause.vmask variable so that bits that correspond
  100446. ** to virtual table cursors are set. This is used to selectively disable
  100447. ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
  100448. ** with virtual tables.
  100449. **
  100450. ** Note that bitmasks are created for all pTabList->nSrc tables in
  100451. ** pTabList, not just the first nTabList tables. nTabList is normally
  100452. ** equal to pTabList->nSrc but might be shortened to 1 if the
  100453. ** WHERE_ONETABLE_ONLY flag is set.
  100454. */
  100455. assert( sWBI.pWC->vmask==0 && pMaskSet->n==0 );
  100456. for(ii=0; ii<pTabList->nSrc; ii++){
  100457. createMask(pMaskSet, pTabList->a[ii].iCursor);
  100458. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100459. if( ALWAYS(pTabList->a[ii].pTab) && IsVirtual(pTabList->a[ii].pTab) ){
  100460. sWBI.pWC->vmask |= ((Bitmask)1 << ii);
  100461. }
  100462. #endif
  100463. }
  100464. #ifndef NDEBUG
  100465. {
  100466. Bitmask toTheLeft = 0;
  100467. for(ii=0; ii<pTabList->nSrc; ii++){
  100468. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  100469. assert( (m-1)==toTheLeft );
  100470. toTheLeft |= m;
  100471. }
  100472. }
  100473. #endif
  100474. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  100475. ** add new virtual terms onto the end of the WHERE clause. We do not
  100476. ** want to analyze these virtual terms, so start analyzing at the end
  100477. ** and work forward so that the added virtual terms are never processed.
  100478. */
  100479. exprAnalyzeAll(pTabList, sWBI.pWC);
  100480. if( db->mallocFailed ){
  100481. goto whereBeginError;
  100482. }
  100483. /* Check if the DISTINCT qualifier, if there is one, is redundant.
  100484. ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
  100485. ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
  100486. */
  100487. if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
  100488. pDistinct = 0;
  100489. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  100490. }
  100491. /* Chose the best index to use for each table in the FROM clause.
  100492. **
  100493. ** This loop fills in the following fields:
  100494. **
  100495. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  100496. ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
  100497. ** pWInfo->a[].nEq The number of == and IN constraints
  100498. ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
  100499. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  100500. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  100501. ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
  100502. **
  100503. ** This loop also figures out the nesting order of tables in the FROM
  100504. ** clause.
  100505. */
  100506. sWBI.notValid = ~(Bitmask)0;
  100507. sWBI.pOrderBy = pOrderBy;
  100508. sWBI.n = nTabList;
  100509. sWBI.pDistinct = pDistinct;
  100510. andFlags = ~0;
  100511. WHERETRACE(("*** Optimizer Start ***\n"));
  100512. for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
  100513. WhereCost bestPlan; /* Most efficient plan seen so far */
  100514. Index *pIdx; /* Index for FROM table at pTabItem */
  100515. int j; /* For looping over FROM tables */
  100516. int bestJ = -1; /* The value of j */
  100517. Bitmask m; /* Bitmask value for j or bestJ */
  100518. int isOptimal; /* Iterator for optimal/non-optimal search */
  100519. int nUnconstrained; /* Number tables without INDEXED BY */
  100520. Bitmask notIndexed; /* Mask of tables that cannot use an index */
  100521. memset(&bestPlan, 0, sizeof(bestPlan));
  100522. bestPlan.rCost = SQLITE_BIG_DBL;
  100523. WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
  100524. /* Loop through the remaining entries in the FROM clause to find the
  100525. ** next nested loop. The loop tests all FROM clause entries
  100526. ** either once or twice.
  100527. **
  100528. ** The first test is always performed if there are two or more entries
  100529. ** remaining and never performed if there is only one FROM clause entry
  100530. ** to choose from. The first test looks for an "optimal" scan. In
  100531. ** this context an optimal scan is one that uses the same strategy
  100532. ** for the given FROM clause entry as would be selected if the entry
  100533. ** were used as the innermost nested loop. In other words, a table
  100534. ** is chosen such that the cost of running that table cannot be reduced
  100535. ** by waiting for other tables to run first. This "optimal" test works
  100536. ** by first assuming that the FROM clause is on the inner loop and finding
  100537. ** its query plan, then checking to see if that query plan uses any
  100538. ** other FROM clause terms that are sWBI.notValid. If no notValid terms
  100539. ** are used then the "optimal" query plan works.
  100540. **
  100541. ** Note that the WhereCost.nRow parameter for an optimal scan might
  100542. ** not be as small as it would be if the table really were the innermost
  100543. ** join. The nRow value can be reduced by WHERE clause constraints
  100544. ** that do not use indices. But this nRow reduction only happens if the
  100545. ** table really is the innermost join.
  100546. **
  100547. ** The second loop iteration is only performed if no optimal scan
  100548. ** strategies were found by the first iteration. This second iteration
  100549. ** is used to search for the lowest cost scan overall.
  100550. **
  100551. ** Previous versions of SQLite performed only the second iteration -
  100552. ** the next outermost loop was always that with the lowest overall
  100553. ** cost. However, this meant that SQLite could select the wrong plan
  100554. ** for scripts such as the following:
  100555. **
  100556. ** CREATE TABLE t1(a, b);
  100557. ** CREATE TABLE t2(c, d);
  100558. ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
  100559. **
  100560. ** The best strategy is to iterate through table t1 first. However it
  100561. ** is not possible to determine this with a simple greedy algorithm.
  100562. ** Since the cost of a linear scan through table t2 is the same
  100563. ** as the cost of a linear scan through table t1, a simple greedy
  100564. ** algorithm may choose to use t2 for the outer loop, which is a much
  100565. ** costlier approach.
  100566. */
  100567. nUnconstrained = 0;
  100568. notIndexed = 0;
  100569. for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
  100570. for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
  100571. int doNotReorder; /* True if this table should not be reordered */
  100572. doNotReorder = (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0;
  100573. if( j!=iFrom && doNotReorder ) break;
  100574. m = getMask(pMaskSet, sWBI.pSrc->iCursor);
  100575. if( (m & sWBI.notValid)==0 ){
  100576. if( j==iFrom ) iFrom++;
  100577. continue;
  100578. }
  100579. sWBI.notReady = (isOptimal ? m : sWBI.notValid);
  100580. if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
  100581. WHERETRACE((" === trying table %d (%s) with isOptimal=%d ===\n",
  100582. j, sWBI.pSrc->pTab->zName, isOptimal));
  100583. assert( sWBI.pSrc->pTab );
  100584. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100585. if( IsVirtual(sWBI.pSrc->pTab) ){
  100586. sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
  100587. bestVirtualIndex(&sWBI);
  100588. }else
  100589. #endif
  100590. {
  100591. bestBtreeIndex(&sWBI);
  100592. }
  100593. assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
  100594. /* If an INDEXED BY clause is present, then the plan must use that
  100595. ** index if it uses any index at all */
  100596. assert( sWBI.pSrc->pIndex==0
  100597. || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
  100598. || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
  100599. if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  100600. notIndexed |= m;
  100601. }
  100602. if( isOptimal ){
  100603. pWInfo->a[j].rOptCost = sWBI.cost.rCost;
  100604. }else if( iFrom<nTabList-1 ){
  100605. /* If two or more tables have nearly the same outer loop cost,
  100606. ** very different inner loop (optimal) cost, we want to choose
  100607. ** for the outer loop that table which benefits the least from
  100608. ** being in the inner loop. The following code scales the
  100609. ** outer loop cost estimate to accomplish that. */
  100610. WHERETRACE((" scaling cost from %.1f to %.1f\n",
  100611. sWBI.cost.rCost,
  100612. sWBI.cost.rCost/pWInfo->a[j].rOptCost));
  100613. sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
  100614. }
  100615. /* Conditions under which this table becomes the best so far:
  100616. **
  100617. ** (1) The table must not depend on other tables that have not
  100618. ** yet run. (In other words, it must not depend on tables
  100619. ** in inner loops.)
  100620. **
  100621. ** (2) (This rule was removed on 2012-11-09. The scaling of the
  100622. ** cost using the optimal scan cost made this rule obsolete.)
  100623. **
  100624. ** (3) All tables have an INDEXED BY clause or this table lacks an
  100625. ** INDEXED BY clause or this table uses the specific
  100626. ** index specified by its INDEXED BY clause. This rule ensures
  100627. ** that a best-so-far is always selected even if an impossible
  100628. ** combination of INDEXED BY clauses are given. The error
  100629. ** will be detected and relayed back to the application later.
  100630. ** The NEVER() comes about because rule (2) above prevents
  100631. ** An indexable full-table-scan from reaching rule (3).
  100632. **
  100633. ** (4) The plan cost must be lower than prior plans, where "cost"
  100634. ** is defined by the compareCost() function above.
  100635. */
  100636. if( (sWBI.cost.used&sWBI.notValid)==0 /* (1) */
  100637. && (nUnconstrained==0 || sWBI.pSrc->pIndex==0 /* (3) */
  100638. || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
  100639. && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan)) /* (4) */
  100640. ){
  100641. WHERETRACE((" === table %d (%s) is best so far\n"
  100642. " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
  100643. j, sWBI.pSrc->pTab->zName,
  100644. sWBI.cost.rCost, sWBI.cost.plan.nRow,
  100645. sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
  100646. bestPlan = sWBI.cost;
  100647. bestJ = j;
  100648. }
  100649. if( doNotReorder ) break;
  100650. }
  100651. }
  100652. assert( bestJ>=0 );
  100653. assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
  100654. WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
  100655. " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
  100656. bestJ, pTabList->a[bestJ].pTab->zName,
  100657. pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
  100658. bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
  100659. if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
  100660. assert( pWInfo->eDistinct==0 );
  100661. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  100662. }
  100663. andFlags &= bestPlan.plan.wsFlags;
  100664. pLevel->plan = bestPlan.plan;
  100665. pLevel->iTabCur = pTabList->a[bestJ].iCursor;
  100666. testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
  100667. testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
  100668. if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
  100669. if( (wctrlFlags & WHERE_ONETABLE_ONLY)
  100670. && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
  100671. ){
  100672. pLevel->iIdxCur = iIdxCur;
  100673. }else{
  100674. pLevel->iIdxCur = pParse->nTab++;
  100675. }
  100676. }else{
  100677. pLevel->iIdxCur = -1;
  100678. }
  100679. sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
  100680. pLevel->iFrom = (u8)bestJ;
  100681. if( bestPlan.plan.nRow>=(double)1 ){
  100682. pParse->nQueryLoop *= bestPlan.plan.nRow;
  100683. }
  100684. /* Check that if the table scanned by this loop iteration had an
  100685. ** INDEXED BY clause attached to it, that the named index is being
  100686. ** used for the scan. If not, then query compilation has failed.
  100687. ** Return an error.
  100688. */
  100689. pIdx = pTabList->a[bestJ].pIndex;
  100690. if( pIdx ){
  100691. if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
  100692. sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
  100693. goto whereBeginError;
  100694. }else{
  100695. /* If an INDEXED BY clause is used, the bestIndex() function is
  100696. ** guaranteed to find the index specified in the INDEXED BY clause
  100697. ** if it find an index at all. */
  100698. assert( bestPlan.plan.u.pIdx==pIdx );
  100699. }
  100700. }
  100701. }
  100702. WHERETRACE(("*** Optimizer Finished ***\n"));
  100703. if( pParse->nErr || db->mallocFailed ){
  100704. goto whereBeginError;
  100705. }
  100706. if( nTabList ){
  100707. pLevel--;
  100708. pWInfo->nOBSat = pLevel->plan.nOBSat;
  100709. }else{
  100710. pWInfo->nOBSat = 0;
  100711. }
  100712. /* If the total query only selects a single row, then the ORDER BY
  100713. ** clause is irrelevant.
  100714. */
  100715. if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
  100716. assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
  100717. pWInfo->nOBSat = pOrderBy->nExpr;
  100718. }
  100719. /* If the caller is an UPDATE or DELETE statement that is requesting
  100720. ** to use a one-pass algorithm, determine if this is appropriate.
  100721. ** The one-pass algorithm only works if the WHERE clause constraints
  100722. ** the statement to update a single row.
  100723. */
  100724. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  100725. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
  100726. pWInfo->okOnePass = 1;
  100727. pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  100728. }
  100729. /* Open all tables in the pTabList and any indices selected for
  100730. ** searching those tables.
  100731. */
  100732. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  100733. notReady = ~(Bitmask)0;
  100734. pWInfo->nRowOut = (double)1;
  100735. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  100736. Table *pTab; /* Table to open */
  100737. int iDb; /* Index of database containing table/index */
  100738. struct SrcList_item *pTabItem;
  100739. pTabItem = &pTabList->a[pLevel->iFrom];
  100740. pTab = pTabItem->pTab;
  100741. pWInfo->nRowOut *= pLevel->plan.nRow;
  100742. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  100743. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  100744. /* Do nothing */
  100745. }else
  100746. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100747. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  100748. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  100749. int iCur = pTabItem->iCursor;
  100750. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  100751. }else if( IsVirtual(pTab) ){
  100752. /* noop */
  100753. }else
  100754. #endif
  100755. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  100756. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  100757. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  100758. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  100759. testcase( pTab->nCol==BMS-1 );
  100760. testcase( pTab->nCol==BMS );
  100761. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  100762. Bitmask b = pTabItem->colUsed;
  100763. int n = 0;
  100764. for(; b; b=b>>1, n++){}
  100765. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  100766. SQLITE_INT_TO_PTR(n), P4_INT32);
  100767. assert( n<=pTab->nCol );
  100768. }
  100769. }else{
  100770. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  100771. }
  100772. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  100773. if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
  100774. constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
  100775. }else
  100776. #endif
  100777. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  100778. Index *pIx = pLevel->plan.u.pIdx;
  100779. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  100780. int iIndexCur = pLevel->iIdxCur;
  100781. assert( pIx->pSchema==pTab->pSchema );
  100782. assert( iIndexCur>=0 );
  100783. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  100784. (char*)pKey, P4_KEYINFO_HANDOFF);
  100785. VdbeComment((v, "%s", pIx->zName));
  100786. }
  100787. sqlite3CodeVerifySchema(pParse, iDb);
  100788. notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
  100789. }
  100790. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  100791. if( db->mallocFailed ) goto whereBeginError;
  100792. /* Generate the code to do the search. Each iteration of the for
  100793. ** loop below generates code for a single nested loop of the VM
  100794. ** program.
  100795. */
  100796. notReady = ~(Bitmask)0;
  100797. for(ii=0; ii<nTabList; ii++){
  100798. pLevel = &pWInfo->a[ii];
  100799. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  100800. notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
  100801. pWInfo->iContinue = pLevel->addrCont;
  100802. }
  100803. #ifdef SQLITE_TEST /* For testing and debugging use only */
  100804. /* Record in the query plan information about the current table
  100805. ** and the index used to access it (if any). If the table itself
  100806. ** is not used, its name is just '{}'. If no index is used
  100807. ** the index is listed as "{}". If the primary key is used the
  100808. ** index name is '*'.
  100809. */
  100810. for(ii=0; ii<nTabList; ii++){
  100811. char *z;
  100812. int n;
  100813. int w;
  100814. struct SrcList_item *pTabItem;
  100815. pLevel = &pWInfo->a[ii];
  100816. w = pLevel->plan.wsFlags;
  100817. pTabItem = &pTabList->a[pLevel->iFrom];
  100818. z = pTabItem->zAlias;
  100819. if( z==0 ) z = pTabItem->pTab->zName;
  100820. n = sqlite3Strlen30(z);
  100821. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  100822. if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
  100823. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  100824. nQPlan += 2;
  100825. }else{
  100826. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  100827. nQPlan += n;
  100828. }
  100829. sqlite3_query_plan[nQPlan++] = ' ';
  100830. }
  100831. testcase( w & WHERE_ROWID_EQ );
  100832. testcase( w & WHERE_ROWID_RANGE );
  100833. if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  100834. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  100835. nQPlan += 2;
  100836. }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
  100837. n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
  100838. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  100839. memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
  100840. nQPlan += n;
  100841. sqlite3_query_plan[nQPlan++] = ' ';
  100842. }
  100843. }else{
  100844. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  100845. nQPlan += 3;
  100846. }
  100847. }
  100848. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  100849. sqlite3_query_plan[--nQPlan] = 0;
  100850. }
  100851. sqlite3_query_plan[nQPlan] = 0;
  100852. nQPlan = 0;
  100853. #endif /* SQLITE_TEST // Testing and debugging use only */
  100854. /* Record the continuation address in the WhereInfo structure. Then
  100855. ** clean up and return.
  100856. */
  100857. return pWInfo;
  100858. /* Jump here if malloc fails */
  100859. whereBeginError:
  100860. if( pWInfo ){
  100861. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  100862. whereInfoFree(db, pWInfo);
  100863. }
  100864. return 0;
  100865. }
  100866. /*
  100867. ** Generate the end of the WHERE loop. See comments on
  100868. ** sqlite3WhereBegin() for additional information.
  100869. */
  100870. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  100871. Parse *pParse = pWInfo->pParse;
  100872. Vdbe *v = pParse->pVdbe;
  100873. int i;
  100874. WhereLevel *pLevel;
  100875. SrcList *pTabList = pWInfo->pTabList;
  100876. sqlite3 *db = pParse->db;
  100877. /* Generate loop termination code.
  100878. */
  100879. sqlite3ExprCacheClear(pParse);
  100880. for(i=pWInfo->nLevel-1; i>=0; i--){
  100881. pLevel = &pWInfo->a[i];
  100882. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  100883. if( pLevel->op!=OP_Noop ){
  100884. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  100885. sqlite3VdbeChangeP5(v, pLevel->p5);
  100886. }
  100887. if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  100888. struct InLoop *pIn;
  100889. int j;
  100890. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  100891. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  100892. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  100893. sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
  100894. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  100895. }
  100896. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  100897. }
  100898. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  100899. if( pLevel->iLeftJoin ){
  100900. int addr;
  100901. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  100902. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  100903. || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
  100904. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
  100905. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  100906. }
  100907. if( pLevel->iIdxCur>=0 ){
  100908. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  100909. }
  100910. if( pLevel->op==OP_Return ){
  100911. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  100912. }else{
  100913. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  100914. }
  100915. sqlite3VdbeJumpHere(v, addr);
  100916. }
  100917. }
  100918. /* The "break" point is here, just past the end of the outer loop.
  100919. ** Set it.
  100920. */
  100921. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  100922. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  100923. */
  100924. assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
  100925. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  100926. Index *pIdx = 0;
  100927. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  100928. Table *pTab = pTabItem->pTab;
  100929. assert( pTab!=0 );
  100930. if( (pTab->tabFlags & TF_Ephemeral)==0
  100931. && pTab->pSelect==0
  100932. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  100933. ){
  100934. int ws = pLevel->plan.wsFlags;
  100935. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  100936. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  100937. }
  100938. if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
  100939. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  100940. }
  100941. }
  100942. /* If this scan uses an index, make code substitutions to read data
  100943. ** from the index in preference to the table. Sometimes, this means
  100944. ** the table need never be read from. This is a performance boost,
  100945. ** as the vdbe level waits until the table is read before actually
  100946. ** seeking the table cursor to the record corresponding to the current
  100947. ** position in the index.
  100948. **
  100949. ** Calls to the code generator in between sqlite3WhereBegin and
  100950. ** sqlite3WhereEnd will have created code that references the table
  100951. ** directly. This loop scans all that code looking for opcodes
  100952. ** that reference the table and converts them into opcodes that
  100953. ** reference the index.
  100954. */
  100955. if( pLevel->plan.wsFlags & WHERE_INDEXED ){
  100956. pIdx = pLevel->plan.u.pIdx;
  100957. }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  100958. pIdx = pLevel->u.pCovidx;
  100959. }
  100960. if( pIdx && !db->mallocFailed){
  100961. int k, j, last;
  100962. VdbeOp *pOp;
  100963. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  100964. last = sqlite3VdbeCurrentAddr(v);
  100965. for(k=pWInfo->iTop; k<last; k++, pOp++){
  100966. if( pOp->p1!=pLevel->iTabCur ) continue;
  100967. if( pOp->opcode==OP_Column ){
  100968. for(j=0; j<pIdx->nColumn; j++){
  100969. if( pOp->p2==pIdx->aiColumn[j] ){
  100970. pOp->p2 = j;
  100971. pOp->p1 = pLevel->iIdxCur;
  100972. break;
  100973. }
  100974. }
  100975. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  100976. || j<pIdx->nColumn );
  100977. }else if( pOp->opcode==OP_Rowid ){
  100978. pOp->p1 = pLevel->iIdxCur;
  100979. pOp->opcode = OP_IdxRowid;
  100980. }
  100981. }
  100982. }
  100983. }
  100984. /* Final cleanup
  100985. */
  100986. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  100987. whereInfoFree(db, pWInfo);
  100988. return;
  100989. }
  100990. /************** End of where.c ***********************************************/
  100991. /************** Begin file parse.c *******************************************/
  100992. /* Driver template for the LEMON parser generator.
  100993. ** The author disclaims copyright to this source code.
  100994. **
  100995. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  100996. ** The only modifications are the addition of a couple of NEVER()
  100997. ** macros to disable tests that are needed in the case of a general
  100998. ** LALR(1) grammar but which are always false in the
  100999. ** specific grammar used by SQLite.
  101000. */
  101001. /* First off, code is included that follows the "include" declaration
  101002. ** in the input grammar file. */
  101003. /* #include <stdio.h> */
  101004. /*
  101005. ** Disable all error recovery processing in the parser push-down
  101006. ** automaton.
  101007. */
  101008. #define YYNOERRORRECOVERY 1
  101009. /*
  101010. ** Make yytestcase() the same as testcase()
  101011. */
  101012. #define yytestcase(X) testcase(X)
  101013. /*
  101014. ** An instance of this structure holds information about the
  101015. ** LIMIT clause of a SELECT statement.
  101016. */
  101017. struct LimitVal {
  101018. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  101019. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  101020. };
  101021. /*
  101022. ** An instance of this structure is used to store the LIKE,
  101023. ** GLOB, NOT LIKE, and NOT GLOB operators.
  101024. */
  101025. struct LikeOp {
  101026. Token eOperator; /* "like" or "glob" or "regexp" */
  101027. int bNot; /* True if the NOT keyword is present */
  101028. };
  101029. /*
  101030. ** An instance of the following structure describes the event of a
  101031. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  101032. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  101033. **
  101034. ** UPDATE ON (a,b,c)
  101035. **
  101036. ** Then the "b" IdList records the list "a,b,c".
  101037. */
  101038. struct TrigEvent { int a; IdList * b; };
  101039. /*
  101040. ** An instance of this structure holds the ATTACH key and the key type.
  101041. */
  101042. struct AttachKey { int type; Token key; };
  101043. /*
  101044. ** One or more VALUES claues
  101045. */
  101046. struct ValueList {
  101047. ExprList *pList;
  101048. Select *pSelect;
  101049. };
  101050. /* This is a utility routine used to set the ExprSpan.zStart and
  101051. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  101052. ** range of text beginning with pStart and going to the end of pEnd.
  101053. */
  101054. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  101055. pOut->zStart = pStart->z;
  101056. pOut->zEnd = &pEnd->z[pEnd->n];
  101057. }
  101058. /* Construct a new Expr object from a single identifier. Use the
  101059. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  101060. ** that created the expression.
  101061. */
  101062. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  101063. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  101064. pOut->zStart = pValue->z;
  101065. pOut->zEnd = &pValue->z[pValue->n];
  101066. }
  101067. /* This routine constructs a binary expression node out of two ExprSpan
  101068. ** objects and uses the result to populate a new ExprSpan object.
  101069. */
  101070. static void spanBinaryExpr(
  101071. ExprSpan *pOut, /* Write the result here */
  101072. Parse *pParse, /* The parsing context. Errors accumulate here */
  101073. int op, /* The binary operation */
  101074. ExprSpan *pLeft, /* The left operand */
  101075. ExprSpan *pRight /* The right operand */
  101076. ){
  101077. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  101078. pOut->zStart = pLeft->zStart;
  101079. pOut->zEnd = pRight->zEnd;
  101080. }
  101081. /* Construct an expression node for a unary postfix operator
  101082. */
  101083. static void spanUnaryPostfix(
  101084. ExprSpan *pOut, /* Write the new expression node here */
  101085. Parse *pParse, /* Parsing context to record errors */
  101086. int op, /* The operator */
  101087. ExprSpan *pOperand, /* The operand */
  101088. Token *pPostOp /* The operand token for setting the span */
  101089. ){
  101090. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  101091. pOut->zStart = pOperand->zStart;
  101092. pOut->zEnd = &pPostOp->z[pPostOp->n];
  101093. }
  101094. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  101095. ** unary TK_ISNULL or TK_NOTNULL expression. */
  101096. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  101097. sqlite3 *db = pParse->db;
  101098. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  101099. pA->op = (u8)op;
  101100. sqlite3ExprDelete(db, pA->pRight);
  101101. pA->pRight = 0;
  101102. }
  101103. }
  101104. /* Construct an expression node for a unary prefix operator
  101105. */
  101106. static void spanUnaryPrefix(
  101107. ExprSpan *pOut, /* Write the new expression node here */
  101108. Parse *pParse, /* Parsing context to record errors */
  101109. int op, /* The operator */
  101110. ExprSpan *pOperand, /* The operand */
  101111. Token *pPreOp /* The operand token for setting the span */
  101112. ){
  101113. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  101114. pOut->zStart = pPreOp->z;
  101115. pOut->zEnd = pOperand->zEnd;
  101116. }
  101117. /* Next is all token values, in a form suitable for use by makeheaders.
  101118. ** This section will be null unless lemon is run with the -m switch.
  101119. */
  101120. /*
  101121. ** These constants (all generated automatically by the parser generator)
  101122. ** specify the various kinds of tokens (terminals) that the parser
  101123. ** understands.
  101124. **
  101125. ** Each symbol here is a terminal symbol in the grammar.
  101126. */
  101127. /* Make sure the INTERFACE macro is defined.
  101128. */
  101129. #ifndef INTERFACE
  101130. # define INTERFACE 1
  101131. #endif
  101132. /* The next thing included is series of defines which control
  101133. ** various aspects of the generated parser.
  101134. ** YYCODETYPE is the data type used for storing terminal
  101135. ** and nonterminal numbers. "unsigned char" is
  101136. ** used if there are fewer than 250 terminals
  101137. ** and nonterminals. "int" is used otherwise.
  101138. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  101139. ** to no legal terminal or nonterminal number. This
  101140. ** number is used to fill in empty slots of the hash
  101141. ** table.
  101142. ** YYFALLBACK If defined, this indicates that one or more tokens
  101143. ** have fall-back values which should be used if the
  101144. ** original value of the token will not parse.
  101145. ** YYACTIONTYPE is the data type used for storing terminal
  101146. ** and nonterminal numbers. "unsigned char" is
  101147. ** used if there are fewer than 250 rules and
  101148. ** states combined. "int" is used otherwise.
  101149. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  101150. ** directly to the parser from the tokenizer.
  101151. ** YYMINORTYPE is the data type used for all minor tokens.
  101152. ** This is typically a union of many types, one of
  101153. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  101154. ** for base tokens is called "yy0".
  101155. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  101156. ** zero the stack is dynamically sized using realloc()
  101157. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  101158. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  101159. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  101160. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  101161. ** YYNSTATE the combined number of states.
  101162. ** YYNRULE the number of rules in the grammar
  101163. ** YYERRORSYMBOL is the code number of the error symbol. If not
  101164. ** defined, then do no error processing.
  101165. */
  101166. #define YYCODETYPE unsigned char
  101167. #define YYNOCODE 251
  101168. #define YYACTIONTYPE unsigned short int
  101169. #define YYWILDCARD 67
  101170. #define sqlite3ParserTOKENTYPE Token
  101171. typedef union {
  101172. int yyinit;
  101173. sqlite3ParserTOKENTYPE yy0;
  101174. struct LimitVal yy64;
  101175. Expr* yy122;
  101176. Select* yy159;
  101177. IdList* yy180;
  101178. struct {int value; int mask;} yy207;
  101179. u8 yy258;
  101180. struct LikeOp yy318;
  101181. TriggerStep* yy327;
  101182. ExprSpan yy342;
  101183. SrcList* yy347;
  101184. int yy392;
  101185. struct TrigEvent yy410;
  101186. ExprList* yy442;
  101187. struct ValueList yy487;
  101188. } YYMINORTYPE;
  101189. #ifndef YYSTACKDEPTH
  101190. #define YYSTACKDEPTH 100
  101191. #endif
  101192. #define sqlite3ParserARG_SDECL Parse *pParse;
  101193. #define sqlite3ParserARG_PDECL ,Parse *pParse
  101194. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  101195. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  101196. #define YYNSTATE 627
  101197. #define YYNRULE 327
  101198. #define YYFALLBACK 1
  101199. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  101200. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  101201. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  101202. /* The yyzerominor constant is used to initialize instances of
  101203. ** YYMINORTYPE objects to zero. */
  101204. static const YYMINORTYPE yyzerominor = { 0 };
  101205. /* Define the yytestcase() macro to be a no-op if is not already defined
  101206. ** otherwise.
  101207. **
  101208. ** Applications can choose to define yytestcase() in the %include section
  101209. ** to a macro that can assist in verifying code coverage. For production
  101210. ** code the yytestcase() macro should be turned off. But it is useful
  101211. ** for testing.
  101212. */
  101213. #ifndef yytestcase
  101214. # define yytestcase(X)
  101215. #endif
  101216. /* Next are the tables used to determine what action to take based on the
  101217. ** current state and lookahead token. These tables are used to implement
  101218. ** functions that take a state number and lookahead value and return an
  101219. ** action integer.
  101220. **
  101221. ** Suppose the action integer is N. Then the action is determined as
  101222. ** follows
  101223. **
  101224. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  101225. ** token onto the stack and goto state N.
  101226. **
  101227. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  101228. **
  101229. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  101230. **
  101231. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  101232. **
  101233. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  101234. ** slots in the yy_action[] table.
  101235. **
  101236. ** The action table is constructed as a single large table named yy_action[].
  101237. ** Given state S and lookahead X, the action is computed as
  101238. **
  101239. ** yy_action[ yy_shift_ofst[S] + X ]
  101240. **
  101241. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  101242. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  101243. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  101244. ** and that yy_default[S] should be used instead.
  101245. **
  101246. ** The formula above is for computing the action when the lookahead is
  101247. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  101248. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  101249. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  101250. ** YY_SHIFT_USE_DFLT.
  101251. **
  101252. ** The following are the tables generated in this section:
  101253. **
  101254. ** yy_action[] A single table containing all actions.
  101255. ** yy_lookahead[] A table containing the lookahead for each entry in
  101256. ** yy_action. Used to detect hash collisions.
  101257. ** yy_shift_ofst[] For each state, the offset into yy_action for
  101258. ** shifting terminals.
  101259. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  101260. ** shifting non-terminals after a reduce.
  101261. ** yy_default[] Default action for each state.
  101262. */
  101263. #define YY_ACTTAB_COUNT (1564)
  101264. static const YYACTIONTYPE yy_action[] = {
  101265. /* 0 */ 309, 955, 184, 417, 2, 171, 624, 594, 56, 56,
  101266. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  101267. /* 20 */ 52, 52, 51, 233, 620, 619, 298, 620, 619, 234,
  101268. /* 30 */ 587, 581, 56, 56, 56, 56, 19, 54, 54, 54,
  101269. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 605, 57,
  101270. /* 50 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  101271. /* 60 */ 56, 56, 541, 54, 54, 54, 54, 53, 53, 52,
  101272. /* 70 */ 52, 52, 51, 233, 309, 594, 325, 196, 195, 194,
  101273. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  101274. /* 90 */ 51, 233, 617, 616, 165, 617, 616, 380, 377, 376,
  101275. /* 100 */ 407, 532, 576, 576, 587, 581, 303, 422, 375, 59,
  101276. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  101277. /* 120 */ 574, 545, 65, 57, 58, 48, 579, 578, 580, 580,
  101278. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  101279. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 223,
  101280. /* 150 */ 539, 420, 170, 176, 138, 280, 383, 275, 382, 168,
  101281. /* 160 */ 489, 551, 409, 668, 620, 619, 271, 438, 409, 438,
  101282. /* 170 */ 550, 604, 67, 482, 507, 618, 599, 412, 587, 581,
  101283. /* 180 */ 600, 483, 618, 412, 618, 598, 91, 439, 440, 439,
  101284. /* 190 */ 335, 598, 73, 669, 222, 266, 480, 57, 58, 48,
  101285. /* 200 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  101286. /* 210 */ 670, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  101287. /* 220 */ 51, 233, 309, 279, 232, 231, 1, 132, 200, 385,
  101288. /* 230 */ 620, 619, 617, 616, 278, 435, 289, 563, 175, 262,
  101289. /* 240 */ 409, 264, 437, 497, 436, 166, 441, 568, 336, 568,
  101290. /* 250 */ 201, 537, 587, 581, 599, 412, 165, 594, 600, 380,
  101291. /* 260 */ 377, 376, 597, 598, 92, 523, 618, 569, 569, 592,
  101292. /* 270 */ 375, 57, 58, 48, 579, 578, 580, 580, 55, 55,
  101293. /* 280 */ 56, 56, 56, 56, 597, 54, 54, 54, 54, 53,
  101294. /* 290 */ 53, 52, 52, 52, 51, 233, 309, 463, 617, 616,
  101295. /* 300 */ 590, 590, 590, 174, 272, 396, 409, 272, 409, 548,
  101296. /* 310 */ 397, 620, 619, 68, 326, 620, 619, 620, 619, 618,
  101297. /* 320 */ 546, 412, 618, 412, 471, 594, 587, 581, 472, 598,
  101298. /* 330 */ 92, 598, 92, 52, 52, 52, 51, 233, 513, 512,
  101299. /* 340 */ 206, 322, 363, 464, 221, 57, 58, 48, 579, 578,
  101300. /* 350 */ 580, 580, 55, 55, 56, 56, 56, 56, 529, 54,
  101301. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  101302. /* 370 */ 309, 396, 409, 396, 597, 372, 386, 530, 347, 617,
  101303. /* 380 */ 616, 575, 202, 617, 616, 617, 616, 412, 620, 619,
  101304. /* 390 */ 145, 255, 346, 254, 577, 598, 74, 351, 45, 489,
  101305. /* 400 */ 587, 581, 235, 189, 464, 544, 167, 296, 187, 469,
  101306. /* 410 */ 479, 67, 62, 39, 618, 546, 597, 345, 573, 57,
  101307. /* 420 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  101308. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  101309. /* 440 */ 52, 52, 51, 233, 309, 562, 558, 407, 528, 576,
  101310. /* 450 */ 576, 344, 255, 346, 254, 182, 617, 616, 503, 504,
  101311. /* 460 */ 314, 409, 557, 235, 166, 271, 409, 352, 564, 181,
  101312. /* 470 */ 407, 546, 576, 576, 587, 581, 412, 537, 556, 561,
  101313. /* 480 */ 517, 412, 618, 249, 598, 16, 7, 36, 467, 598,
  101314. /* 490 */ 92, 516, 618, 57, 58, 48, 579, 578, 580, 580,
  101315. /* 500 */ 55, 55, 56, 56, 56, 56, 541, 54, 54, 54,
  101316. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 327,
  101317. /* 520 */ 572, 571, 525, 558, 560, 394, 871, 246, 409, 248,
  101318. /* 530 */ 171, 392, 594, 219, 407, 409, 576, 576, 502, 557,
  101319. /* 540 */ 364, 145, 510, 412, 407, 229, 576, 576, 587, 581,
  101320. /* 550 */ 412, 598, 92, 381, 269, 556, 166, 400, 598, 69,
  101321. /* 560 */ 501, 419, 945, 199, 945, 198, 546, 57, 58, 48,
  101322. /* 570 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  101323. /* 580 */ 568, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  101324. /* 590 */ 51, 233, 309, 317, 419, 944, 508, 944, 308, 597,
  101325. /* 600 */ 594, 565, 490, 212, 173, 247, 423, 615, 614, 613,
  101326. /* 610 */ 323, 197, 143, 405, 572, 571, 489, 66, 50, 47,
  101327. /* 620 */ 146, 594, 587, 581, 232, 231, 559, 427, 67, 555,
  101328. /* 630 */ 15, 618, 186, 543, 303, 421, 35, 206, 432, 423,
  101329. /* 640 */ 552, 57, 58, 48, 579, 578, 580, 580, 55, 55,
  101330. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  101331. /* 660 */ 53, 52, 52, 52, 51, 233, 309, 569, 569, 260,
  101332. /* 670 */ 268, 597, 12, 373, 568, 166, 409, 313, 409, 420,
  101333. /* 680 */ 409, 473, 473, 365, 618, 50, 47, 146, 597, 594,
  101334. /* 690 */ 468, 412, 166, 412, 351, 412, 587, 581, 32, 598,
  101335. /* 700 */ 94, 598, 97, 598, 95, 627, 625, 329, 142, 50,
  101336. /* 710 */ 47, 146, 333, 349, 358, 57, 58, 48, 579, 578,
  101337. /* 720 */ 580, 580, 55, 55, 56, 56, 56, 56, 409, 54,
  101338. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  101339. /* 740 */ 309, 409, 388, 412, 409, 22, 565, 404, 212, 362,
  101340. /* 750 */ 389, 598, 104, 359, 409, 156, 412, 409, 603, 412,
  101341. /* 760 */ 537, 331, 569, 569, 598, 103, 493, 598, 105, 412,
  101342. /* 770 */ 587, 581, 412, 260, 549, 618, 11, 598, 106, 521,
  101343. /* 780 */ 598, 133, 169, 457, 456, 170, 35, 601, 618, 57,
  101344. /* 790 */ 58, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  101345. /* 800 */ 56, 56, 409, 54, 54, 54, 54, 53, 53, 52,
  101346. /* 810 */ 52, 52, 51, 233, 309, 409, 259, 412, 409, 50,
  101347. /* 820 */ 47, 146, 357, 318, 355, 598, 134, 527, 352, 337,
  101348. /* 830 */ 412, 409, 356, 412, 357, 409, 357, 618, 598, 98,
  101349. /* 840 */ 129, 598, 102, 618, 587, 581, 412, 21, 235, 618,
  101350. /* 850 */ 412, 618, 211, 143, 598, 101, 30, 167, 598, 93,
  101351. /* 860 */ 350, 535, 203, 57, 58, 48, 579, 578, 580, 580,
  101352. /* 870 */ 55, 55, 56, 56, 56, 56, 409, 54, 54, 54,
  101353. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 309, 409,
  101354. /* 890 */ 526, 412, 409, 425, 215, 305, 597, 551, 141, 598,
  101355. /* 900 */ 100, 40, 409, 38, 412, 409, 550, 412, 409, 228,
  101356. /* 910 */ 220, 314, 598, 77, 500, 598, 96, 412, 587, 581,
  101357. /* 920 */ 412, 338, 253, 412, 218, 598, 137, 379, 598, 136,
  101358. /* 930 */ 28, 598, 135, 270, 715, 210, 481, 57, 58, 48,
  101359. /* 940 */ 579, 578, 580, 580, 55, 55, 56, 56, 56, 56,
  101360. /* 950 */ 409, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  101361. /* 960 */ 51, 233, 309, 409, 272, 412, 409, 315, 147, 597,
  101362. /* 970 */ 272, 626, 2, 598, 76, 209, 409, 127, 412, 618,
  101363. /* 980 */ 126, 412, 409, 621, 235, 618, 598, 90, 374, 598,
  101364. /* 990 */ 89, 412, 587, 581, 27, 260, 350, 412, 618, 598,
  101365. /* 1000 */ 75, 321, 541, 541, 125, 598, 88, 320, 278, 597,
  101366. /* 1010 */ 618, 57, 46, 48, 579, 578, 580, 580, 55, 55,
  101367. /* 1020 */ 56, 56, 56, 56, 409, 54, 54, 54, 54, 53,
  101368. /* 1030 */ 53, 52, 52, 52, 51, 233, 309, 409, 450, 412,
  101369. /* 1040 */ 164, 284, 282, 272, 609, 424, 304, 598, 87, 370,
  101370. /* 1050 */ 409, 477, 412, 409, 608, 409, 607, 602, 618, 618,
  101371. /* 1060 */ 598, 99, 586, 585, 122, 412, 587, 581, 412, 618,
  101372. /* 1070 */ 412, 618, 618, 598, 86, 366, 598, 17, 598, 85,
  101373. /* 1080 */ 319, 185, 519, 518, 583, 582, 58, 48, 579, 578,
  101374. /* 1090 */ 580, 580, 55, 55, 56, 56, 56, 56, 409, 54,
  101375. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  101376. /* 1110 */ 309, 584, 409, 412, 409, 260, 260, 260, 408, 591,
  101377. /* 1120 */ 474, 598, 84, 170, 409, 466, 518, 412, 121, 412,
  101378. /* 1130 */ 618, 618, 618, 618, 618, 598, 83, 598, 72, 412,
  101379. /* 1140 */ 587, 581, 51, 233, 625, 329, 470, 598, 71, 257,
  101380. /* 1150 */ 159, 120, 14, 462, 157, 158, 117, 260, 448, 447,
  101381. /* 1160 */ 446, 48, 579, 578, 580, 580, 55, 55, 56, 56,
  101382. /* 1170 */ 56, 56, 618, 54, 54, 54, 54, 53, 53, 52,
  101383. /* 1180 */ 52, 52, 51, 233, 44, 403, 260, 3, 409, 459,
  101384. /* 1190 */ 260, 413, 619, 118, 398, 10, 25, 24, 554, 348,
  101385. /* 1200 */ 217, 618, 406, 412, 409, 618, 4, 44, 403, 618,
  101386. /* 1210 */ 3, 598, 82, 618, 413, 619, 455, 542, 115, 412,
  101387. /* 1220 */ 538, 401, 536, 274, 506, 406, 251, 598, 81, 216,
  101388. /* 1230 */ 273, 563, 618, 243, 453, 618, 154, 618, 618, 618,
  101389. /* 1240 */ 449, 416, 623, 110, 401, 618, 409, 236, 64, 123,
  101390. /* 1250 */ 487, 41, 42, 531, 563, 204, 409, 267, 43, 411,
  101391. /* 1260 */ 410, 412, 265, 592, 108, 618, 107, 434, 332, 598,
  101392. /* 1270 */ 80, 412, 618, 263, 41, 42, 443, 618, 409, 598,
  101393. /* 1280 */ 70, 43, 411, 410, 433, 261, 592, 149, 618, 597,
  101394. /* 1290 */ 256, 237, 188, 412, 590, 590, 590, 589, 588, 13,
  101395. /* 1300 */ 618, 598, 18, 328, 235, 618, 44, 403, 360, 3,
  101396. /* 1310 */ 418, 461, 339, 413, 619, 227, 124, 590, 590, 590,
  101397. /* 1320 */ 589, 588, 13, 618, 406, 409, 618, 409, 139, 34,
  101398. /* 1330 */ 403, 387, 3, 148, 622, 312, 413, 619, 311, 330,
  101399. /* 1340 */ 412, 460, 412, 401, 180, 353, 412, 406, 598, 79,
  101400. /* 1350 */ 598, 78, 250, 563, 598, 9, 618, 612, 611, 610,
  101401. /* 1360 */ 618, 8, 452, 442, 242, 415, 401, 618, 239, 235,
  101402. /* 1370 */ 179, 238, 428, 41, 42, 288, 563, 618, 618, 618,
  101403. /* 1380 */ 43, 411, 410, 618, 144, 592, 618, 618, 177, 61,
  101404. /* 1390 */ 618, 596, 391, 620, 619, 287, 41, 42, 414, 618,
  101405. /* 1400 */ 293, 30, 393, 43, 411, 410, 292, 618, 592, 31,
  101406. /* 1410 */ 618, 395, 291, 60, 230, 37, 590, 590, 590, 589,
  101407. /* 1420 */ 588, 13, 214, 553, 183, 290, 172, 301, 300, 299,
  101408. /* 1430 */ 178, 297, 595, 563, 451, 29, 285, 390, 540, 590,
  101409. /* 1440 */ 590, 590, 589, 588, 13, 283, 520, 534, 150, 533,
  101410. /* 1450 */ 241, 281, 384, 192, 191, 324, 515, 514, 276, 240,
  101411. /* 1460 */ 510, 523, 307, 511, 128, 592, 509, 225, 226, 486,
  101412. /* 1470 */ 485, 224, 152, 491, 464, 306, 484, 163, 153, 371,
  101413. /* 1480 */ 478, 151, 162, 258, 369, 161, 367, 208, 475, 476,
  101414. /* 1490 */ 26, 160, 465, 140, 361, 131, 590, 590, 590, 116,
  101415. /* 1500 */ 119, 454, 343, 155, 114, 342, 113, 112, 445, 111,
  101416. /* 1510 */ 130, 109, 431, 316, 426, 430, 23, 429, 20, 606,
  101417. /* 1520 */ 190, 507, 255, 341, 244, 63, 294, 593, 310, 570,
  101418. /* 1530 */ 277, 402, 354, 235, 567, 496, 495, 492, 494, 302,
  101419. /* 1540 */ 458, 378, 286, 245, 566, 5, 252, 547, 193, 444,
  101420. /* 1550 */ 233, 340, 207, 524, 368, 505, 334, 522, 499, 399,
  101421. /* 1560 */ 295, 498, 956, 488,
  101422. };
  101423. static const YYCODETYPE yy_lookahead[] = {
  101424. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  101425. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  101426. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  101427. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  101428. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  101429. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  101430. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  101431. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  101432. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  101433. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  101434. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  101435. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  101436. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  101437. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  101438. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  101439. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  101440. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  101441. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  101442. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  101443. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  101444. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  101445. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  101446. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  101447. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  101448. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  101449. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  101450. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  101451. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  101452. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  101453. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  101454. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  101455. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  101456. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  101457. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  101458. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  101459. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  101460. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  101461. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  101462. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  101463. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  101464. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  101465. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  101466. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  101467. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  101468. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  101469. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  101470. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  101471. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  101472. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  101473. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  101474. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  101475. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  101476. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  101477. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  101478. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  101479. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  101480. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  101481. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  101482. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  101483. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  101484. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  101485. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  101486. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  101487. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  101488. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  101489. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  101490. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  101491. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  101492. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  101493. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  101494. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  101495. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  101496. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  101497. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  101498. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  101499. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  101500. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  101501. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  101502. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  101503. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  101504. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  101505. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  101506. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  101507. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  101508. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  101509. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  101510. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  101511. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  101512. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  101513. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  101514. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  101515. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  101516. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  101517. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  101518. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  101519. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  101520. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  101521. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  101522. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  101523. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  101524. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  101525. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  101526. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  101527. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  101528. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  101529. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  101530. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  101531. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  101532. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  101533. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  101534. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  101535. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  101536. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  101537. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  101538. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  101539. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  101540. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  101541. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  101542. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  101543. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  101544. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  101545. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  101546. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  101547. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  101548. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  101549. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  101550. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  101551. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  101552. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  101553. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  101554. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  101555. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  101556. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  101557. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  101558. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  101559. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  101560. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  101561. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  101562. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  101563. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  101564. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  101565. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  101566. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  101567. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  101568. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  101569. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  101570. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  101571. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  101572. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  101573. /* 1490 */ 135, 156, 189, 68, 157, 218, 129, 130, 131, 22,
  101574. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  101575. /* 1510 */ 218, 189, 40, 157, 38, 157, 240, 157, 240, 153,
  101576. /* 1520 */ 196, 181, 105, 106, 107, 243, 198, 166, 111, 230,
  101577. /* 1530 */ 176, 226, 239, 116, 230, 176, 166, 166, 176, 148,
  101578. /* 1540 */ 199, 177, 209, 209, 166, 196, 239, 208, 185, 199,
  101579. /* 1550 */ 92, 209, 233, 173, 234, 182, 139, 173, 182, 191,
  101580. /* 1560 */ 195, 182, 250, 186,
  101581. };
  101582. #define YY_SHIFT_USE_DFLT (-70)
  101583. #define YY_SHIFT_COUNT (416)
  101584. #define YY_SHIFT_MIN (-69)
  101585. #define YY_SHIFT_MAX (1487)
  101586. static const short yy_shift_ofst[] = {
  101587. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  101588. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  101589. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  101590. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  101591. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  101592. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  101593. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  101594. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  101595. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  101596. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  101597. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  101598. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  101599. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  101600. /* 130 */ 732, 868, 231, 1051, 1458, -70, -70, -70, 1367, 57,
  101601. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  101602. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  101603. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  101604. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  101605. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  101606. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  101607. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  101608. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  101609. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  101610. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1476, 1308, 1308,
  101611. /* 240 */ 1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
  101612. /* 250 */ 1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
  101613. /* 260 */ 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
  101614. /* 270 */ 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
  101615. /* 280 */ 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
  101616. /* 290 */ 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
  101617. /* 300 */ 1338, 1338, 1338, -70, -70, -70, -70, -70, -70, 1013,
  101618. /* 310 */ 467, 612, 84, 179, -28, 870, 410, 761, 760, 667,
  101619. /* 320 */ 650, 531, 220, 361, 331, 125, 127, 97, 1306, 1300,
  101620. /* 330 */ 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
  101621. /* 340 */ 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
  101622. /* 350 */ 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
  101623. /* 360 */ 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960, 1057,
  101624. /* 370 */ 1031, 1030, 899, 938, 982, 936, 972, 958, 910, 955,
  101625. /* 380 */ 875, 885, 908, 857, 859, 867, 804, 590, 834, 747,
  101626. /* 390 */ 818, 513, 611, 741, 673, 637, 611, 606, 603, 579,
  101627. /* 400 */ 501, 541, 468, 386, 445, 395, 376, 281, 185, 120,
  101628. /* 410 */ 92, 75, 45, 114, 25, 11, 5,
  101629. };
  101630. #define YY_REDUCE_USE_DFLT (-169)
  101631. #define YY_REDUCE_COUNT (308)
  101632. #define YY_REDUCE_MIN (-168)
  101633. #define YY_REDUCE_MAX (1391)
  101634. static const short yy_reduce_ofst[] = {
  101635. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  101636. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  101637. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  101638. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  101639. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  101640. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  101641. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  101642. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  101643. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  101644. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  101645. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  101646. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  101647. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  101648. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  101649. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  101650. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  101651. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  101652. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  101653. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  101654. /* 190 */ -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
  101655. /* 200 */ 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
  101656. /* 210 */ 1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
  101657. /* 220 */ 1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
  101658. /* 230 */ 1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
  101659. /* 240 */ 1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
  101660. /* 250 */ 1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
  101661. /* 260 */ 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
  101662. /* 270 */ 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
  101663. /* 280 */ 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
  101664. /* 290 */ 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
  101665. /* 300 */ 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  101666. };
  101667. static const YYACTIONTYPE yy_default[] = {
  101668. /* 0 */ 632, 866, 954, 954, 866, 866, 954, 954, 954, 756,
  101669. /* 10 */ 954, 954, 954, 864, 954, 954, 784, 784, 928, 954,
  101670. /* 20 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101671. /* 30 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101672. /* 40 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101673. /* 50 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101674. /* 60 */ 954, 954, 954, 954, 954, 954, 954, 671, 760, 790,
  101675. /* 70 */ 954, 954, 954, 954, 954, 954, 954, 954, 927, 929,
  101676. /* 80 */ 798, 797, 907, 771, 795, 788, 792, 867, 860, 861,
  101677. /* 90 */ 859, 863, 868, 954, 791, 827, 844, 826, 838, 843,
  101678. /* 100 */ 850, 842, 839, 829, 828, 830, 831, 954, 954, 954,
  101679. /* 110 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101680. /* 120 */ 954, 954, 954, 658, 725, 954, 954, 954, 954, 954,
  101681. /* 130 */ 954, 954, 954, 832, 833, 847, 846, 845, 954, 663,
  101682. /* 140 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101683. /* 150 */ 934, 932, 954, 879, 954, 954, 954, 954, 954, 954,
  101684. /* 160 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101685. /* 170 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101686. /* 180 */ 638, 756, 756, 756, 632, 954, 954, 954, 946, 760,
  101687. /* 190 */ 750, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101688. /* 200 */ 954, 954, 954, 800, 739, 917, 919, 954, 900, 737,
  101689. /* 210 */ 660, 758, 673, 748, 640, 794, 773, 773, 912, 794,
  101690. /* 220 */ 912, 696, 719, 954, 784, 954, 784, 693, 784, 773,
  101691. /* 230 */ 862, 954, 954, 954, 757, 748, 954, 939, 764, 764,
  101692. /* 240 */ 931, 931, 764, 806, 729, 794, 736, 736, 736, 736,
  101693. /* 250 */ 764, 655, 794, 806, 729, 729, 764, 655, 906, 904,
  101694. /* 260 */ 764, 764, 655, 764, 655, 764, 655, 872, 727, 727,
  101695. /* 270 */ 727, 711, 876, 876, 872, 727, 696, 727, 711, 727,
  101696. /* 280 */ 727, 777, 772, 777, 772, 777, 772, 764, 764, 954,
  101697. /* 290 */ 789, 778, 787, 785, 794, 954, 714, 648, 648, 637,
  101698. /* 300 */ 637, 637, 637, 951, 951, 946, 698, 698, 681, 954,
  101699. /* 310 */ 954, 954, 954, 954, 954, 954, 881, 954, 954, 954,
  101700. /* 320 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 633,
  101701. /* 330 */ 941, 954, 954, 938, 954, 954, 954, 954, 799, 954,
  101702. /* 340 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 916,
  101703. /* 350 */ 954, 954, 954, 954, 954, 954, 954, 910, 954, 954,
  101704. /* 360 */ 954, 954, 954, 954, 903, 902, 954, 954, 954, 954,
  101705. /* 370 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101706. /* 380 */ 954, 954, 954, 954, 954, 954, 954, 954, 954, 954,
  101707. /* 390 */ 954, 954, 786, 954, 779, 954, 865, 954, 954, 954,
  101708. /* 400 */ 954, 954, 954, 954, 954, 954, 954, 742, 815, 954,
  101709. /* 410 */ 814, 818, 813, 665, 954, 646, 954, 629, 634, 950,
  101710. /* 420 */ 953, 952, 949, 948, 947, 942, 940, 937, 936, 935,
  101711. /* 430 */ 933, 930, 926, 885, 883, 890, 889, 888, 887, 886,
  101712. /* 440 */ 884, 882, 880, 801, 796, 793, 925, 878, 738, 735,
  101713. /* 450 */ 734, 654, 943, 909, 918, 805, 804, 807, 915, 914,
  101714. /* 460 */ 913, 911, 908, 895, 803, 802, 730, 870, 869, 657,
  101715. /* 470 */ 899, 898, 897, 901, 905, 896, 766, 656, 653, 662,
  101716. /* 480 */ 717, 718, 726, 724, 723, 722, 721, 720, 716, 664,
  101717. /* 490 */ 672, 710, 695, 694, 875, 877, 874, 873, 703, 702,
  101718. /* 500 */ 708, 707, 706, 705, 704, 701, 700, 699, 692, 691,
  101719. /* 510 */ 697, 690, 713, 712, 709, 689, 733, 732, 731, 728,
  101720. /* 520 */ 688, 687, 686, 818, 685, 684, 824, 823, 811, 854,
  101721. /* 530 */ 753, 752, 751, 763, 762, 775, 774, 809, 808, 776,
  101722. /* 540 */ 761, 755, 754, 770, 769, 768, 767, 759, 749, 781,
  101723. /* 550 */ 783, 782, 780, 856, 765, 853, 924, 923, 922, 921,
  101724. /* 560 */ 920, 858, 857, 825, 822, 676, 677, 893, 892, 894,
  101725. /* 570 */ 891, 679, 678, 675, 674, 855, 744, 743, 851, 848,
  101726. /* 580 */ 840, 836, 852, 849, 841, 837, 835, 834, 820, 819,
  101727. /* 590 */ 817, 816, 812, 821, 667, 745, 741, 740, 810, 747,
  101728. /* 600 */ 746, 683, 682, 680, 661, 659, 652, 650, 649, 651,
  101729. /* 610 */ 647, 645, 644, 643, 642, 641, 670, 669, 668, 666,
  101730. /* 620 */ 665, 639, 636, 635, 631, 630, 628,
  101731. };
  101732. /* The next table maps tokens into fallback tokens. If a construct
  101733. ** like the following:
  101734. **
  101735. ** %fallback ID X Y Z.
  101736. **
  101737. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  101738. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  101739. ** but it does not parse, the type of the token is changed to ID and
  101740. ** the parse is retried before an error is thrown.
  101741. */
  101742. #ifdef YYFALLBACK
  101743. static const YYCODETYPE yyFallback[] = {
  101744. 0, /* $ => nothing */
  101745. 0, /* SEMI => nothing */
  101746. 26, /* EXPLAIN => ID */
  101747. 26, /* QUERY => ID */
  101748. 26, /* PLAN => ID */
  101749. 26, /* BEGIN => ID */
  101750. 0, /* TRANSACTION => nothing */
  101751. 26, /* DEFERRED => ID */
  101752. 26, /* IMMEDIATE => ID */
  101753. 26, /* EXCLUSIVE => ID */
  101754. 0, /* COMMIT => nothing */
  101755. 26, /* END => ID */
  101756. 26, /* ROLLBACK => ID */
  101757. 26, /* SAVEPOINT => ID */
  101758. 26, /* RELEASE => ID */
  101759. 0, /* TO => nothing */
  101760. 0, /* TABLE => nothing */
  101761. 0, /* CREATE => nothing */
  101762. 26, /* IF => ID */
  101763. 0, /* NOT => nothing */
  101764. 0, /* EXISTS => nothing */
  101765. 26, /* TEMP => ID */
  101766. 0, /* LP => nothing */
  101767. 0, /* RP => nothing */
  101768. 0, /* AS => nothing */
  101769. 0, /* COMMA => nothing */
  101770. 0, /* ID => nothing */
  101771. 0, /* INDEXED => nothing */
  101772. 26, /* ABORT => ID */
  101773. 26, /* ACTION => ID */
  101774. 26, /* AFTER => ID */
  101775. 26, /* ANALYZE => ID */
  101776. 26, /* ASC => ID */
  101777. 26, /* ATTACH => ID */
  101778. 26, /* BEFORE => ID */
  101779. 26, /* BY => ID */
  101780. 26, /* CASCADE => ID */
  101781. 26, /* CAST => ID */
  101782. 26, /* COLUMNKW => ID */
  101783. 26, /* CONFLICT => ID */
  101784. 26, /* DATABASE => ID */
  101785. 26, /* DESC => ID */
  101786. 26, /* DETACH => ID */
  101787. 26, /* EACH => ID */
  101788. 26, /* FAIL => ID */
  101789. 26, /* FOR => ID */
  101790. 26, /* IGNORE => ID */
  101791. 26, /* INITIALLY => ID */
  101792. 26, /* INSTEAD => ID */
  101793. 26, /* LIKE_KW => ID */
  101794. 26, /* MATCH => ID */
  101795. 26, /* NO => ID */
  101796. 26, /* KEY => ID */
  101797. 26, /* OF => ID */
  101798. 26, /* OFFSET => ID */
  101799. 26, /* PRAGMA => ID */
  101800. 26, /* RAISE => ID */
  101801. 26, /* REPLACE => ID */
  101802. 26, /* RESTRICT => ID */
  101803. 26, /* ROW => ID */
  101804. 26, /* TRIGGER => ID */
  101805. 26, /* VACUUM => ID */
  101806. 26, /* VIEW => ID */
  101807. 26, /* VIRTUAL => ID */
  101808. 26, /* REINDEX => ID */
  101809. 26, /* RENAME => ID */
  101810. 26, /* CTIME_KW => ID */
  101811. };
  101812. #endif /* YYFALLBACK */
  101813. /* The following structure represents a single element of the
  101814. ** parser's stack. Information stored includes:
  101815. **
  101816. ** + The state number for the parser at this level of the stack.
  101817. **
  101818. ** + The value of the token stored at this level of the stack.
  101819. ** (In other words, the "major" token.)
  101820. **
  101821. ** + The semantic value stored at this level of the stack. This is
  101822. ** the information used by the action routines in the grammar.
  101823. ** It is sometimes called the "minor" token.
  101824. */
  101825. struct yyStackEntry {
  101826. YYACTIONTYPE stateno; /* The state-number */
  101827. YYCODETYPE major; /* The major token value. This is the code
  101828. ** number for the token at this stack level */
  101829. YYMINORTYPE minor; /* The user-supplied minor token value. This
  101830. ** is the value of the token */
  101831. };
  101832. typedef struct yyStackEntry yyStackEntry;
  101833. /* The state of the parser is completely contained in an instance of
  101834. ** the following structure */
  101835. struct yyParser {
  101836. int yyidx; /* Index of top element in stack */
  101837. #ifdef YYTRACKMAXSTACKDEPTH
  101838. int yyidxMax; /* Maximum value of yyidx */
  101839. #endif
  101840. int yyerrcnt; /* Shifts left before out of the error */
  101841. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  101842. #if YYSTACKDEPTH<=0
  101843. int yystksz; /* Current side of the stack */
  101844. yyStackEntry *yystack; /* The parser's stack */
  101845. #else
  101846. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  101847. #endif
  101848. };
  101849. typedef struct yyParser yyParser;
  101850. #ifndef NDEBUG
  101851. /* #include <stdio.h> */
  101852. static FILE *yyTraceFILE = 0;
  101853. static char *yyTracePrompt = 0;
  101854. #endif /* NDEBUG */
  101855. #ifndef NDEBUG
  101856. /*
  101857. ** Turn parser tracing on by giving a stream to which to write the trace
  101858. ** and a prompt to preface each trace message. Tracing is turned off
  101859. ** by making either argument NULL
  101860. **
  101861. ** Inputs:
  101862. ** <ul>
  101863. ** <li> A FILE* to which trace output should be written.
  101864. ** If NULL, then tracing is turned off.
  101865. ** <li> A prefix string written at the beginning of every
  101866. ** line of trace output. If NULL, then tracing is
  101867. ** turned off.
  101868. ** </ul>
  101869. **
  101870. ** Outputs:
  101871. ** None.
  101872. */
  101873. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  101874. yyTraceFILE = TraceFILE;
  101875. yyTracePrompt = zTracePrompt;
  101876. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  101877. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  101878. }
  101879. #endif /* NDEBUG */
  101880. #ifndef NDEBUG
  101881. /* For tracing shifts, the names of all terminals and nonterminals
  101882. ** are required. The following table supplies these names */
  101883. static const char *const yyTokenName[] = {
  101884. "$", "SEMI", "EXPLAIN", "QUERY",
  101885. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  101886. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  101887. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  101888. "TABLE", "CREATE", "IF", "NOT",
  101889. "EXISTS", "TEMP", "LP", "RP",
  101890. "AS", "COMMA", "ID", "INDEXED",
  101891. "ABORT", "ACTION", "AFTER", "ANALYZE",
  101892. "ASC", "ATTACH", "BEFORE", "BY",
  101893. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  101894. "DATABASE", "DESC", "DETACH", "EACH",
  101895. "FAIL", "FOR", "IGNORE", "INITIALLY",
  101896. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  101897. "KEY", "OF", "OFFSET", "PRAGMA",
  101898. "RAISE", "REPLACE", "RESTRICT", "ROW",
  101899. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  101900. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  101901. "OR", "AND", "IS", "BETWEEN",
  101902. "IN", "ISNULL", "NOTNULL", "NE",
  101903. "EQ", "GT", "LE", "LT",
  101904. "GE", "ESCAPE", "BITAND", "BITOR",
  101905. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  101906. "STAR", "SLASH", "REM", "CONCAT",
  101907. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  101908. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  101909. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  101910. "ON", "INSERT", "DELETE", "UPDATE",
  101911. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  101912. "UNION", "ALL", "EXCEPT", "INTERSECT",
  101913. "SELECT", "DISTINCT", "DOT", "FROM",
  101914. "JOIN", "USING", "ORDER", "GROUP",
  101915. "HAVING", "LIMIT", "WHERE", "INTO",
  101916. "VALUES", "INTEGER", "FLOAT", "BLOB",
  101917. "REGISTER", "VARIABLE", "CASE", "WHEN",
  101918. "THEN", "ELSE", "INDEX", "ALTER",
  101919. "ADD", "error", "input", "cmdlist",
  101920. "ecmd", "explain", "cmdx", "cmd",
  101921. "transtype", "trans_opt", "nm", "savepoint_opt",
  101922. "create_table", "create_table_args", "createkw", "temp",
  101923. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  101924. "select", "column", "columnid", "type",
  101925. "carglist", "id", "ids", "typetoken",
  101926. "typename", "signed", "plus_num", "minus_num",
  101927. "ccons", "term", "expr", "onconf",
  101928. "sortorder", "autoinc", "idxlist_opt", "refargs",
  101929. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  101930. "conslist", "tconscomma", "tcons", "idxlist",
  101931. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  101932. "ifexists", "fullname", "oneselect", "multiselect_op",
  101933. "distinct", "selcollist", "from", "where_opt",
  101934. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  101935. "sclp", "as", "seltablist", "stl_prefix",
  101936. "joinop", "indexed_opt", "on_opt", "using_opt",
  101937. "joinop2", "inscollist", "sortlist", "nexprlist",
  101938. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  101939. "exprlist", "likeop", "between_op", "in_op",
  101940. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  101941. "collate", "nmnum", "number", "trigger_decl",
  101942. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  101943. "when_clause", "trigger_cmd", "trnm", "tridxby",
  101944. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  101945. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  101946. "lp", "anylist",
  101947. };
  101948. #endif /* NDEBUG */
  101949. #ifndef NDEBUG
  101950. /* For tracing reduce actions, the names of all rules are required.
  101951. */
  101952. static const char *const yyRuleName[] = {
  101953. /* 0 */ "input ::= cmdlist",
  101954. /* 1 */ "cmdlist ::= cmdlist ecmd",
  101955. /* 2 */ "cmdlist ::= ecmd",
  101956. /* 3 */ "ecmd ::= SEMI",
  101957. /* 4 */ "ecmd ::= explain cmdx SEMI",
  101958. /* 5 */ "explain ::=",
  101959. /* 6 */ "explain ::= EXPLAIN",
  101960. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  101961. /* 8 */ "cmdx ::= cmd",
  101962. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  101963. /* 10 */ "trans_opt ::=",
  101964. /* 11 */ "trans_opt ::= TRANSACTION",
  101965. /* 12 */ "trans_opt ::= TRANSACTION nm",
  101966. /* 13 */ "transtype ::=",
  101967. /* 14 */ "transtype ::= DEFERRED",
  101968. /* 15 */ "transtype ::= IMMEDIATE",
  101969. /* 16 */ "transtype ::= EXCLUSIVE",
  101970. /* 17 */ "cmd ::= COMMIT trans_opt",
  101971. /* 18 */ "cmd ::= END trans_opt",
  101972. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  101973. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  101974. /* 21 */ "savepoint_opt ::=",
  101975. /* 22 */ "cmd ::= SAVEPOINT nm",
  101976. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  101977. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  101978. /* 25 */ "cmd ::= create_table create_table_args",
  101979. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  101980. /* 27 */ "createkw ::= CREATE",
  101981. /* 28 */ "ifnotexists ::=",
  101982. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  101983. /* 30 */ "temp ::= TEMP",
  101984. /* 31 */ "temp ::=",
  101985. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  101986. /* 33 */ "create_table_args ::= AS select",
  101987. /* 34 */ "columnlist ::= columnlist COMMA column",
  101988. /* 35 */ "columnlist ::= column",
  101989. /* 36 */ "column ::= columnid type carglist",
  101990. /* 37 */ "columnid ::= nm",
  101991. /* 38 */ "id ::= ID",
  101992. /* 39 */ "id ::= INDEXED",
  101993. /* 40 */ "ids ::= ID|STRING",
  101994. /* 41 */ "nm ::= id",
  101995. /* 42 */ "nm ::= STRING",
  101996. /* 43 */ "nm ::= JOIN_KW",
  101997. /* 44 */ "type ::=",
  101998. /* 45 */ "type ::= typetoken",
  101999. /* 46 */ "typetoken ::= typename",
  102000. /* 47 */ "typetoken ::= typename LP signed RP",
  102001. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  102002. /* 49 */ "typename ::= ids",
  102003. /* 50 */ "typename ::= typename ids",
  102004. /* 51 */ "signed ::= plus_num",
  102005. /* 52 */ "signed ::= minus_num",
  102006. /* 53 */ "carglist ::= carglist ccons",
  102007. /* 54 */ "carglist ::=",
  102008. /* 55 */ "ccons ::= CONSTRAINT nm",
  102009. /* 56 */ "ccons ::= DEFAULT term",
  102010. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  102011. /* 58 */ "ccons ::= DEFAULT PLUS term",
  102012. /* 59 */ "ccons ::= DEFAULT MINUS term",
  102013. /* 60 */ "ccons ::= DEFAULT id",
  102014. /* 61 */ "ccons ::= NULL onconf",
  102015. /* 62 */ "ccons ::= NOT NULL onconf",
  102016. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  102017. /* 64 */ "ccons ::= UNIQUE onconf",
  102018. /* 65 */ "ccons ::= CHECK LP expr RP",
  102019. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  102020. /* 67 */ "ccons ::= defer_subclause",
  102021. /* 68 */ "ccons ::= COLLATE ids",
  102022. /* 69 */ "autoinc ::=",
  102023. /* 70 */ "autoinc ::= AUTOINCR",
  102024. /* 71 */ "refargs ::=",
  102025. /* 72 */ "refargs ::= refargs refarg",
  102026. /* 73 */ "refarg ::= MATCH nm",
  102027. /* 74 */ "refarg ::= ON INSERT refact",
  102028. /* 75 */ "refarg ::= ON DELETE refact",
  102029. /* 76 */ "refarg ::= ON UPDATE refact",
  102030. /* 77 */ "refact ::= SET NULL",
  102031. /* 78 */ "refact ::= SET DEFAULT",
  102032. /* 79 */ "refact ::= CASCADE",
  102033. /* 80 */ "refact ::= RESTRICT",
  102034. /* 81 */ "refact ::= NO ACTION",
  102035. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  102036. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  102037. /* 84 */ "init_deferred_pred_opt ::=",
  102038. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  102039. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  102040. /* 87 */ "conslist_opt ::=",
  102041. /* 88 */ "conslist_opt ::= COMMA conslist",
  102042. /* 89 */ "conslist ::= conslist tconscomma tcons",
  102043. /* 90 */ "conslist ::= tcons",
  102044. /* 91 */ "tconscomma ::= COMMA",
  102045. /* 92 */ "tconscomma ::=",
  102046. /* 93 */ "tcons ::= CONSTRAINT nm",
  102047. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  102048. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  102049. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  102050. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  102051. /* 98 */ "defer_subclause_opt ::=",
  102052. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  102053. /* 100 */ "onconf ::=",
  102054. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  102055. /* 102 */ "orconf ::=",
  102056. /* 103 */ "orconf ::= OR resolvetype",
  102057. /* 104 */ "resolvetype ::= raisetype",
  102058. /* 105 */ "resolvetype ::= IGNORE",
  102059. /* 106 */ "resolvetype ::= REPLACE",
  102060. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  102061. /* 108 */ "ifexists ::= IF EXISTS",
  102062. /* 109 */ "ifexists ::=",
  102063. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  102064. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  102065. /* 112 */ "cmd ::= select",
  102066. /* 113 */ "select ::= oneselect",
  102067. /* 114 */ "select ::= select multiselect_op oneselect",
  102068. /* 115 */ "multiselect_op ::= UNION",
  102069. /* 116 */ "multiselect_op ::= UNION ALL",
  102070. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  102071. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  102072. /* 119 */ "distinct ::= DISTINCT",
  102073. /* 120 */ "distinct ::= ALL",
  102074. /* 121 */ "distinct ::=",
  102075. /* 122 */ "sclp ::= selcollist COMMA",
  102076. /* 123 */ "sclp ::=",
  102077. /* 124 */ "selcollist ::= sclp expr as",
  102078. /* 125 */ "selcollist ::= sclp STAR",
  102079. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  102080. /* 127 */ "as ::= AS nm",
  102081. /* 128 */ "as ::= ids",
  102082. /* 129 */ "as ::=",
  102083. /* 130 */ "from ::=",
  102084. /* 131 */ "from ::= FROM seltablist",
  102085. /* 132 */ "stl_prefix ::= seltablist joinop",
  102086. /* 133 */ "stl_prefix ::=",
  102087. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  102088. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  102089. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  102090. /* 137 */ "dbnm ::=",
  102091. /* 138 */ "dbnm ::= DOT nm",
  102092. /* 139 */ "fullname ::= nm dbnm",
  102093. /* 140 */ "joinop ::= COMMA|JOIN",
  102094. /* 141 */ "joinop ::= JOIN_KW JOIN",
  102095. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  102096. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  102097. /* 144 */ "on_opt ::= ON expr",
  102098. /* 145 */ "on_opt ::=",
  102099. /* 146 */ "indexed_opt ::=",
  102100. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  102101. /* 148 */ "indexed_opt ::= NOT INDEXED",
  102102. /* 149 */ "using_opt ::= USING LP inscollist RP",
  102103. /* 150 */ "using_opt ::=",
  102104. /* 151 */ "orderby_opt ::=",
  102105. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  102106. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  102107. /* 154 */ "sortlist ::= expr sortorder",
  102108. /* 155 */ "sortorder ::= ASC",
  102109. /* 156 */ "sortorder ::= DESC",
  102110. /* 157 */ "sortorder ::=",
  102111. /* 158 */ "groupby_opt ::=",
  102112. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  102113. /* 160 */ "having_opt ::=",
  102114. /* 161 */ "having_opt ::= HAVING expr",
  102115. /* 162 */ "limit_opt ::=",
  102116. /* 163 */ "limit_opt ::= LIMIT expr",
  102117. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  102118. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  102119. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  102120. /* 167 */ "where_opt ::=",
  102121. /* 168 */ "where_opt ::= WHERE expr",
  102122. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  102123. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  102124. /* 171 */ "setlist ::= nm EQ expr",
  102125. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  102126. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  102127. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  102128. /* 175 */ "insert_cmd ::= INSERT orconf",
  102129. /* 176 */ "insert_cmd ::= REPLACE",
  102130. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  102131. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  102132. /* 179 */ "inscollist_opt ::=",
  102133. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  102134. /* 181 */ "inscollist ::= inscollist COMMA nm",
  102135. /* 182 */ "inscollist ::= nm",
  102136. /* 183 */ "expr ::= term",
  102137. /* 184 */ "expr ::= LP expr RP",
  102138. /* 185 */ "term ::= NULL",
  102139. /* 186 */ "expr ::= id",
  102140. /* 187 */ "expr ::= JOIN_KW",
  102141. /* 188 */ "expr ::= nm DOT nm",
  102142. /* 189 */ "expr ::= nm DOT nm DOT nm",
  102143. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  102144. /* 191 */ "term ::= STRING",
  102145. /* 192 */ "expr ::= REGISTER",
  102146. /* 193 */ "expr ::= VARIABLE",
  102147. /* 194 */ "expr ::= expr COLLATE ids",
  102148. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  102149. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  102150. /* 197 */ "expr ::= ID LP STAR RP",
  102151. /* 198 */ "term ::= CTIME_KW",
  102152. /* 199 */ "expr ::= expr AND expr",
  102153. /* 200 */ "expr ::= expr OR expr",
  102154. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  102155. /* 202 */ "expr ::= expr EQ|NE expr",
  102156. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  102157. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  102158. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  102159. /* 206 */ "expr ::= expr CONCAT expr",
  102160. /* 207 */ "likeop ::= LIKE_KW",
  102161. /* 208 */ "likeop ::= NOT LIKE_KW",
  102162. /* 209 */ "likeop ::= MATCH",
  102163. /* 210 */ "likeop ::= NOT MATCH",
  102164. /* 211 */ "expr ::= expr likeop expr",
  102165. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  102166. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  102167. /* 214 */ "expr ::= expr NOT NULL",
  102168. /* 215 */ "expr ::= expr IS expr",
  102169. /* 216 */ "expr ::= expr IS NOT expr",
  102170. /* 217 */ "expr ::= NOT expr",
  102171. /* 218 */ "expr ::= BITNOT expr",
  102172. /* 219 */ "expr ::= MINUS expr",
  102173. /* 220 */ "expr ::= PLUS expr",
  102174. /* 221 */ "between_op ::= BETWEEN",
  102175. /* 222 */ "between_op ::= NOT BETWEEN",
  102176. /* 223 */ "expr ::= expr between_op expr AND expr",
  102177. /* 224 */ "in_op ::= IN",
  102178. /* 225 */ "in_op ::= NOT IN",
  102179. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  102180. /* 227 */ "expr ::= LP select RP",
  102181. /* 228 */ "expr ::= expr in_op LP select RP",
  102182. /* 229 */ "expr ::= expr in_op nm dbnm",
  102183. /* 230 */ "expr ::= EXISTS LP select RP",
  102184. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  102185. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  102186. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  102187. /* 234 */ "case_else ::= ELSE expr",
  102188. /* 235 */ "case_else ::=",
  102189. /* 236 */ "case_operand ::= expr",
  102190. /* 237 */ "case_operand ::=",
  102191. /* 238 */ "exprlist ::= nexprlist",
  102192. /* 239 */ "exprlist ::=",
  102193. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  102194. /* 241 */ "nexprlist ::= expr",
  102195. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
  102196. /* 243 */ "uniqueflag ::= UNIQUE",
  102197. /* 244 */ "uniqueflag ::=",
  102198. /* 245 */ "idxlist_opt ::=",
  102199. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  102200. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  102201. /* 248 */ "idxlist ::= nm collate sortorder",
  102202. /* 249 */ "collate ::=",
  102203. /* 250 */ "collate ::= COLLATE ids",
  102204. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  102205. /* 252 */ "cmd ::= VACUUM",
  102206. /* 253 */ "cmd ::= VACUUM nm",
  102207. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  102208. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  102209. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  102210. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  102211. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  102212. /* 259 */ "nmnum ::= plus_num",
  102213. /* 260 */ "nmnum ::= nm",
  102214. /* 261 */ "nmnum ::= ON",
  102215. /* 262 */ "nmnum ::= DELETE",
  102216. /* 263 */ "nmnum ::= DEFAULT",
  102217. /* 264 */ "plus_num ::= PLUS number",
  102218. /* 265 */ "plus_num ::= number",
  102219. /* 266 */ "minus_num ::= MINUS number",
  102220. /* 267 */ "number ::= INTEGER|FLOAT",
  102221. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  102222. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  102223. /* 270 */ "trigger_time ::= BEFORE",
  102224. /* 271 */ "trigger_time ::= AFTER",
  102225. /* 272 */ "trigger_time ::= INSTEAD OF",
  102226. /* 273 */ "trigger_time ::=",
  102227. /* 274 */ "trigger_event ::= DELETE|INSERT",
  102228. /* 275 */ "trigger_event ::= UPDATE",
  102229. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  102230. /* 277 */ "foreach_clause ::=",
  102231. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  102232. /* 279 */ "when_clause ::=",
  102233. /* 280 */ "when_clause ::= WHEN expr",
  102234. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  102235. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  102236. /* 283 */ "trnm ::= nm",
  102237. /* 284 */ "trnm ::= nm DOT nm",
  102238. /* 285 */ "tridxby ::=",
  102239. /* 286 */ "tridxby ::= INDEXED BY nm",
  102240. /* 287 */ "tridxby ::= NOT INDEXED",
  102241. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  102242. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  102243. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  102244. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  102245. /* 292 */ "trigger_cmd ::= select",
  102246. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  102247. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  102248. /* 295 */ "raisetype ::= ROLLBACK",
  102249. /* 296 */ "raisetype ::= ABORT",
  102250. /* 297 */ "raisetype ::= FAIL",
  102251. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  102252. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  102253. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  102254. /* 301 */ "key_opt ::=",
  102255. /* 302 */ "key_opt ::= KEY expr",
  102256. /* 303 */ "database_kw_opt ::= DATABASE",
  102257. /* 304 */ "database_kw_opt ::=",
  102258. /* 305 */ "cmd ::= REINDEX",
  102259. /* 306 */ "cmd ::= REINDEX nm dbnm",
  102260. /* 307 */ "cmd ::= ANALYZE",
  102261. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  102262. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  102263. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  102264. /* 311 */ "add_column_fullname ::= fullname",
  102265. /* 312 */ "kwcolumn_opt ::=",
  102266. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  102267. /* 314 */ "cmd ::= create_vtab",
  102268. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  102269. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  102270. /* 317 */ "vtabarglist ::= vtabarg",
  102271. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  102272. /* 319 */ "vtabarg ::=",
  102273. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  102274. /* 321 */ "vtabargtoken ::= ANY",
  102275. /* 322 */ "vtabargtoken ::= lp anylist RP",
  102276. /* 323 */ "lp ::= LP",
  102277. /* 324 */ "anylist ::=",
  102278. /* 325 */ "anylist ::= anylist LP anylist RP",
  102279. /* 326 */ "anylist ::= anylist ANY",
  102280. };
  102281. #endif /* NDEBUG */
  102282. #if YYSTACKDEPTH<=0
  102283. /*
  102284. ** Try to increase the size of the parser stack.
  102285. */
  102286. static void yyGrowStack(yyParser *p){
  102287. int newSize;
  102288. yyStackEntry *pNew;
  102289. newSize = p->yystksz*2 + 100;
  102290. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  102291. if( pNew ){
  102292. p->yystack = pNew;
  102293. p->yystksz = newSize;
  102294. #ifndef NDEBUG
  102295. if( yyTraceFILE ){
  102296. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  102297. yyTracePrompt, p->yystksz);
  102298. }
  102299. #endif
  102300. }
  102301. }
  102302. #endif
  102303. /*
  102304. ** This function allocates a new parser.
  102305. ** The only argument is a pointer to a function which works like
  102306. ** malloc.
  102307. **
  102308. ** Inputs:
  102309. ** A pointer to the function used to allocate memory.
  102310. **
  102311. ** Outputs:
  102312. ** A pointer to a parser. This pointer is used in subsequent calls
  102313. ** to sqlite3Parser and sqlite3ParserFree.
  102314. */
  102315. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  102316. yyParser *pParser;
  102317. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  102318. if( pParser ){
  102319. pParser->yyidx = -1;
  102320. #ifdef YYTRACKMAXSTACKDEPTH
  102321. pParser->yyidxMax = 0;
  102322. #endif
  102323. #if YYSTACKDEPTH<=0
  102324. pParser->yystack = NULL;
  102325. pParser->yystksz = 0;
  102326. yyGrowStack(pParser);
  102327. #endif
  102328. }
  102329. return pParser;
  102330. }
  102331. /* The following function deletes the value associated with a
  102332. ** symbol. The symbol can be either a terminal or nonterminal.
  102333. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  102334. ** the value.
  102335. */
  102336. static void yy_destructor(
  102337. yyParser *yypParser, /* The parser */
  102338. YYCODETYPE yymajor, /* Type code for object to destroy */
  102339. YYMINORTYPE *yypminor /* The object to be destroyed */
  102340. ){
  102341. sqlite3ParserARG_FETCH;
  102342. switch( yymajor ){
  102343. /* Here is inserted the actions which take place when a
  102344. ** terminal or non-terminal is destroyed. This can happen
  102345. ** when the symbol is popped from the stack during a
  102346. ** reduce or during error processing or when a parser is
  102347. ** being destroyed before it is finished parsing.
  102348. **
  102349. ** Note: during a reduce, the only symbols destroyed are those
  102350. ** which appear on the RHS of the rule, but which are not used
  102351. ** inside the C code.
  102352. */
  102353. case 160: /* select */
  102354. case 194: /* oneselect */
  102355. {
  102356. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  102357. }
  102358. break;
  102359. case 173: /* term */
  102360. case 174: /* expr */
  102361. {
  102362. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  102363. }
  102364. break;
  102365. case 178: /* idxlist_opt */
  102366. case 187: /* idxlist */
  102367. case 197: /* selcollist */
  102368. case 200: /* groupby_opt */
  102369. case 202: /* orderby_opt */
  102370. case 204: /* sclp */
  102371. case 214: /* sortlist */
  102372. case 215: /* nexprlist */
  102373. case 216: /* setlist */
  102374. case 220: /* exprlist */
  102375. case 225: /* case_exprlist */
  102376. {
  102377. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  102378. }
  102379. break;
  102380. case 193: /* fullname */
  102381. case 198: /* from */
  102382. case 206: /* seltablist */
  102383. case 207: /* stl_prefix */
  102384. {
  102385. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  102386. }
  102387. break;
  102388. case 199: /* where_opt */
  102389. case 201: /* having_opt */
  102390. case 210: /* on_opt */
  102391. case 224: /* case_operand */
  102392. case 226: /* case_else */
  102393. case 236: /* when_clause */
  102394. case 241: /* key_opt */
  102395. {
  102396. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  102397. }
  102398. break;
  102399. case 211: /* using_opt */
  102400. case 213: /* inscollist */
  102401. case 218: /* inscollist_opt */
  102402. {
  102403. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  102404. }
  102405. break;
  102406. case 219: /* valuelist */
  102407. {
  102408. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  102409. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  102410. }
  102411. break;
  102412. case 232: /* trigger_cmd_list */
  102413. case 237: /* trigger_cmd */
  102414. {
  102415. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  102416. }
  102417. break;
  102418. case 234: /* trigger_event */
  102419. {
  102420. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  102421. }
  102422. break;
  102423. default: break; /* If no destructor action specified: do nothing */
  102424. }
  102425. }
  102426. /*
  102427. ** Pop the parser's stack once.
  102428. **
  102429. ** If there is a destructor routine associated with the token which
  102430. ** is popped from the stack, then call it.
  102431. **
  102432. ** Return the major token number for the symbol popped.
  102433. */
  102434. static int yy_pop_parser_stack(yyParser *pParser){
  102435. YYCODETYPE yymajor;
  102436. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  102437. /* There is no mechanism by which the parser stack can be popped below
  102438. ** empty in SQLite. */
  102439. if( NEVER(pParser->yyidx<0) ) return 0;
  102440. #ifndef NDEBUG
  102441. if( yyTraceFILE && pParser->yyidx>=0 ){
  102442. fprintf(yyTraceFILE,"%sPopping %s\n",
  102443. yyTracePrompt,
  102444. yyTokenName[yytos->major]);
  102445. }
  102446. #endif
  102447. yymajor = yytos->major;
  102448. yy_destructor(pParser, yymajor, &yytos->minor);
  102449. pParser->yyidx--;
  102450. return yymajor;
  102451. }
  102452. /*
  102453. ** Deallocate and destroy a parser. Destructors are all called for
  102454. ** all stack elements before shutting the parser down.
  102455. **
  102456. ** Inputs:
  102457. ** <ul>
  102458. ** <li> A pointer to the parser. This should be a pointer
  102459. ** obtained from sqlite3ParserAlloc.
  102460. ** <li> A pointer to a function used to reclaim memory obtained
  102461. ** from malloc.
  102462. ** </ul>
  102463. */
  102464. SQLITE_PRIVATE void sqlite3ParserFree(
  102465. void *p, /* The parser to be deleted */
  102466. void (*freeProc)(void*) /* Function used to reclaim memory */
  102467. ){
  102468. yyParser *pParser = (yyParser*)p;
  102469. /* In SQLite, we never try to destroy a parser that was not successfully
  102470. ** created in the first place. */
  102471. if( NEVER(pParser==0) ) return;
  102472. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  102473. #if YYSTACKDEPTH<=0
  102474. free(pParser->yystack);
  102475. #endif
  102476. (*freeProc)((void*)pParser);
  102477. }
  102478. /*
  102479. ** Return the peak depth of the stack for a parser.
  102480. */
  102481. #ifdef YYTRACKMAXSTACKDEPTH
  102482. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  102483. yyParser *pParser = (yyParser*)p;
  102484. return pParser->yyidxMax;
  102485. }
  102486. #endif
  102487. /*
  102488. ** Find the appropriate action for a parser given the terminal
  102489. ** look-ahead token iLookAhead.
  102490. **
  102491. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  102492. ** independent of the look-ahead. If it is, return the action, otherwise
  102493. ** return YY_NO_ACTION.
  102494. */
  102495. static int yy_find_shift_action(
  102496. yyParser *pParser, /* The parser */
  102497. YYCODETYPE iLookAhead /* The look-ahead token */
  102498. ){
  102499. int i;
  102500. int stateno = pParser->yystack[pParser->yyidx].stateno;
  102501. if( stateno>YY_SHIFT_COUNT
  102502. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  102503. return yy_default[stateno];
  102504. }
  102505. assert( iLookAhead!=YYNOCODE );
  102506. i += iLookAhead;
  102507. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  102508. if( iLookAhead>0 ){
  102509. #ifdef YYFALLBACK
  102510. YYCODETYPE iFallback; /* Fallback token */
  102511. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  102512. && (iFallback = yyFallback[iLookAhead])!=0 ){
  102513. #ifndef NDEBUG
  102514. if( yyTraceFILE ){
  102515. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  102516. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  102517. }
  102518. #endif
  102519. return yy_find_shift_action(pParser, iFallback);
  102520. }
  102521. #endif
  102522. #ifdef YYWILDCARD
  102523. {
  102524. int j = i - iLookAhead + YYWILDCARD;
  102525. if(
  102526. #if YY_SHIFT_MIN+YYWILDCARD<0
  102527. j>=0 &&
  102528. #endif
  102529. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  102530. j<YY_ACTTAB_COUNT &&
  102531. #endif
  102532. yy_lookahead[j]==YYWILDCARD
  102533. ){
  102534. #ifndef NDEBUG
  102535. if( yyTraceFILE ){
  102536. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  102537. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  102538. }
  102539. #endif /* NDEBUG */
  102540. return yy_action[j];
  102541. }
  102542. }
  102543. #endif /* YYWILDCARD */
  102544. }
  102545. return yy_default[stateno];
  102546. }else{
  102547. return yy_action[i];
  102548. }
  102549. }
  102550. /*
  102551. ** Find the appropriate action for a parser given the non-terminal
  102552. ** look-ahead token iLookAhead.
  102553. **
  102554. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  102555. ** independent of the look-ahead. If it is, return the action, otherwise
  102556. ** return YY_NO_ACTION.
  102557. */
  102558. static int yy_find_reduce_action(
  102559. int stateno, /* Current state number */
  102560. YYCODETYPE iLookAhead /* The look-ahead token */
  102561. ){
  102562. int i;
  102563. #ifdef YYERRORSYMBOL
  102564. if( stateno>YY_REDUCE_COUNT ){
  102565. return yy_default[stateno];
  102566. }
  102567. #else
  102568. assert( stateno<=YY_REDUCE_COUNT );
  102569. #endif
  102570. i = yy_reduce_ofst[stateno];
  102571. assert( i!=YY_REDUCE_USE_DFLT );
  102572. assert( iLookAhead!=YYNOCODE );
  102573. i += iLookAhead;
  102574. #ifdef YYERRORSYMBOL
  102575. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  102576. return yy_default[stateno];
  102577. }
  102578. #else
  102579. assert( i>=0 && i<YY_ACTTAB_COUNT );
  102580. assert( yy_lookahead[i]==iLookAhead );
  102581. #endif
  102582. return yy_action[i];
  102583. }
  102584. /*
  102585. ** The following routine is called if the stack overflows.
  102586. */
  102587. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  102588. sqlite3ParserARG_FETCH;
  102589. yypParser->yyidx--;
  102590. #ifndef NDEBUG
  102591. if( yyTraceFILE ){
  102592. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  102593. }
  102594. #endif
  102595. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  102596. /* Here code is inserted which will execute if the parser
  102597. ** stack every overflows */
  102598. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  102599. sqlite3ErrorMsg(pParse, "parser stack overflow");
  102600. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  102601. }
  102602. /*
  102603. ** Perform a shift action.
  102604. */
  102605. static void yy_shift(
  102606. yyParser *yypParser, /* The parser to be shifted */
  102607. int yyNewState, /* The new state to shift in */
  102608. int yyMajor, /* The major token to shift in */
  102609. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  102610. ){
  102611. yyStackEntry *yytos;
  102612. yypParser->yyidx++;
  102613. #ifdef YYTRACKMAXSTACKDEPTH
  102614. if( yypParser->yyidx>yypParser->yyidxMax ){
  102615. yypParser->yyidxMax = yypParser->yyidx;
  102616. }
  102617. #endif
  102618. #if YYSTACKDEPTH>0
  102619. if( yypParser->yyidx>=YYSTACKDEPTH ){
  102620. yyStackOverflow(yypParser, yypMinor);
  102621. return;
  102622. }
  102623. #else
  102624. if( yypParser->yyidx>=yypParser->yystksz ){
  102625. yyGrowStack(yypParser);
  102626. if( yypParser->yyidx>=yypParser->yystksz ){
  102627. yyStackOverflow(yypParser, yypMinor);
  102628. return;
  102629. }
  102630. }
  102631. #endif
  102632. yytos = &yypParser->yystack[yypParser->yyidx];
  102633. yytos->stateno = (YYACTIONTYPE)yyNewState;
  102634. yytos->major = (YYCODETYPE)yyMajor;
  102635. yytos->minor = *yypMinor;
  102636. #ifndef NDEBUG
  102637. if( yyTraceFILE && yypParser->yyidx>0 ){
  102638. int i;
  102639. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  102640. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  102641. for(i=1; i<=yypParser->yyidx; i++)
  102642. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  102643. fprintf(yyTraceFILE,"\n");
  102644. }
  102645. #endif
  102646. }
  102647. /* The following table contains information about every rule that
  102648. ** is used during the reduce.
  102649. */
  102650. static const struct {
  102651. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  102652. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  102653. } yyRuleInfo[] = {
  102654. { 142, 1 },
  102655. { 143, 2 },
  102656. { 143, 1 },
  102657. { 144, 1 },
  102658. { 144, 3 },
  102659. { 145, 0 },
  102660. { 145, 1 },
  102661. { 145, 3 },
  102662. { 146, 1 },
  102663. { 147, 3 },
  102664. { 149, 0 },
  102665. { 149, 1 },
  102666. { 149, 2 },
  102667. { 148, 0 },
  102668. { 148, 1 },
  102669. { 148, 1 },
  102670. { 148, 1 },
  102671. { 147, 2 },
  102672. { 147, 2 },
  102673. { 147, 2 },
  102674. { 151, 1 },
  102675. { 151, 0 },
  102676. { 147, 2 },
  102677. { 147, 3 },
  102678. { 147, 5 },
  102679. { 147, 2 },
  102680. { 152, 6 },
  102681. { 154, 1 },
  102682. { 156, 0 },
  102683. { 156, 3 },
  102684. { 155, 1 },
  102685. { 155, 0 },
  102686. { 153, 4 },
  102687. { 153, 2 },
  102688. { 158, 3 },
  102689. { 158, 1 },
  102690. { 161, 3 },
  102691. { 162, 1 },
  102692. { 165, 1 },
  102693. { 165, 1 },
  102694. { 166, 1 },
  102695. { 150, 1 },
  102696. { 150, 1 },
  102697. { 150, 1 },
  102698. { 163, 0 },
  102699. { 163, 1 },
  102700. { 167, 1 },
  102701. { 167, 4 },
  102702. { 167, 6 },
  102703. { 168, 1 },
  102704. { 168, 2 },
  102705. { 169, 1 },
  102706. { 169, 1 },
  102707. { 164, 2 },
  102708. { 164, 0 },
  102709. { 172, 2 },
  102710. { 172, 2 },
  102711. { 172, 4 },
  102712. { 172, 3 },
  102713. { 172, 3 },
  102714. { 172, 2 },
  102715. { 172, 2 },
  102716. { 172, 3 },
  102717. { 172, 5 },
  102718. { 172, 2 },
  102719. { 172, 4 },
  102720. { 172, 4 },
  102721. { 172, 1 },
  102722. { 172, 2 },
  102723. { 177, 0 },
  102724. { 177, 1 },
  102725. { 179, 0 },
  102726. { 179, 2 },
  102727. { 181, 2 },
  102728. { 181, 3 },
  102729. { 181, 3 },
  102730. { 181, 3 },
  102731. { 182, 2 },
  102732. { 182, 2 },
  102733. { 182, 1 },
  102734. { 182, 1 },
  102735. { 182, 2 },
  102736. { 180, 3 },
  102737. { 180, 2 },
  102738. { 183, 0 },
  102739. { 183, 2 },
  102740. { 183, 2 },
  102741. { 159, 0 },
  102742. { 159, 2 },
  102743. { 184, 3 },
  102744. { 184, 1 },
  102745. { 185, 1 },
  102746. { 185, 0 },
  102747. { 186, 2 },
  102748. { 186, 7 },
  102749. { 186, 5 },
  102750. { 186, 5 },
  102751. { 186, 10 },
  102752. { 188, 0 },
  102753. { 188, 1 },
  102754. { 175, 0 },
  102755. { 175, 3 },
  102756. { 189, 0 },
  102757. { 189, 2 },
  102758. { 190, 1 },
  102759. { 190, 1 },
  102760. { 190, 1 },
  102761. { 147, 4 },
  102762. { 192, 2 },
  102763. { 192, 0 },
  102764. { 147, 8 },
  102765. { 147, 4 },
  102766. { 147, 1 },
  102767. { 160, 1 },
  102768. { 160, 3 },
  102769. { 195, 1 },
  102770. { 195, 2 },
  102771. { 195, 1 },
  102772. { 194, 9 },
  102773. { 196, 1 },
  102774. { 196, 1 },
  102775. { 196, 0 },
  102776. { 204, 2 },
  102777. { 204, 0 },
  102778. { 197, 3 },
  102779. { 197, 2 },
  102780. { 197, 4 },
  102781. { 205, 2 },
  102782. { 205, 1 },
  102783. { 205, 0 },
  102784. { 198, 0 },
  102785. { 198, 2 },
  102786. { 207, 2 },
  102787. { 207, 0 },
  102788. { 206, 7 },
  102789. { 206, 7 },
  102790. { 206, 7 },
  102791. { 157, 0 },
  102792. { 157, 2 },
  102793. { 193, 2 },
  102794. { 208, 1 },
  102795. { 208, 2 },
  102796. { 208, 3 },
  102797. { 208, 4 },
  102798. { 210, 2 },
  102799. { 210, 0 },
  102800. { 209, 0 },
  102801. { 209, 3 },
  102802. { 209, 2 },
  102803. { 211, 4 },
  102804. { 211, 0 },
  102805. { 202, 0 },
  102806. { 202, 3 },
  102807. { 214, 4 },
  102808. { 214, 2 },
  102809. { 176, 1 },
  102810. { 176, 1 },
  102811. { 176, 0 },
  102812. { 200, 0 },
  102813. { 200, 3 },
  102814. { 201, 0 },
  102815. { 201, 2 },
  102816. { 203, 0 },
  102817. { 203, 2 },
  102818. { 203, 4 },
  102819. { 203, 4 },
  102820. { 147, 5 },
  102821. { 199, 0 },
  102822. { 199, 2 },
  102823. { 147, 7 },
  102824. { 216, 5 },
  102825. { 216, 3 },
  102826. { 147, 5 },
  102827. { 147, 5 },
  102828. { 147, 6 },
  102829. { 217, 2 },
  102830. { 217, 1 },
  102831. { 219, 4 },
  102832. { 219, 5 },
  102833. { 218, 0 },
  102834. { 218, 3 },
  102835. { 213, 3 },
  102836. { 213, 1 },
  102837. { 174, 1 },
  102838. { 174, 3 },
  102839. { 173, 1 },
  102840. { 174, 1 },
  102841. { 174, 1 },
  102842. { 174, 3 },
  102843. { 174, 5 },
  102844. { 173, 1 },
  102845. { 173, 1 },
  102846. { 174, 1 },
  102847. { 174, 1 },
  102848. { 174, 3 },
  102849. { 174, 6 },
  102850. { 174, 5 },
  102851. { 174, 4 },
  102852. { 173, 1 },
  102853. { 174, 3 },
  102854. { 174, 3 },
  102855. { 174, 3 },
  102856. { 174, 3 },
  102857. { 174, 3 },
  102858. { 174, 3 },
  102859. { 174, 3 },
  102860. { 174, 3 },
  102861. { 221, 1 },
  102862. { 221, 2 },
  102863. { 221, 1 },
  102864. { 221, 2 },
  102865. { 174, 3 },
  102866. { 174, 5 },
  102867. { 174, 2 },
  102868. { 174, 3 },
  102869. { 174, 3 },
  102870. { 174, 4 },
  102871. { 174, 2 },
  102872. { 174, 2 },
  102873. { 174, 2 },
  102874. { 174, 2 },
  102875. { 222, 1 },
  102876. { 222, 2 },
  102877. { 174, 5 },
  102878. { 223, 1 },
  102879. { 223, 2 },
  102880. { 174, 5 },
  102881. { 174, 3 },
  102882. { 174, 5 },
  102883. { 174, 4 },
  102884. { 174, 4 },
  102885. { 174, 5 },
  102886. { 225, 5 },
  102887. { 225, 4 },
  102888. { 226, 2 },
  102889. { 226, 0 },
  102890. { 224, 1 },
  102891. { 224, 0 },
  102892. { 220, 1 },
  102893. { 220, 0 },
  102894. { 215, 3 },
  102895. { 215, 1 },
  102896. { 147, 11 },
  102897. { 227, 1 },
  102898. { 227, 0 },
  102899. { 178, 0 },
  102900. { 178, 3 },
  102901. { 187, 5 },
  102902. { 187, 3 },
  102903. { 228, 0 },
  102904. { 228, 2 },
  102905. { 147, 4 },
  102906. { 147, 1 },
  102907. { 147, 2 },
  102908. { 147, 3 },
  102909. { 147, 5 },
  102910. { 147, 6 },
  102911. { 147, 5 },
  102912. { 147, 6 },
  102913. { 229, 1 },
  102914. { 229, 1 },
  102915. { 229, 1 },
  102916. { 229, 1 },
  102917. { 229, 1 },
  102918. { 170, 2 },
  102919. { 170, 1 },
  102920. { 171, 2 },
  102921. { 230, 1 },
  102922. { 147, 5 },
  102923. { 231, 11 },
  102924. { 233, 1 },
  102925. { 233, 1 },
  102926. { 233, 2 },
  102927. { 233, 0 },
  102928. { 234, 1 },
  102929. { 234, 1 },
  102930. { 234, 3 },
  102931. { 235, 0 },
  102932. { 235, 3 },
  102933. { 236, 0 },
  102934. { 236, 2 },
  102935. { 232, 3 },
  102936. { 232, 2 },
  102937. { 238, 1 },
  102938. { 238, 3 },
  102939. { 239, 0 },
  102940. { 239, 3 },
  102941. { 239, 2 },
  102942. { 237, 7 },
  102943. { 237, 5 },
  102944. { 237, 5 },
  102945. { 237, 5 },
  102946. { 237, 1 },
  102947. { 174, 4 },
  102948. { 174, 6 },
  102949. { 191, 1 },
  102950. { 191, 1 },
  102951. { 191, 1 },
  102952. { 147, 4 },
  102953. { 147, 6 },
  102954. { 147, 3 },
  102955. { 241, 0 },
  102956. { 241, 2 },
  102957. { 240, 1 },
  102958. { 240, 0 },
  102959. { 147, 1 },
  102960. { 147, 3 },
  102961. { 147, 1 },
  102962. { 147, 3 },
  102963. { 147, 6 },
  102964. { 147, 6 },
  102965. { 242, 1 },
  102966. { 243, 0 },
  102967. { 243, 1 },
  102968. { 147, 1 },
  102969. { 147, 4 },
  102970. { 244, 8 },
  102971. { 245, 1 },
  102972. { 245, 3 },
  102973. { 246, 0 },
  102974. { 246, 2 },
  102975. { 247, 1 },
  102976. { 247, 3 },
  102977. { 248, 1 },
  102978. { 249, 0 },
  102979. { 249, 4 },
  102980. { 249, 2 },
  102981. };
  102982. static void yy_accept(yyParser*); /* Forward Declaration */
  102983. /*
  102984. ** Perform a reduce action and the shift that must immediately
  102985. ** follow the reduce.
  102986. */
  102987. static void yy_reduce(
  102988. yyParser *yypParser, /* The parser */
  102989. int yyruleno /* Number of the rule by which to reduce */
  102990. ){
  102991. int yygoto; /* The next state */
  102992. int yyact; /* The next action */
  102993. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  102994. yyStackEntry *yymsp; /* The top of the parser's stack */
  102995. int yysize; /* Amount to pop the stack */
  102996. sqlite3ParserARG_FETCH;
  102997. yymsp = &yypParser->yystack[yypParser->yyidx];
  102998. #ifndef NDEBUG
  102999. if( yyTraceFILE && yyruleno>=0
  103000. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  103001. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  103002. yyRuleName[yyruleno]);
  103003. }
  103004. #endif /* NDEBUG */
  103005. /* Silence complaints from purify about yygotominor being uninitialized
  103006. ** in some cases when it is copied into the stack after the following
  103007. ** switch. yygotominor is uninitialized when a rule reduces that does
  103008. ** not set the value of its left-hand side nonterminal. Leaving the
  103009. ** value of the nonterminal uninitialized is utterly harmless as long
  103010. ** as the value is never used. So really the only thing this code
  103011. ** accomplishes is to quieten purify.
  103012. **
  103013. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  103014. ** without this code, their parser segfaults. I'm not sure what there
  103015. ** parser is doing to make this happen. This is the second bug report
  103016. ** from wireshark this week. Clearly they are stressing Lemon in ways
  103017. ** that it has not been previously stressed... (SQLite ticket #2172)
  103018. */
  103019. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  103020. yygotominor = yyzerominor;
  103021. switch( yyruleno ){
  103022. /* Beginning here are the reduction cases. A typical example
  103023. ** follows:
  103024. ** case 0:
  103025. ** #line <lineno> <grammarfile>
  103026. ** { ... } // User supplied code
  103027. ** #line <lineno> <thisfile>
  103028. ** break;
  103029. */
  103030. case 5: /* explain ::= */
  103031. { sqlite3BeginParse(pParse, 0); }
  103032. break;
  103033. case 6: /* explain ::= EXPLAIN */
  103034. { sqlite3BeginParse(pParse, 1); }
  103035. break;
  103036. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  103037. { sqlite3BeginParse(pParse, 2); }
  103038. break;
  103039. case 8: /* cmdx ::= cmd */
  103040. { sqlite3FinishCoding(pParse); }
  103041. break;
  103042. case 9: /* cmd ::= BEGIN transtype trans_opt */
  103043. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  103044. break;
  103045. case 13: /* transtype ::= */
  103046. {yygotominor.yy392 = TK_DEFERRED;}
  103047. break;
  103048. case 14: /* transtype ::= DEFERRED */
  103049. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  103050. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  103051. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  103052. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  103053. {yygotominor.yy392 = yymsp[0].major;}
  103054. break;
  103055. case 17: /* cmd ::= COMMIT trans_opt */
  103056. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  103057. {sqlite3CommitTransaction(pParse);}
  103058. break;
  103059. case 19: /* cmd ::= ROLLBACK trans_opt */
  103060. {sqlite3RollbackTransaction(pParse);}
  103061. break;
  103062. case 22: /* cmd ::= SAVEPOINT nm */
  103063. {
  103064. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  103065. }
  103066. break;
  103067. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  103068. {
  103069. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  103070. }
  103071. break;
  103072. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  103073. {
  103074. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  103075. }
  103076. break;
  103077. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  103078. {
  103079. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  103080. }
  103081. break;
  103082. case 27: /* createkw ::= CREATE */
  103083. {
  103084. pParse->db->lookaside.bEnabled = 0;
  103085. yygotominor.yy0 = yymsp[0].minor.yy0;
  103086. }
  103087. break;
  103088. case 28: /* ifnotexists ::= */
  103089. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  103090. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  103091. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  103092. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  103093. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  103094. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  103095. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  103096. case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
  103097. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  103098. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  103099. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  103100. {yygotominor.yy392 = 0;}
  103101. break;
  103102. case 29: /* ifnotexists ::= IF NOT EXISTS */
  103103. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  103104. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  103105. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  103106. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  103107. case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
  103108. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  103109. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  103110. {yygotominor.yy392 = 1;}
  103111. break;
  103112. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  103113. {
  103114. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  103115. }
  103116. break;
  103117. case 33: /* create_table_args ::= AS select */
  103118. {
  103119. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  103120. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  103121. }
  103122. break;
  103123. case 36: /* column ::= columnid type carglist */
  103124. {
  103125. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  103126. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  103127. }
  103128. break;
  103129. case 37: /* columnid ::= nm */
  103130. {
  103131. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  103132. yygotominor.yy0 = yymsp[0].minor.yy0;
  103133. pParse->constraintName.n = 0;
  103134. }
  103135. break;
  103136. case 38: /* id ::= ID */
  103137. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  103138. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  103139. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  103140. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  103141. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  103142. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  103143. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  103144. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  103145. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  103146. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  103147. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  103148. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  103149. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  103150. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  103151. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  103152. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  103153. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  103154. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  103155. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  103156. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  103157. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  103158. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  103159. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  103160. break;
  103161. case 45: /* type ::= typetoken */
  103162. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  103163. break;
  103164. case 47: /* typetoken ::= typename LP signed RP */
  103165. {
  103166. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  103167. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  103168. }
  103169. break;
  103170. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  103171. {
  103172. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  103173. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  103174. }
  103175. break;
  103176. case 50: /* typename ::= typename ids */
  103177. {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);}
  103178. break;
  103179. case 55: /* ccons ::= CONSTRAINT nm */
  103180. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  103181. {pParse->constraintName = yymsp[0].minor.yy0;}
  103182. break;
  103183. case 56: /* ccons ::= DEFAULT term */
  103184. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  103185. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  103186. break;
  103187. case 57: /* ccons ::= DEFAULT LP expr RP */
  103188. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  103189. break;
  103190. case 59: /* ccons ::= DEFAULT MINUS term */
  103191. {
  103192. ExprSpan v;
  103193. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  103194. v.zStart = yymsp[-1].minor.yy0.z;
  103195. v.zEnd = yymsp[0].minor.yy342.zEnd;
  103196. sqlite3AddDefaultValue(pParse,&v);
  103197. }
  103198. break;
  103199. case 60: /* ccons ::= DEFAULT id */
  103200. {
  103201. ExprSpan v;
  103202. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  103203. sqlite3AddDefaultValue(pParse,&v);
  103204. }
  103205. break;
  103206. case 62: /* ccons ::= NOT NULL onconf */
  103207. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  103208. break;
  103209. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  103210. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  103211. break;
  103212. case 64: /* ccons ::= UNIQUE onconf */
  103213. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  103214. break;
  103215. case 65: /* ccons ::= CHECK LP expr RP */
  103216. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  103217. break;
  103218. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  103219. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  103220. break;
  103221. case 67: /* ccons ::= defer_subclause */
  103222. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  103223. break;
  103224. case 68: /* ccons ::= COLLATE ids */
  103225. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  103226. break;
  103227. case 71: /* refargs ::= */
  103228. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  103229. break;
  103230. case 72: /* refargs ::= refargs refarg */
  103231. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  103232. break;
  103233. case 73: /* refarg ::= MATCH nm */
  103234. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  103235. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  103236. break;
  103237. case 75: /* refarg ::= ON DELETE refact */
  103238. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  103239. break;
  103240. case 76: /* refarg ::= ON UPDATE refact */
  103241. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  103242. break;
  103243. case 77: /* refact ::= SET NULL */
  103244. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  103245. break;
  103246. case 78: /* refact ::= SET DEFAULT */
  103247. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  103248. break;
  103249. case 79: /* refact ::= CASCADE */
  103250. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  103251. break;
  103252. case 80: /* refact ::= RESTRICT */
  103253. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  103254. break;
  103255. case 81: /* refact ::= NO ACTION */
  103256. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  103257. break;
  103258. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  103259. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  103260. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  103261. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  103262. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  103263. break;
  103264. case 87: /* conslist_opt ::= */
  103265. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  103266. break;
  103267. case 88: /* conslist_opt ::= COMMA conslist */
  103268. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  103269. break;
  103270. case 91: /* tconscomma ::= COMMA */
  103271. {pParse->constraintName.n = 0;}
  103272. break;
  103273. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  103274. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  103275. break;
  103276. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  103277. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  103278. break;
  103279. case 96: /* tcons ::= CHECK LP expr RP onconf */
  103280. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  103281. break;
  103282. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  103283. {
  103284. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  103285. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  103286. }
  103287. break;
  103288. case 100: /* onconf ::= */
  103289. {yygotominor.yy392 = OE_Default;}
  103290. break;
  103291. case 102: /* orconf ::= */
  103292. {yygotominor.yy258 = OE_Default;}
  103293. break;
  103294. case 103: /* orconf ::= OR resolvetype */
  103295. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  103296. break;
  103297. case 105: /* resolvetype ::= IGNORE */
  103298. {yygotominor.yy392 = OE_Ignore;}
  103299. break;
  103300. case 106: /* resolvetype ::= REPLACE */
  103301. {yygotominor.yy392 = OE_Replace;}
  103302. break;
  103303. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  103304. {
  103305. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  103306. }
  103307. break;
  103308. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  103309. {
  103310. 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);
  103311. }
  103312. break;
  103313. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  103314. {
  103315. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  103316. }
  103317. break;
  103318. case 112: /* cmd ::= select */
  103319. {
  103320. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  103321. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  103322. sqlite3ExplainBegin(pParse->pVdbe);
  103323. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  103324. sqlite3ExplainFinish(pParse->pVdbe);
  103325. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  103326. }
  103327. break;
  103328. case 113: /* select ::= oneselect */
  103329. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  103330. break;
  103331. case 114: /* select ::= select multiselect_op oneselect */
  103332. {
  103333. if( yymsp[0].minor.yy159 ){
  103334. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  103335. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  103336. }else{
  103337. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  103338. }
  103339. yygotominor.yy159 = yymsp[0].minor.yy159;
  103340. }
  103341. break;
  103342. case 116: /* multiselect_op ::= UNION ALL */
  103343. {yygotominor.yy392 = TK_ALL;}
  103344. break;
  103345. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  103346. {
  103347. 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.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  103348. }
  103349. break;
  103350. case 122: /* sclp ::= selcollist COMMA */
  103351. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  103352. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  103353. break;
  103354. case 123: /* sclp ::= */
  103355. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  103356. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  103357. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  103358. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  103359. {yygotominor.yy442 = 0;}
  103360. break;
  103361. case 124: /* selcollist ::= sclp expr as */
  103362. {
  103363. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  103364. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  103365. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  103366. }
  103367. break;
  103368. case 125: /* selcollist ::= sclp STAR */
  103369. {
  103370. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  103371. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  103372. }
  103373. break;
  103374. case 126: /* selcollist ::= sclp nm DOT STAR */
  103375. {
  103376. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  103377. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  103378. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  103379. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  103380. }
  103381. break;
  103382. case 129: /* as ::= */
  103383. {yygotominor.yy0.n = 0;}
  103384. break;
  103385. case 130: /* from ::= */
  103386. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  103387. break;
  103388. case 131: /* from ::= FROM seltablist */
  103389. {
  103390. yygotominor.yy347 = yymsp[0].minor.yy347;
  103391. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  103392. }
  103393. break;
  103394. case 132: /* stl_prefix ::= seltablist joinop */
  103395. {
  103396. yygotominor.yy347 = yymsp[-1].minor.yy347;
  103397. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  103398. }
  103399. break;
  103400. case 133: /* stl_prefix ::= */
  103401. {yygotominor.yy347 = 0;}
  103402. break;
  103403. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  103404. {
  103405. 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);
  103406. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  103407. }
  103408. break;
  103409. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  103410. {
  103411. 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);
  103412. }
  103413. break;
  103414. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  103415. {
  103416. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  103417. yygotominor.yy347 = yymsp[-4].minor.yy347;
  103418. }else{
  103419. Select *pSubquery;
  103420. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  103421. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
  103422. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  103423. }
  103424. }
  103425. break;
  103426. case 137: /* dbnm ::= */
  103427. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  103428. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  103429. break;
  103430. case 139: /* fullname ::= nm dbnm */
  103431. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  103432. break;
  103433. case 140: /* joinop ::= COMMA|JOIN */
  103434. { yygotominor.yy392 = JT_INNER; }
  103435. break;
  103436. case 141: /* joinop ::= JOIN_KW JOIN */
  103437. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  103438. break;
  103439. case 142: /* joinop ::= JOIN_KW nm JOIN */
  103440. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  103441. break;
  103442. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  103443. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  103444. break;
  103445. case 144: /* on_opt ::= ON expr */
  103446. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  103447. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  103448. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  103449. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  103450. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  103451. break;
  103452. case 145: /* on_opt ::= */
  103453. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  103454. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  103455. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  103456. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  103457. {yygotominor.yy122 = 0;}
  103458. break;
  103459. case 148: /* indexed_opt ::= NOT INDEXED */
  103460. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  103461. break;
  103462. case 149: /* using_opt ::= USING LP inscollist RP */
  103463. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  103464. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  103465. break;
  103466. case 150: /* using_opt ::= */
  103467. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  103468. {yygotominor.yy180 = 0;}
  103469. break;
  103470. case 152: /* orderby_opt ::= ORDER BY sortlist */
  103471. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  103472. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  103473. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  103474. break;
  103475. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  103476. {
  103477. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  103478. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  103479. }
  103480. break;
  103481. case 154: /* sortlist ::= expr sortorder */
  103482. {
  103483. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  103484. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  103485. }
  103486. break;
  103487. case 155: /* sortorder ::= ASC */
  103488. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  103489. {yygotominor.yy392 = SQLITE_SO_ASC;}
  103490. break;
  103491. case 156: /* sortorder ::= DESC */
  103492. {yygotominor.yy392 = SQLITE_SO_DESC;}
  103493. break;
  103494. case 162: /* limit_opt ::= */
  103495. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  103496. break;
  103497. case 163: /* limit_opt ::= LIMIT expr */
  103498. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  103499. break;
  103500. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  103501. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  103502. break;
  103503. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  103504. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  103505. break;
  103506. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  103507. {
  103508. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  103509. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  103510. }
  103511. break;
  103512. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  103513. {
  103514. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  103515. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  103516. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  103517. }
  103518. break;
  103519. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  103520. {
  103521. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  103522. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  103523. }
  103524. break;
  103525. case 171: /* setlist ::= nm EQ expr */
  103526. {
  103527. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  103528. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  103529. }
  103530. break;
  103531. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  103532. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  103533. break;
  103534. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  103535. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  103536. break;
  103537. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  103538. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  103539. break;
  103540. case 175: /* insert_cmd ::= INSERT orconf */
  103541. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  103542. break;
  103543. case 176: /* insert_cmd ::= REPLACE */
  103544. {yygotominor.yy258 = OE_Replace;}
  103545. break;
  103546. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  103547. {
  103548. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  103549. yygotominor.yy487.pSelect = 0;
  103550. }
  103551. break;
  103552. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  103553. {
  103554. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  103555. if( yymsp[-4].minor.yy487.pList ){
  103556. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  103557. yymsp[-4].minor.yy487.pList = 0;
  103558. }
  103559. yygotominor.yy487.pList = 0;
  103560. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  103561. sqlite3SelectDelete(pParse->db, pRight);
  103562. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  103563. yygotominor.yy487.pSelect = 0;
  103564. }else{
  103565. pRight->op = TK_ALL;
  103566. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  103567. pRight->selFlags |= SF_Values;
  103568. pRight->pPrior->selFlags |= SF_Values;
  103569. yygotominor.yy487.pSelect = pRight;
  103570. }
  103571. }
  103572. break;
  103573. case 181: /* inscollist ::= inscollist COMMA nm */
  103574. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  103575. break;
  103576. case 182: /* inscollist ::= nm */
  103577. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  103578. break;
  103579. case 183: /* expr ::= term */
  103580. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  103581. break;
  103582. case 184: /* expr ::= LP expr RP */
  103583. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  103584. break;
  103585. case 185: /* term ::= NULL */
  103586. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  103587. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  103588. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  103589. break;
  103590. case 186: /* expr ::= id */
  103591. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  103592. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  103593. break;
  103594. case 188: /* expr ::= nm DOT nm */
  103595. {
  103596. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  103597. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  103598. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  103599. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  103600. }
  103601. break;
  103602. case 189: /* expr ::= nm DOT nm DOT nm */
  103603. {
  103604. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  103605. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  103606. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  103607. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  103608. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  103609. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  103610. }
  103611. break;
  103612. case 192: /* expr ::= REGISTER */
  103613. {
  103614. /* When doing a nested parse, one can include terms in an expression
  103615. ** that look like this: #1 #2 ... These terms refer to registers
  103616. ** in the virtual machine. #N is the N-th register. */
  103617. if( pParse->nested==0 ){
  103618. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  103619. yygotominor.yy342.pExpr = 0;
  103620. }else{
  103621. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  103622. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  103623. }
  103624. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  103625. }
  103626. break;
  103627. case 193: /* expr ::= VARIABLE */
  103628. {
  103629. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  103630. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  103631. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  103632. }
  103633. break;
  103634. case 194: /* expr ::= expr COLLATE ids */
  103635. {
  103636. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  103637. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  103638. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103639. }
  103640. break;
  103641. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  103642. {
  103643. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  103644. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  103645. }
  103646. break;
  103647. case 196: /* expr ::= ID LP distinct exprlist RP */
  103648. {
  103649. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  103650. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  103651. }
  103652. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  103653. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  103654. if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
  103655. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  103656. }
  103657. }
  103658. break;
  103659. case 197: /* expr ::= ID LP STAR RP */
  103660. {
  103661. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  103662. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  103663. }
  103664. break;
  103665. case 198: /* term ::= CTIME_KW */
  103666. {
  103667. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  103668. ** treated as functions that return constants */
  103669. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  103670. if( yygotominor.yy342.pExpr ){
  103671. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  103672. }
  103673. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  103674. }
  103675. break;
  103676. case 199: /* expr ::= expr AND expr */
  103677. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  103678. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  103679. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  103680. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  103681. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  103682. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  103683. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  103684. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  103685. break;
  103686. case 207: /* likeop ::= LIKE_KW */
  103687. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  103688. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  103689. break;
  103690. case 208: /* likeop ::= NOT LIKE_KW */
  103691. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  103692. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  103693. break;
  103694. case 211: /* expr ::= expr likeop expr */
  103695. {
  103696. ExprList *pList;
  103697. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  103698. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  103699. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  103700. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103701. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  103702. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  103703. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  103704. }
  103705. break;
  103706. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  103707. {
  103708. ExprList *pList;
  103709. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  103710. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  103711. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  103712. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  103713. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103714. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  103715. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  103716. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  103717. }
  103718. break;
  103719. case 213: /* expr ::= expr ISNULL|NOTNULL */
  103720. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  103721. break;
  103722. case 214: /* expr ::= expr NOT NULL */
  103723. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  103724. break;
  103725. case 215: /* expr ::= expr IS expr */
  103726. {
  103727. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  103728. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  103729. }
  103730. break;
  103731. case 216: /* expr ::= expr IS NOT expr */
  103732. {
  103733. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  103734. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  103735. }
  103736. break;
  103737. case 217: /* expr ::= NOT expr */
  103738. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  103739. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  103740. break;
  103741. case 219: /* expr ::= MINUS expr */
  103742. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  103743. break;
  103744. case 220: /* expr ::= PLUS expr */
  103745. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  103746. break;
  103747. case 223: /* expr ::= expr between_op expr AND expr */
  103748. {
  103749. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  103750. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  103751. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  103752. if( yygotominor.yy342.pExpr ){
  103753. yygotominor.yy342.pExpr->x.pList = pList;
  103754. }else{
  103755. sqlite3ExprListDelete(pParse->db, pList);
  103756. }
  103757. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103758. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  103759. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  103760. }
  103761. break;
  103762. case 226: /* expr ::= expr in_op LP exprlist RP */
  103763. {
  103764. if( yymsp[-1].minor.yy442==0 ){
  103765. /* Expressions of the form
  103766. **
  103767. ** expr1 IN ()
  103768. ** expr1 NOT IN ()
  103769. **
  103770. ** simplify to constants 0 (false) and 1 (true), respectively,
  103771. ** regardless of the value of expr1.
  103772. */
  103773. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  103774. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  103775. }else{
  103776. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  103777. if( yygotominor.yy342.pExpr ){
  103778. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  103779. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  103780. }else{
  103781. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  103782. }
  103783. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103784. }
  103785. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  103786. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103787. }
  103788. break;
  103789. case 227: /* expr ::= LP select RP */
  103790. {
  103791. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  103792. if( yygotominor.yy342.pExpr ){
  103793. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  103794. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  103795. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  103796. }else{
  103797. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  103798. }
  103799. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  103800. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103801. }
  103802. break;
  103803. case 228: /* expr ::= expr in_op LP select RP */
  103804. {
  103805. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  103806. if( yygotominor.yy342.pExpr ){
  103807. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  103808. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  103809. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  103810. }else{
  103811. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  103812. }
  103813. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103814. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  103815. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103816. }
  103817. break;
  103818. case 229: /* expr ::= expr in_op nm dbnm */
  103819. {
  103820. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  103821. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  103822. if( yygotominor.yy342.pExpr ){
  103823. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  103824. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  103825. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  103826. }else{
  103827. sqlite3SrcListDelete(pParse->db, pSrc);
  103828. }
  103829. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  103830. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  103831. 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];
  103832. }
  103833. break;
  103834. case 230: /* expr ::= EXISTS LP select RP */
  103835. {
  103836. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  103837. if( p ){
  103838. p->x.pSelect = yymsp[-1].minor.yy159;
  103839. ExprSetProperty(p, EP_xIsSelect);
  103840. sqlite3ExprSetHeight(pParse, p);
  103841. }else{
  103842. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  103843. }
  103844. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  103845. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103846. }
  103847. break;
  103848. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  103849. {
  103850. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
  103851. if( yygotominor.yy342.pExpr ){
  103852. yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
  103853. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  103854. }else{
  103855. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  103856. }
  103857. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  103858. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  103859. }
  103860. break;
  103861. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  103862. {
  103863. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  103864. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  103865. }
  103866. break;
  103867. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  103868. {
  103869. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  103870. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  103871. }
  103872. break;
  103873. case 240: /* nexprlist ::= nexprlist COMMA expr */
  103874. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  103875. break;
  103876. case 241: /* nexprlist ::= expr */
  103877. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  103878. break;
  103879. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
  103880. {
  103881. sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
  103882. sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
  103883. &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
  103884. }
  103885. break;
  103886. case 243: /* uniqueflag ::= UNIQUE */
  103887. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  103888. {yygotominor.yy392 = OE_Abort;}
  103889. break;
  103890. case 244: /* uniqueflag ::= */
  103891. {yygotominor.yy392 = OE_None;}
  103892. break;
  103893. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  103894. {
  103895. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  103896. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  103897. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  103898. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  103899. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  103900. }
  103901. break;
  103902. case 248: /* idxlist ::= nm collate sortorder */
  103903. {
  103904. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  103905. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  103906. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  103907. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  103908. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  103909. }
  103910. break;
  103911. case 249: /* collate ::= */
  103912. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  103913. break;
  103914. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  103915. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  103916. break;
  103917. case 252: /* cmd ::= VACUUM */
  103918. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  103919. {sqlite3Vacuum(pParse);}
  103920. break;
  103921. case 254: /* cmd ::= PRAGMA nm dbnm */
  103922. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  103923. break;
  103924. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  103925. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  103926. break;
  103927. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  103928. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  103929. break;
  103930. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  103931. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  103932. break;
  103933. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  103934. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  103935. break;
  103936. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  103937. {
  103938. Token all;
  103939. all.z = yymsp[-3].minor.yy0.z;
  103940. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  103941. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  103942. }
  103943. break;
  103944. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  103945. {
  103946. 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);
  103947. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  103948. }
  103949. break;
  103950. case 270: /* trigger_time ::= BEFORE */
  103951. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  103952. { yygotominor.yy392 = TK_BEFORE; }
  103953. break;
  103954. case 271: /* trigger_time ::= AFTER */
  103955. { yygotominor.yy392 = TK_AFTER; }
  103956. break;
  103957. case 272: /* trigger_time ::= INSTEAD OF */
  103958. { yygotominor.yy392 = TK_INSTEAD;}
  103959. break;
  103960. case 274: /* trigger_event ::= DELETE|INSERT */
  103961. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  103962. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  103963. break;
  103964. case 276: /* trigger_event ::= UPDATE OF inscollist */
  103965. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  103966. break;
  103967. case 279: /* when_clause ::= */
  103968. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  103969. { yygotominor.yy122 = 0; }
  103970. break;
  103971. case 280: /* when_clause ::= WHEN expr */
  103972. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  103973. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  103974. break;
  103975. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  103976. {
  103977. assert( yymsp[-2].minor.yy327!=0 );
  103978. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  103979. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  103980. yygotominor.yy327 = yymsp[-2].minor.yy327;
  103981. }
  103982. break;
  103983. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  103984. {
  103985. assert( yymsp[-1].minor.yy327!=0 );
  103986. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  103987. yygotominor.yy327 = yymsp[-1].minor.yy327;
  103988. }
  103989. break;
  103990. case 284: /* trnm ::= nm DOT nm */
  103991. {
  103992. yygotominor.yy0 = yymsp[0].minor.yy0;
  103993. sqlite3ErrorMsg(pParse,
  103994. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  103995. "statements within triggers");
  103996. }
  103997. break;
  103998. case 286: /* tridxby ::= INDEXED BY nm */
  103999. {
  104000. sqlite3ErrorMsg(pParse,
  104001. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  104002. "within triggers");
  104003. }
  104004. break;
  104005. case 287: /* tridxby ::= NOT INDEXED */
  104006. {
  104007. sqlite3ErrorMsg(pParse,
  104008. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  104009. "within triggers");
  104010. }
  104011. break;
  104012. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  104013. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  104014. break;
  104015. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  104016. {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);}
  104017. break;
  104018. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  104019. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  104020. break;
  104021. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  104022. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  104023. break;
  104024. case 292: /* trigger_cmd ::= select */
  104025. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  104026. break;
  104027. case 293: /* expr ::= RAISE LP IGNORE RP */
  104028. {
  104029. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  104030. if( yygotominor.yy342.pExpr ){
  104031. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  104032. }
  104033. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  104034. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  104035. }
  104036. break;
  104037. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  104038. {
  104039. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  104040. if( yygotominor.yy342.pExpr ) {
  104041. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  104042. }
  104043. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  104044. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  104045. }
  104046. break;
  104047. case 295: /* raisetype ::= ROLLBACK */
  104048. {yygotominor.yy392 = OE_Rollback;}
  104049. break;
  104050. case 297: /* raisetype ::= FAIL */
  104051. {yygotominor.yy392 = OE_Fail;}
  104052. break;
  104053. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  104054. {
  104055. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  104056. }
  104057. break;
  104058. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  104059. {
  104060. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  104061. }
  104062. break;
  104063. case 300: /* cmd ::= DETACH database_kw_opt expr */
  104064. {
  104065. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  104066. }
  104067. break;
  104068. case 305: /* cmd ::= REINDEX */
  104069. {sqlite3Reindex(pParse, 0, 0);}
  104070. break;
  104071. case 306: /* cmd ::= REINDEX nm dbnm */
  104072. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  104073. break;
  104074. case 307: /* cmd ::= ANALYZE */
  104075. {sqlite3Analyze(pParse, 0, 0);}
  104076. break;
  104077. case 308: /* cmd ::= ANALYZE nm dbnm */
  104078. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  104079. break;
  104080. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  104081. {
  104082. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  104083. }
  104084. break;
  104085. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  104086. {
  104087. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  104088. }
  104089. break;
  104090. case 311: /* add_column_fullname ::= fullname */
  104091. {
  104092. pParse->db->lookaside.bEnabled = 0;
  104093. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  104094. }
  104095. break;
  104096. case 314: /* cmd ::= create_vtab */
  104097. {sqlite3VtabFinishParse(pParse,0);}
  104098. break;
  104099. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  104100. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  104101. break;
  104102. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  104103. {
  104104. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  104105. }
  104106. break;
  104107. case 319: /* vtabarg ::= */
  104108. {sqlite3VtabArgInit(pParse);}
  104109. break;
  104110. case 321: /* vtabargtoken ::= ANY */
  104111. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  104112. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  104113. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  104114. break;
  104115. default:
  104116. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  104117. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  104118. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  104119. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  104120. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  104121. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  104122. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  104123. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  104124. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  104125. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  104126. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  104127. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  104128. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  104129. /* (44) type ::= */ yytestcase(yyruleno==44);
  104130. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  104131. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  104132. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  104133. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  104134. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  104135. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  104136. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  104137. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  104138. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  104139. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  104140. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  104141. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  104142. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  104143. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  104144. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  104145. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  104146. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  104147. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  104148. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  104149. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  104150. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  104151. break;
  104152. };
  104153. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  104154. yygoto = yyRuleInfo[yyruleno].lhs;
  104155. yysize = yyRuleInfo[yyruleno].nrhs;
  104156. yypParser->yyidx -= yysize;
  104157. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  104158. if( yyact < YYNSTATE ){
  104159. #ifdef NDEBUG
  104160. /* If we are not debugging and the reduce action popped at least
  104161. ** one element off the stack, then we can push the new element back
  104162. ** onto the stack here, and skip the stack overflow test in yy_shift().
  104163. ** That gives a significant speed improvement. */
  104164. if( yysize ){
  104165. yypParser->yyidx++;
  104166. yymsp -= yysize-1;
  104167. yymsp->stateno = (YYACTIONTYPE)yyact;
  104168. yymsp->major = (YYCODETYPE)yygoto;
  104169. yymsp->minor = yygotominor;
  104170. }else
  104171. #endif
  104172. {
  104173. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  104174. }
  104175. }else{
  104176. assert( yyact == YYNSTATE + YYNRULE + 1 );
  104177. yy_accept(yypParser);
  104178. }
  104179. }
  104180. /*
  104181. ** The following code executes when the parse fails
  104182. */
  104183. #ifndef YYNOERRORRECOVERY
  104184. static void yy_parse_failed(
  104185. yyParser *yypParser /* The parser */
  104186. ){
  104187. sqlite3ParserARG_FETCH;
  104188. #ifndef NDEBUG
  104189. if( yyTraceFILE ){
  104190. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  104191. }
  104192. #endif
  104193. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  104194. /* Here code is inserted which will be executed whenever the
  104195. ** parser fails */
  104196. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  104197. }
  104198. #endif /* YYNOERRORRECOVERY */
  104199. /*
  104200. ** The following code executes when a syntax error first occurs.
  104201. */
  104202. static void yy_syntax_error(
  104203. yyParser *yypParser, /* The parser */
  104204. int yymajor, /* The major type of the error token */
  104205. YYMINORTYPE yyminor /* The minor type of the error token */
  104206. ){
  104207. sqlite3ParserARG_FETCH;
  104208. #define TOKEN (yyminor.yy0)
  104209. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  104210. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  104211. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  104212. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  104213. }
  104214. /*
  104215. ** The following is executed when the parser accepts
  104216. */
  104217. static void yy_accept(
  104218. yyParser *yypParser /* The parser */
  104219. ){
  104220. sqlite3ParserARG_FETCH;
  104221. #ifndef NDEBUG
  104222. if( yyTraceFILE ){
  104223. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  104224. }
  104225. #endif
  104226. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  104227. /* Here code is inserted which will be executed whenever the
  104228. ** parser accepts */
  104229. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  104230. }
  104231. /* The main parser program.
  104232. ** The first argument is a pointer to a structure obtained from
  104233. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  104234. ** The second argument is the major token number. The third is
  104235. ** the minor token. The fourth optional argument is whatever the
  104236. ** user wants (and specified in the grammar) and is available for
  104237. ** use by the action routines.
  104238. **
  104239. ** Inputs:
  104240. ** <ul>
  104241. ** <li> A pointer to the parser (an opaque structure.)
  104242. ** <li> The major token number.
  104243. ** <li> The minor token number.
  104244. ** <li> An option argument of a grammar-specified type.
  104245. ** </ul>
  104246. **
  104247. ** Outputs:
  104248. ** None.
  104249. */
  104250. SQLITE_PRIVATE void sqlite3Parser(
  104251. void *yyp, /* The parser */
  104252. int yymajor, /* The major token code number */
  104253. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  104254. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  104255. ){
  104256. YYMINORTYPE yyminorunion;
  104257. int yyact; /* The parser action. */
  104258. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  104259. int yyendofinput; /* True if we are at the end of input */
  104260. #endif
  104261. #ifdef YYERRORSYMBOL
  104262. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  104263. #endif
  104264. yyParser *yypParser; /* The parser */
  104265. /* (re)initialize the parser, if necessary */
  104266. yypParser = (yyParser*)yyp;
  104267. if( yypParser->yyidx<0 ){
  104268. #if YYSTACKDEPTH<=0
  104269. if( yypParser->yystksz <=0 ){
  104270. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  104271. yyminorunion = yyzerominor;
  104272. yyStackOverflow(yypParser, &yyminorunion);
  104273. return;
  104274. }
  104275. #endif
  104276. yypParser->yyidx = 0;
  104277. yypParser->yyerrcnt = -1;
  104278. yypParser->yystack[0].stateno = 0;
  104279. yypParser->yystack[0].major = 0;
  104280. }
  104281. yyminorunion.yy0 = yyminor;
  104282. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  104283. yyendofinput = (yymajor==0);
  104284. #endif
  104285. sqlite3ParserARG_STORE;
  104286. #ifndef NDEBUG
  104287. if( yyTraceFILE ){
  104288. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  104289. }
  104290. #endif
  104291. do{
  104292. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  104293. if( yyact<YYNSTATE ){
  104294. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  104295. yypParser->yyerrcnt--;
  104296. yymajor = YYNOCODE;
  104297. }else if( yyact < YYNSTATE + YYNRULE ){
  104298. yy_reduce(yypParser,yyact-YYNSTATE);
  104299. }else{
  104300. assert( yyact == YY_ERROR_ACTION );
  104301. #ifdef YYERRORSYMBOL
  104302. int yymx;
  104303. #endif
  104304. #ifndef NDEBUG
  104305. if( yyTraceFILE ){
  104306. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  104307. }
  104308. #endif
  104309. #ifdef YYERRORSYMBOL
  104310. /* A syntax error has occurred.
  104311. ** The response to an error depends upon whether or not the
  104312. ** grammar defines an error token "ERROR".
  104313. **
  104314. ** This is what we do if the grammar does define ERROR:
  104315. **
  104316. ** * Call the %syntax_error function.
  104317. **
  104318. ** * Begin popping the stack until we enter a state where
  104319. ** it is legal to shift the error symbol, then shift
  104320. ** the error symbol.
  104321. **
  104322. ** * Set the error count to three.
  104323. **
  104324. ** * Begin accepting and shifting new tokens. No new error
  104325. ** processing will occur until three tokens have been
  104326. ** shifted successfully.
  104327. **
  104328. */
  104329. if( yypParser->yyerrcnt<0 ){
  104330. yy_syntax_error(yypParser,yymajor,yyminorunion);
  104331. }
  104332. yymx = yypParser->yystack[yypParser->yyidx].major;
  104333. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  104334. #ifndef NDEBUG
  104335. if( yyTraceFILE ){
  104336. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  104337. yyTracePrompt,yyTokenName[yymajor]);
  104338. }
  104339. #endif
  104340. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  104341. yymajor = YYNOCODE;
  104342. }else{
  104343. while(
  104344. yypParser->yyidx >= 0 &&
  104345. yymx != YYERRORSYMBOL &&
  104346. (yyact = yy_find_reduce_action(
  104347. yypParser->yystack[yypParser->yyidx].stateno,
  104348. YYERRORSYMBOL)) >= YYNSTATE
  104349. ){
  104350. yy_pop_parser_stack(yypParser);
  104351. }
  104352. if( yypParser->yyidx < 0 || yymajor==0 ){
  104353. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  104354. yy_parse_failed(yypParser);
  104355. yymajor = YYNOCODE;
  104356. }else if( yymx!=YYERRORSYMBOL ){
  104357. YYMINORTYPE u2;
  104358. u2.YYERRSYMDT = 0;
  104359. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  104360. }
  104361. }
  104362. yypParser->yyerrcnt = 3;
  104363. yyerrorhit = 1;
  104364. #elif defined(YYNOERRORRECOVERY)
  104365. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  104366. ** do any kind of error recovery. Instead, simply invoke the syntax
  104367. ** error routine and continue going as if nothing had happened.
  104368. **
  104369. ** Applications can set this macro (for example inside %include) if
  104370. ** they intend to abandon the parse upon the first syntax error seen.
  104371. */
  104372. yy_syntax_error(yypParser,yymajor,yyminorunion);
  104373. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  104374. yymajor = YYNOCODE;
  104375. #else /* YYERRORSYMBOL is not defined */
  104376. /* This is what we do if the grammar does not define ERROR:
  104377. **
  104378. ** * Report an error message, and throw away the input token.
  104379. **
  104380. ** * If the input token is $, then fail the parse.
  104381. **
  104382. ** As before, subsequent error messages are suppressed until
  104383. ** three input tokens have been successfully shifted.
  104384. */
  104385. if( yypParser->yyerrcnt<=0 ){
  104386. yy_syntax_error(yypParser,yymajor,yyminorunion);
  104387. }
  104388. yypParser->yyerrcnt = 3;
  104389. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  104390. if( yyendofinput ){
  104391. yy_parse_failed(yypParser);
  104392. }
  104393. yymajor = YYNOCODE;
  104394. #endif
  104395. }
  104396. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  104397. return;
  104398. }
  104399. /************** End of parse.c ***********************************************/
  104400. /************** Begin file tokenize.c ****************************************/
  104401. /*
  104402. ** 2001 September 15
  104403. **
  104404. ** The author disclaims copyright to this source code. In place of
  104405. ** a legal notice, here is a blessing:
  104406. **
  104407. ** May you do good and not evil.
  104408. ** May you find forgiveness for yourself and forgive others.
  104409. ** May you share freely, never taking more than you give.
  104410. **
  104411. *************************************************************************
  104412. ** An tokenizer for SQL
  104413. **
  104414. ** This file contains C code that splits an SQL input string up into
  104415. ** individual tokens and sends those tokens one-by-one over to the
  104416. ** parser for analysis.
  104417. */
  104418. /* #include <stdlib.h> */
  104419. /*
  104420. ** The charMap() macro maps alphabetic characters into their
  104421. ** lower-case ASCII equivalent. On ASCII machines, this is just
  104422. ** an upper-to-lower case map. On EBCDIC machines we also need
  104423. ** to adjust the encoding. Only alphabetic characters and underscores
  104424. ** need to be translated.
  104425. */
  104426. #ifdef SQLITE_ASCII
  104427. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  104428. #endif
  104429. #ifdef SQLITE_EBCDIC
  104430. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  104431. const unsigned char ebcdicToAscii[] = {
  104432. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  104433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  104434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  104435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  104436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  104437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  104438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  104439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  104440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  104441. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  104442. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  104443. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  104444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  104445. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  104446. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  104447. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  104448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  104449. };
  104450. #endif
  104451. /*
  104452. ** The sqlite3KeywordCode function looks up an identifier to determine if
  104453. ** it is a keyword. If it is a keyword, the token code of that keyword is
  104454. ** returned. If the input is not a keyword, TK_ID is returned.
  104455. **
  104456. ** The implementation of this routine was generated by a program,
  104457. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  104458. ** The output of the mkkeywordhash.c program is written into a file
  104459. ** named keywordhash.h and then included into this source file by
  104460. ** the #include below.
  104461. */
  104462. /************** Include keywordhash.h in the middle of tokenize.c ************/
  104463. /************** Begin file keywordhash.h *************************************/
  104464. /***** This file contains automatically generated code ******
  104465. **
  104466. ** The code in this file has been automatically generated by
  104467. **
  104468. ** sqlite/tool/mkkeywordhash.c
  104469. **
  104470. ** The code in this file implements a function that determines whether
  104471. ** or not a given identifier is really an SQL keyword. The same thing
  104472. ** might be implemented more directly using a hand-written hash table.
  104473. ** But by using this automatically generated code, the size of the code
  104474. ** is substantially reduced. This is important for embedded applications
  104475. ** on platforms with limited memory.
  104476. */
  104477. /* Hash score: 175 */
  104478. static int keywordCode(const char *z, int n){
  104479. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  104480. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  104481. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  104482. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  104483. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  104484. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  104485. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  104486. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  104487. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  104488. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  104489. /* INITIALLY */
  104490. static const char zText[540] = {
  104491. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  104492. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  104493. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  104494. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  104495. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  104496. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  104497. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  104498. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  104499. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  104500. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  104501. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  104502. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  104503. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  104504. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  104505. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  104506. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  104507. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  104508. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  104509. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  104510. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  104511. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  104512. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  104513. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  104514. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  104515. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  104516. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  104517. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  104518. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  104519. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  104520. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  104521. };
  104522. static const unsigned char aHash[127] = {
  104523. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  104524. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  104525. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  104526. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  104527. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  104528. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  104529. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  104530. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  104531. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  104532. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  104533. };
  104534. static const unsigned char aNext[121] = {
  104535. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  104536. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  104537. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  104538. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  104539. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  104540. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  104541. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  104542. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  104543. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  104544. 35, 64, 0, 0,
  104545. };
  104546. static const unsigned char aLen[121] = {
  104547. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  104548. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  104549. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  104550. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  104551. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  104552. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  104553. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  104554. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  104555. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  104556. 6, 4, 9, 3,
  104557. };
  104558. static const unsigned short int aOffset[121] = {
  104559. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  104560. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  104561. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  104562. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  104563. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  104564. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  104565. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  104566. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  104567. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  104568. 521, 527, 531, 536,
  104569. };
  104570. static const unsigned char aCode[121] = {
  104571. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  104572. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  104573. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  104574. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  104575. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  104576. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  104577. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  104578. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  104579. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  104580. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  104581. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  104582. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  104583. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  104584. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  104585. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  104586. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  104587. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  104588. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  104589. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  104590. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  104591. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  104592. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  104593. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  104594. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  104595. TK_ALL,
  104596. };
  104597. int h, i;
  104598. if( n<2 ) return TK_ID;
  104599. h = ((charMap(z[0])*4) ^
  104600. (charMap(z[n-1])*3) ^
  104601. n) % 127;
  104602. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  104603. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  104604. testcase( i==0 ); /* REINDEX */
  104605. testcase( i==1 ); /* INDEXED */
  104606. testcase( i==2 ); /* INDEX */
  104607. testcase( i==3 ); /* DESC */
  104608. testcase( i==4 ); /* ESCAPE */
  104609. testcase( i==5 ); /* EACH */
  104610. testcase( i==6 ); /* CHECK */
  104611. testcase( i==7 ); /* KEY */
  104612. testcase( i==8 ); /* BEFORE */
  104613. testcase( i==9 ); /* FOREIGN */
  104614. testcase( i==10 ); /* FOR */
  104615. testcase( i==11 ); /* IGNORE */
  104616. testcase( i==12 ); /* REGEXP */
  104617. testcase( i==13 ); /* EXPLAIN */
  104618. testcase( i==14 ); /* INSTEAD */
  104619. testcase( i==15 ); /* ADD */
  104620. testcase( i==16 ); /* DATABASE */
  104621. testcase( i==17 ); /* AS */
  104622. testcase( i==18 ); /* SELECT */
  104623. testcase( i==19 ); /* TABLE */
  104624. testcase( i==20 ); /* LEFT */
  104625. testcase( i==21 ); /* THEN */
  104626. testcase( i==22 ); /* END */
  104627. testcase( i==23 ); /* DEFERRABLE */
  104628. testcase( i==24 ); /* ELSE */
  104629. testcase( i==25 ); /* EXCEPT */
  104630. testcase( i==26 ); /* TRANSACTION */
  104631. testcase( i==27 ); /* ACTION */
  104632. testcase( i==28 ); /* ON */
  104633. testcase( i==29 ); /* NATURAL */
  104634. testcase( i==30 ); /* ALTER */
  104635. testcase( i==31 ); /* RAISE */
  104636. testcase( i==32 ); /* EXCLUSIVE */
  104637. testcase( i==33 ); /* EXISTS */
  104638. testcase( i==34 ); /* SAVEPOINT */
  104639. testcase( i==35 ); /* INTERSECT */
  104640. testcase( i==36 ); /* TRIGGER */
  104641. testcase( i==37 ); /* REFERENCES */
  104642. testcase( i==38 ); /* CONSTRAINT */
  104643. testcase( i==39 ); /* INTO */
  104644. testcase( i==40 ); /* OFFSET */
  104645. testcase( i==41 ); /* OF */
  104646. testcase( i==42 ); /* SET */
  104647. testcase( i==43 ); /* TEMPORARY */
  104648. testcase( i==44 ); /* TEMP */
  104649. testcase( i==45 ); /* OR */
  104650. testcase( i==46 ); /* UNIQUE */
  104651. testcase( i==47 ); /* QUERY */
  104652. testcase( i==48 ); /* ATTACH */
  104653. testcase( i==49 ); /* HAVING */
  104654. testcase( i==50 ); /* GROUP */
  104655. testcase( i==51 ); /* UPDATE */
  104656. testcase( i==52 ); /* BEGIN */
  104657. testcase( i==53 ); /* INNER */
  104658. testcase( i==54 ); /* RELEASE */
  104659. testcase( i==55 ); /* BETWEEN */
  104660. testcase( i==56 ); /* NOTNULL */
  104661. testcase( i==57 ); /* NOT */
  104662. testcase( i==58 ); /* NO */
  104663. testcase( i==59 ); /* NULL */
  104664. testcase( i==60 ); /* LIKE */
  104665. testcase( i==61 ); /* CASCADE */
  104666. testcase( i==62 ); /* ASC */
  104667. testcase( i==63 ); /* DELETE */
  104668. testcase( i==64 ); /* CASE */
  104669. testcase( i==65 ); /* COLLATE */
  104670. testcase( i==66 ); /* CREATE */
  104671. testcase( i==67 ); /* CURRENT_DATE */
  104672. testcase( i==68 ); /* DETACH */
  104673. testcase( i==69 ); /* IMMEDIATE */
  104674. testcase( i==70 ); /* JOIN */
  104675. testcase( i==71 ); /* INSERT */
  104676. testcase( i==72 ); /* MATCH */
  104677. testcase( i==73 ); /* PLAN */
  104678. testcase( i==74 ); /* ANALYZE */
  104679. testcase( i==75 ); /* PRAGMA */
  104680. testcase( i==76 ); /* ABORT */
  104681. testcase( i==77 ); /* VALUES */
  104682. testcase( i==78 ); /* VIRTUAL */
  104683. testcase( i==79 ); /* LIMIT */
  104684. testcase( i==80 ); /* WHEN */
  104685. testcase( i==81 ); /* WHERE */
  104686. testcase( i==82 ); /* RENAME */
  104687. testcase( i==83 ); /* AFTER */
  104688. testcase( i==84 ); /* REPLACE */
  104689. testcase( i==85 ); /* AND */
  104690. testcase( i==86 ); /* DEFAULT */
  104691. testcase( i==87 ); /* AUTOINCREMENT */
  104692. testcase( i==88 ); /* TO */
  104693. testcase( i==89 ); /* IN */
  104694. testcase( i==90 ); /* CAST */
  104695. testcase( i==91 ); /* COLUMN */
  104696. testcase( i==92 ); /* COMMIT */
  104697. testcase( i==93 ); /* CONFLICT */
  104698. testcase( i==94 ); /* CROSS */
  104699. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  104700. testcase( i==96 ); /* CURRENT_TIME */
  104701. testcase( i==97 ); /* PRIMARY */
  104702. testcase( i==98 ); /* DEFERRED */
  104703. testcase( i==99 ); /* DISTINCT */
  104704. testcase( i==100 ); /* IS */
  104705. testcase( i==101 ); /* DROP */
  104706. testcase( i==102 ); /* FAIL */
  104707. testcase( i==103 ); /* FROM */
  104708. testcase( i==104 ); /* FULL */
  104709. testcase( i==105 ); /* GLOB */
  104710. testcase( i==106 ); /* BY */
  104711. testcase( i==107 ); /* IF */
  104712. testcase( i==108 ); /* ISNULL */
  104713. testcase( i==109 ); /* ORDER */
  104714. testcase( i==110 ); /* RESTRICT */
  104715. testcase( i==111 ); /* OUTER */
  104716. testcase( i==112 ); /* RIGHT */
  104717. testcase( i==113 ); /* ROLLBACK */
  104718. testcase( i==114 ); /* ROW */
  104719. testcase( i==115 ); /* UNION */
  104720. testcase( i==116 ); /* USING */
  104721. testcase( i==117 ); /* VACUUM */
  104722. testcase( i==118 ); /* VIEW */
  104723. testcase( i==119 ); /* INITIALLY */
  104724. testcase( i==120 ); /* ALL */
  104725. return aCode[i];
  104726. }
  104727. }
  104728. return TK_ID;
  104729. }
  104730. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  104731. return keywordCode((char*)z, n);
  104732. }
  104733. #define SQLITE_N_KEYWORD 121
  104734. /************** End of keywordhash.h *****************************************/
  104735. /************** Continuing where we left off in tokenize.c *******************/
  104736. /*
  104737. ** If X is a character that can be used in an identifier then
  104738. ** IdChar(X) will be true. Otherwise it is false.
  104739. **
  104740. ** For ASCII, any character with the high-order bit set is
  104741. ** allowed in an identifier. For 7-bit characters,
  104742. ** sqlite3IsIdChar[X] must be 1.
  104743. **
  104744. ** For EBCDIC, the rules are more complex but have the same
  104745. ** end result.
  104746. **
  104747. ** Ticket #1066. the SQL standard does not allow '$' in the
  104748. ** middle of identfiers. But many SQL implementations do.
  104749. ** SQLite will allow '$' in identifiers for compatibility.
  104750. ** But the feature is undocumented.
  104751. */
  104752. #ifdef SQLITE_ASCII
  104753. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  104754. #endif
  104755. #ifdef SQLITE_EBCDIC
  104756. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  104757. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  104758. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  104759. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  104760. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  104761. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  104762. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  104763. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  104764. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  104765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  104766. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  104767. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  104768. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  104769. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  104770. };
  104771. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  104772. #endif
  104773. /*
  104774. ** Return the length of the token that begins at z[0].
  104775. ** Store the token type in *tokenType before returning.
  104776. */
  104777. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  104778. int i, c;
  104779. switch( *z ){
  104780. case ' ': case '\t': case '\n': case '\f': case '\r': {
  104781. testcase( z[0]==' ' );
  104782. testcase( z[0]=='\t' );
  104783. testcase( z[0]=='\n' );
  104784. testcase( z[0]=='\f' );
  104785. testcase( z[0]=='\r' );
  104786. for(i=1; sqlite3Isspace(z[i]); i++){}
  104787. *tokenType = TK_SPACE;
  104788. return i;
  104789. }
  104790. case '-': {
  104791. if( z[1]=='-' ){
  104792. /* IMP: R-50417-27976 -- syntax diagram for comments */
  104793. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  104794. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  104795. return i;
  104796. }
  104797. *tokenType = TK_MINUS;
  104798. return 1;
  104799. }
  104800. case '(': {
  104801. *tokenType = TK_LP;
  104802. return 1;
  104803. }
  104804. case ')': {
  104805. *tokenType = TK_RP;
  104806. return 1;
  104807. }
  104808. case ';': {
  104809. *tokenType = TK_SEMI;
  104810. return 1;
  104811. }
  104812. case '+': {
  104813. *tokenType = TK_PLUS;
  104814. return 1;
  104815. }
  104816. case '*': {
  104817. *tokenType = TK_STAR;
  104818. return 1;
  104819. }
  104820. case '/': {
  104821. if( z[1]!='*' || z[2]==0 ){
  104822. *tokenType = TK_SLASH;
  104823. return 1;
  104824. }
  104825. /* IMP: R-50417-27976 -- syntax diagram for comments */
  104826. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  104827. if( c ) i++;
  104828. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  104829. return i;
  104830. }
  104831. case '%': {
  104832. *tokenType = TK_REM;
  104833. return 1;
  104834. }
  104835. case '=': {
  104836. *tokenType = TK_EQ;
  104837. return 1 + (z[1]=='=');
  104838. }
  104839. case '<': {
  104840. if( (c=z[1])=='=' ){
  104841. *tokenType = TK_LE;
  104842. return 2;
  104843. }else if( c=='>' ){
  104844. *tokenType = TK_NE;
  104845. return 2;
  104846. }else if( c=='<' ){
  104847. *tokenType = TK_LSHIFT;
  104848. return 2;
  104849. }else{
  104850. *tokenType = TK_LT;
  104851. return 1;
  104852. }
  104853. }
  104854. case '>': {
  104855. if( (c=z[1])=='=' ){
  104856. *tokenType = TK_GE;
  104857. return 2;
  104858. }else if( c=='>' ){
  104859. *tokenType = TK_RSHIFT;
  104860. return 2;
  104861. }else{
  104862. *tokenType = TK_GT;
  104863. return 1;
  104864. }
  104865. }
  104866. case '!': {
  104867. if( z[1]!='=' ){
  104868. *tokenType = TK_ILLEGAL;
  104869. return 2;
  104870. }else{
  104871. *tokenType = TK_NE;
  104872. return 2;
  104873. }
  104874. }
  104875. case '|': {
  104876. if( z[1]!='|' ){
  104877. *tokenType = TK_BITOR;
  104878. return 1;
  104879. }else{
  104880. *tokenType = TK_CONCAT;
  104881. return 2;
  104882. }
  104883. }
  104884. case ',': {
  104885. *tokenType = TK_COMMA;
  104886. return 1;
  104887. }
  104888. case '&': {
  104889. *tokenType = TK_BITAND;
  104890. return 1;
  104891. }
  104892. case '~': {
  104893. *tokenType = TK_BITNOT;
  104894. return 1;
  104895. }
  104896. case '`':
  104897. case '\'':
  104898. case '"': {
  104899. int delim = z[0];
  104900. testcase( delim=='`' );
  104901. testcase( delim=='\'' );
  104902. testcase( delim=='"' );
  104903. for(i=1; (c=z[i])!=0; i++){
  104904. if( c==delim ){
  104905. if( z[i+1]==delim ){
  104906. i++;
  104907. }else{
  104908. break;
  104909. }
  104910. }
  104911. }
  104912. if( c=='\'' ){
  104913. *tokenType = TK_STRING;
  104914. return i+1;
  104915. }else if( c!=0 ){
  104916. *tokenType = TK_ID;
  104917. return i+1;
  104918. }else{
  104919. *tokenType = TK_ILLEGAL;
  104920. return i;
  104921. }
  104922. }
  104923. case '.': {
  104924. #ifndef SQLITE_OMIT_FLOATING_POINT
  104925. if( !sqlite3Isdigit(z[1]) )
  104926. #endif
  104927. {
  104928. *tokenType = TK_DOT;
  104929. return 1;
  104930. }
  104931. /* If the next character is a digit, this is a floating point
  104932. ** number that begins with ".". Fall thru into the next case */
  104933. }
  104934. case '0': case '1': case '2': case '3': case '4':
  104935. case '5': case '6': case '7': case '8': case '9': {
  104936. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  104937. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  104938. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  104939. testcase( z[0]=='9' );
  104940. *tokenType = TK_INTEGER;
  104941. for(i=0; sqlite3Isdigit(z[i]); i++){}
  104942. #ifndef SQLITE_OMIT_FLOATING_POINT
  104943. if( z[i]=='.' ){
  104944. i++;
  104945. while( sqlite3Isdigit(z[i]) ){ i++; }
  104946. *tokenType = TK_FLOAT;
  104947. }
  104948. if( (z[i]=='e' || z[i]=='E') &&
  104949. ( sqlite3Isdigit(z[i+1])
  104950. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  104951. )
  104952. ){
  104953. i += 2;
  104954. while( sqlite3Isdigit(z[i]) ){ i++; }
  104955. *tokenType = TK_FLOAT;
  104956. }
  104957. #endif
  104958. while( IdChar(z[i]) ){
  104959. *tokenType = TK_ILLEGAL;
  104960. i++;
  104961. }
  104962. return i;
  104963. }
  104964. case '[': {
  104965. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  104966. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  104967. return i;
  104968. }
  104969. case '?': {
  104970. *tokenType = TK_VARIABLE;
  104971. for(i=1; sqlite3Isdigit(z[i]); i++){}
  104972. return i;
  104973. }
  104974. case '#': {
  104975. for(i=1; sqlite3Isdigit(z[i]); i++){}
  104976. if( i>1 ){
  104977. /* Parameters of the form #NNN (where NNN is a number) are used
  104978. ** internally by sqlite3NestedParse. */
  104979. *tokenType = TK_REGISTER;
  104980. return i;
  104981. }
  104982. /* Fall through into the next case if the '#' is not followed by
  104983. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  104984. }
  104985. #ifndef SQLITE_OMIT_TCL_VARIABLE
  104986. case '$':
  104987. #endif
  104988. case '@': /* For compatibility with MS SQL Server */
  104989. case ':': {
  104990. int n = 0;
  104991. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  104992. *tokenType = TK_VARIABLE;
  104993. for(i=1; (c=z[i])!=0; i++){
  104994. if( IdChar(c) ){
  104995. n++;
  104996. #ifndef SQLITE_OMIT_TCL_VARIABLE
  104997. }else if( c=='(' && n>0 ){
  104998. do{
  104999. i++;
  105000. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  105001. if( c==')' ){
  105002. i++;
  105003. }else{
  105004. *tokenType = TK_ILLEGAL;
  105005. }
  105006. break;
  105007. }else if( c==':' && z[i+1]==':' ){
  105008. i++;
  105009. #endif
  105010. }else{
  105011. break;
  105012. }
  105013. }
  105014. if( n==0 ) *tokenType = TK_ILLEGAL;
  105015. return i;
  105016. }
  105017. #ifndef SQLITE_OMIT_BLOB_LITERAL
  105018. case 'x': case 'X': {
  105019. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  105020. if( z[1]=='\'' ){
  105021. *tokenType = TK_BLOB;
  105022. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  105023. if( z[i]!='\'' || i%2 ){
  105024. *tokenType = TK_ILLEGAL;
  105025. while( z[i] && z[i]!='\'' ){ i++; }
  105026. }
  105027. if( z[i] ) i++;
  105028. return i;
  105029. }
  105030. /* Otherwise fall through to the next case */
  105031. }
  105032. #endif
  105033. default: {
  105034. if( !IdChar(*z) ){
  105035. break;
  105036. }
  105037. for(i=1; IdChar(z[i]); i++){}
  105038. *tokenType = keywordCode((char*)z, i);
  105039. return i;
  105040. }
  105041. }
  105042. *tokenType = TK_ILLEGAL;
  105043. return 1;
  105044. }
  105045. /*
  105046. ** Run the parser on the given SQL string. The parser structure is
  105047. ** passed in. An SQLITE_ status code is returned. If an error occurs
  105048. ** then an and attempt is made to write an error message into
  105049. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  105050. ** error message.
  105051. */
  105052. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  105053. int nErr = 0; /* Number of errors encountered */
  105054. int i; /* Loop counter */
  105055. void *pEngine; /* The LEMON-generated LALR(1) parser */
  105056. int tokenType; /* type of the next token */
  105057. int lastTokenParsed = -1; /* type of the previous token */
  105058. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  105059. sqlite3 *db = pParse->db; /* The database connection */
  105060. int mxSqlLen; /* Max length of an SQL string */
  105061. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  105062. if( db->activeVdbeCnt==0 ){
  105063. db->u1.isInterrupted = 0;
  105064. }
  105065. pParse->rc = SQLITE_OK;
  105066. pParse->zTail = zSql;
  105067. i = 0;
  105068. assert( pzErrMsg!=0 );
  105069. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  105070. if( pEngine==0 ){
  105071. db->mallocFailed = 1;
  105072. return SQLITE_NOMEM;
  105073. }
  105074. assert( pParse->pNewTable==0 );
  105075. assert( pParse->pNewTrigger==0 );
  105076. assert( pParse->nVar==0 );
  105077. assert( pParse->nzVar==0 );
  105078. assert( pParse->azVar==0 );
  105079. enableLookaside = db->lookaside.bEnabled;
  105080. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  105081. while( !db->mallocFailed && zSql[i]!=0 ){
  105082. assert( i>=0 );
  105083. pParse->sLastToken.z = &zSql[i];
  105084. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  105085. i += pParse->sLastToken.n;
  105086. if( i>mxSqlLen ){
  105087. pParse->rc = SQLITE_TOOBIG;
  105088. break;
  105089. }
  105090. switch( tokenType ){
  105091. case TK_SPACE: {
  105092. if( db->u1.isInterrupted ){
  105093. sqlite3ErrorMsg(pParse, "interrupt");
  105094. pParse->rc = SQLITE_INTERRUPT;
  105095. goto abort_parse;
  105096. }
  105097. break;
  105098. }
  105099. case TK_ILLEGAL: {
  105100. sqlite3DbFree(db, *pzErrMsg);
  105101. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  105102. &pParse->sLastToken);
  105103. nErr++;
  105104. goto abort_parse;
  105105. }
  105106. case TK_SEMI: {
  105107. pParse->zTail = &zSql[i];
  105108. /* Fall thru into the default case */
  105109. }
  105110. default: {
  105111. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  105112. lastTokenParsed = tokenType;
  105113. if( pParse->rc!=SQLITE_OK ){
  105114. goto abort_parse;
  105115. }
  105116. break;
  105117. }
  105118. }
  105119. }
  105120. abort_parse:
  105121. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  105122. if( lastTokenParsed!=TK_SEMI ){
  105123. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  105124. pParse->zTail = &zSql[i];
  105125. }
  105126. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  105127. }
  105128. #ifdef YYTRACKMAXSTACKDEPTH
  105129. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  105130. sqlite3ParserStackPeak(pEngine)
  105131. );
  105132. #endif /* YYDEBUG */
  105133. sqlite3ParserFree(pEngine, sqlite3_free);
  105134. db->lookaside.bEnabled = enableLookaside;
  105135. if( db->mallocFailed ){
  105136. pParse->rc = SQLITE_NOMEM;
  105137. }
  105138. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  105139. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  105140. }
  105141. assert( pzErrMsg!=0 );
  105142. if( pParse->zErrMsg ){
  105143. *pzErrMsg = pParse->zErrMsg;
  105144. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  105145. pParse->zErrMsg = 0;
  105146. nErr++;
  105147. }
  105148. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  105149. sqlite3VdbeDelete(pParse->pVdbe);
  105150. pParse->pVdbe = 0;
  105151. }
  105152. #ifndef SQLITE_OMIT_SHARED_CACHE
  105153. if( pParse->nested==0 ){
  105154. sqlite3DbFree(db, pParse->aTableLock);
  105155. pParse->aTableLock = 0;
  105156. pParse->nTableLock = 0;
  105157. }
  105158. #endif
  105159. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105160. sqlite3_free(pParse->apVtabLock);
  105161. #endif
  105162. if( !IN_DECLARE_VTAB ){
  105163. /* If the pParse->declareVtab flag is set, do not delete any table
  105164. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  105165. ** will take responsibility for freeing the Table structure.
  105166. */
  105167. sqlite3DeleteTable(db, pParse->pNewTable);
  105168. }
  105169. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  105170. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  105171. sqlite3DbFree(db, pParse->azVar);
  105172. sqlite3DbFree(db, pParse->aAlias);
  105173. while( pParse->pAinc ){
  105174. AutoincInfo *p = pParse->pAinc;
  105175. pParse->pAinc = p->pNext;
  105176. sqlite3DbFree(db, p);
  105177. }
  105178. while( pParse->pZombieTab ){
  105179. Table *p = pParse->pZombieTab;
  105180. pParse->pZombieTab = p->pNextZombie;
  105181. sqlite3DeleteTable(db, p);
  105182. }
  105183. if( nErr>0 && pParse->rc==SQLITE_OK ){
  105184. pParse->rc = SQLITE_ERROR;
  105185. }
  105186. return nErr;
  105187. }
  105188. /************** End of tokenize.c ********************************************/
  105189. /************** Begin file complete.c ****************************************/
  105190. /*
  105191. ** 2001 September 15
  105192. **
  105193. ** The author disclaims copyright to this source code. In place of
  105194. ** a legal notice, here is a blessing:
  105195. **
  105196. ** May you do good and not evil.
  105197. ** May you find forgiveness for yourself and forgive others.
  105198. ** May you share freely, never taking more than you give.
  105199. **
  105200. *************************************************************************
  105201. ** An tokenizer for SQL
  105202. **
  105203. ** This file contains C code that implements the sqlite3_complete() API.
  105204. ** This code used to be part of the tokenizer.c source file. But by
  105205. ** separating it out, the code will be automatically omitted from
  105206. ** static links that do not use it.
  105207. */
  105208. #ifndef SQLITE_OMIT_COMPLETE
  105209. /*
  105210. ** This is defined in tokenize.c. We just have to import the definition.
  105211. */
  105212. #ifndef SQLITE_AMALGAMATION
  105213. #ifdef SQLITE_ASCII
  105214. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  105215. #endif
  105216. #ifdef SQLITE_EBCDIC
  105217. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  105218. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  105219. #endif
  105220. #endif /* SQLITE_AMALGAMATION */
  105221. /*
  105222. ** Token types used by the sqlite3_complete() routine. See the header
  105223. ** comments on that procedure for additional information.
  105224. */
  105225. #define tkSEMI 0
  105226. #define tkWS 1
  105227. #define tkOTHER 2
  105228. #ifndef SQLITE_OMIT_TRIGGER
  105229. #define tkEXPLAIN 3
  105230. #define tkCREATE 4
  105231. #define tkTEMP 5
  105232. #define tkTRIGGER 6
  105233. #define tkEND 7
  105234. #endif
  105235. /*
  105236. ** Return TRUE if the given SQL string ends in a semicolon.
  105237. **
  105238. ** Special handling is require for CREATE TRIGGER statements.
  105239. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  105240. ** must end with ";END;".
  105241. **
  105242. ** This implementation uses a state machine with 8 states:
  105243. **
  105244. ** (0) INVALID We have not yet seen a non-whitespace character.
  105245. **
  105246. ** (1) START At the beginning or end of an SQL statement. This routine
  105247. ** returns 1 if it ends in the START state and 0 if it ends
  105248. ** in any other state.
  105249. **
  105250. ** (2) NORMAL We are in the middle of statement which ends with a single
  105251. ** semicolon.
  105252. **
  105253. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  105254. ** a statement.
  105255. **
  105256. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  105257. ** statement, possibly preceeded by EXPLAIN and/or followed by
  105258. ** TEMP or TEMPORARY
  105259. **
  105260. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  105261. ** ended by a semicolon, the keyword END, and another semicolon.
  105262. **
  105263. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  105264. ** the end of a trigger definition.
  105265. **
  105266. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  105267. ** of a trigger difinition.
  105268. **
  105269. ** Transitions between states above are determined by tokens extracted
  105270. ** from the input. The following tokens are significant:
  105271. **
  105272. ** (0) tkSEMI A semicolon.
  105273. ** (1) tkWS Whitespace.
  105274. ** (2) tkOTHER Any other SQL token.
  105275. ** (3) tkEXPLAIN The "explain" keyword.
  105276. ** (4) tkCREATE The "create" keyword.
  105277. ** (5) tkTEMP The "temp" or "temporary" keyword.
  105278. ** (6) tkTRIGGER The "trigger" keyword.
  105279. ** (7) tkEND The "end" keyword.
  105280. **
  105281. ** Whitespace never causes a state transition and is always ignored.
  105282. ** This means that a SQL string of all whitespace is invalid.
  105283. **
  105284. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  105285. ** to recognize the end of a trigger can be omitted. All we have to do
  105286. ** is look for a semicolon that is not part of an string or comment.
  105287. */
  105288. SQLITE_API int sqlite3_complete(const char *zSql){
  105289. u8 state = 0; /* Current state, using numbers defined in header comment */
  105290. u8 token; /* Value of the next token */
  105291. #ifndef SQLITE_OMIT_TRIGGER
  105292. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  105293. ** statement. This is the normal case.
  105294. */
  105295. static const u8 trans[8][8] = {
  105296. /* Token: */
  105297. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  105298. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  105299. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  105300. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  105301. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  105302. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  105303. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  105304. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  105305. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  105306. };
  105307. #else
  105308. /* If triggers are not supported by this compile then the statement machine
  105309. ** used to detect the end of a statement is much simplier
  105310. */
  105311. static const u8 trans[3][3] = {
  105312. /* Token: */
  105313. /* State: ** SEMI WS OTHER */
  105314. /* 0 INVALID: */ { 1, 0, 2, },
  105315. /* 1 START: */ { 1, 1, 2, },
  105316. /* 2 NORMAL: */ { 1, 2, 2, },
  105317. };
  105318. #endif /* SQLITE_OMIT_TRIGGER */
  105319. while( *zSql ){
  105320. switch( *zSql ){
  105321. case ';': { /* A semicolon */
  105322. token = tkSEMI;
  105323. break;
  105324. }
  105325. case ' ':
  105326. case '\r':
  105327. case '\t':
  105328. case '\n':
  105329. case '\f': { /* White space is ignored */
  105330. token = tkWS;
  105331. break;
  105332. }
  105333. case '/': { /* C-style comments */
  105334. if( zSql[1]!='*' ){
  105335. token = tkOTHER;
  105336. break;
  105337. }
  105338. zSql += 2;
  105339. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  105340. if( zSql[0]==0 ) return 0;
  105341. zSql++;
  105342. token = tkWS;
  105343. break;
  105344. }
  105345. case '-': { /* SQL-style comments from "--" to end of line */
  105346. if( zSql[1]!='-' ){
  105347. token = tkOTHER;
  105348. break;
  105349. }
  105350. while( *zSql && *zSql!='\n' ){ zSql++; }
  105351. if( *zSql==0 ) return state==1;
  105352. token = tkWS;
  105353. break;
  105354. }
  105355. case '[': { /* Microsoft-style identifiers in [...] */
  105356. zSql++;
  105357. while( *zSql && *zSql!=']' ){ zSql++; }
  105358. if( *zSql==0 ) return 0;
  105359. token = tkOTHER;
  105360. break;
  105361. }
  105362. case '`': /* Grave-accent quoted symbols used by MySQL */
  105363. case '"': /* single- and double-quoted strings */
  105364. case '\'': {
  105365. int c = *zSql;
  105366. zSql++;
  105367. while( *zSql && *zSql!=c ){ zSql++; }
  105368. if( *zSql==0 ) return 0;
  105369. token = tkOTHER;
  105370. break;
  105371. }
  105372. default: {
  105373. #ifdef SQLITE_EBCDIC
  105374. unsigned char c;
  105375. #endif
  105376. if( IdChar((u8)*zSql) ){
  105377. /* Keywords and unquoted identifiers */
  105378. int nId;
  105379. for(nId=1; IdChar(zSql[nId]); nId++){}
  105380. #ifdef SQLITE_OMIT_TRIGGER
  105381. token = tkOTHER;
  105382. #else
  105383. switch( *zSql ){
  105384. case 'c': case 'C': {
  105385. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  105386. token = tkCREATE;
  105387. }else{
  105388. token = tkOTHER;
  105389. }
  105390. break;
  105391. }
  105392. case 't': case 'T': {
  105393. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  105394. token = tkTRIGGER;
  105395. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  105396. token = tkTEMP;
  105397. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  105398. token = tkTEMP;
  105399. }else{
  105400. token = tkOTHER;
  105401. }
  105402. break;
  105403. }
  105404. case 'e': case 'E': {
  105405. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  105406. token = tkEND;
  105407. }else
  105408. #ifndef SQLITE_OMIT_EXPLAIN
  105409. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  105410. token = tkEXPLAIN;
  105411. }else
  105412. #endif
  105413. {
  105414. token = tkOTHER;
  105415. }
  105416. break;
  105417. }
  105418. default: {
  105419. token = tkOTHER;
  105420. break;
  105421. }
  105422. }
  105423. #endif /* SQLITE_OMIT_TRIGGER */
  105424. zSql += nId-1;
  105425. }else{
  105426. /* Operators and special symbols */
  105427. token = tkOTHER;
  105428. }
  105429. break;
  105430. }
  105431. }
  105432. state = trans[state][token];
  105433. zSql++;
  105434. }
  105435. return state==1;
  105436. }
  105437. #ifndef SQLITE_OMIT_UTF16
  105438. /*
  105439. ** This routine is the same as the sqlite3_complete() routine described
  105440. ** above, except that the parameter is required to be UTF-16 encoded, not
  105441. ** UTF-8.
  105442. */
  105443. SQLITE_API int sqlite3_complete16(const void *zSql){
  105444. sqlite3_value *pVal;
  105445. char const *zSql8;
  105446. int rc = SQLITE_NOMEM;
  105447. #ifndef SQLITE_OMIT_AUTOINIT
  105448. rc = sqlite3_initialize();
  105449. if( rc ) return rc;
  105450. #endif
  105451. pVal = sqlite3ValueNew(0);
  105452. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  105453. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  105454. if( zSql8 ){
  105455. rc = sqlite3_complete(zSql8);
  105456. }else{
  105457. rc = SQLITE_NOMEM;
  105458. }
  105459. sqlite3ValueFree(pVal);
  105460. return sqlite3ApiExit(0, rc);
  105461. }
  105462. #endif /* SQLITE_OMIT_UTF16 */
  105463. #endif /* SQLITE_OMIT_COMPLETE */
  105464. /************** End of complete.c ********************************************/
  105465. /************** Begin file main.c ********************************************/
  105466. /*
  105467. ** 2001 September 15
  105468. **
  105469. ** The author disclaims copyright to this source code. In place of
  105470. ** a legal notice, here is a blessing:
  105471. **
  105472. ** May you do good and not evil.
  105473. ** May you find forgiveness for yourself and forgive others.
  105474. ** May you share freely, never taking more than you give.
  105475. **
  105476. *************************************************************************
  105477. ** Main file for the SQLite library. The routines in this file
  105478. ** implement the programmer interface to the library. Routines in
  105479. ** other files are for internal use by SQLite and should not be
  105480. ** accessed by users of the library.
  105481. */
  105482. #ifdef SQLITE_ENABLE_FTS3
  105483. /************** Include fts3.h in the middle of main.c ***********************/
  105484. /************** Begin file fts3.h ********************************************/
  105485. /*
  105486. ** 2006 Oct 10
  105487. **
  105488. ** The author disclaims copyright to this source code. In place of
  105489. ** a legal notice, here is a blessing:
  105490. **
  105491. ** May you do good and not evil.
  105492. ** May you find forgiveness for yourself and forgive others.
  105493. ** May you share freely, never taking more than you give.
  105494. **
  105495. ******************************************************************************
  105496. **
  105497. ** This header file is used by programs that want to link against the
  105498. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  105499. */
  105500. #if 0
  105501. extern "C" {
  105502. #endif /* __cplusplus */
  105503. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  105504. #if 0
  105505. } /* extern "C" */
  105506. #endif /* __cplusplus */
  105507. /************** End of fts3.h ************************************************/
  105508. /************** Continuing where we left off in main.c ***********************/
  105509. #endif
  105510. #ifdef SQLITE_ENABLE_RTREE
  105511. /************** Include rtree.h in the middle of main.c **********************/
  105512. /************** Begin file rtree.h *******************************************/
  105513. /*
  105514. ** 2008 May 26
  105515. **
  105516. ** The author disclaims copyright to this source code. In place of
  105517. ** a legal notice, here is a blessing:
  105518. **
  105519. ** May you do good and not evil.
  105520. ** May you find forgiveness for yourself and forgive others.
  105521. ** May you share freely, never taking more than you give.
  105522. **
  105523. ******************************************************************************
  105524. **
  105525. ** This header file is used by programs that want to link against the
  105526. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  105527. */
  105528. #if 0
  105529. extern "C" {
  105530. #endif /* __cplusplus */
  105531. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  105532. #if 0
  105533. } /* extern "C" */
  105534. #endif /* __cplusplus */
  105535. /************** End of rtree.h ***********************************************/
  105536. /************** Continuing where we left off in main.c ***********************/
  105537. #endif
  105538. #ifdef SQLITE_ENABLE_ICU
  105539. /************** Include sqliteicu.h in the middle of main.c ******************/
  105540. /************** Begin file sqliteicu.h ***************************************/
  105541. /*
  105542. ** 2008 May 26
  105543. **
  105544. ** The author disclaims copyright to this source code. In place of
  105545. ** a legal notice, here is a blessing:
  105546. **
  105547. ** May you do good and not evil.
  105548. ** May you find forgiveness for yourself and forgive others.
  105549. ** May you share freely, never taking more than you give.
  105550. **
  105551. ******************************************************************************
  105552. **
  105553. ** This header file is used by programs that want to link against the
  105554. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  105555. */
  105556. #if 0
  105557. extern "C" {
  105558. #endif /* __cplusplus */
  105559. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  105560. #if 0
  105561. } /* extern "C" */
  105562. #endif /* __cplusplus */
  105563. /************** End of sqliteicu.h *******************************************/
  105564. /************** Continuing where we left off in main.c ***********************/
  105565. #endif
  105566. #ifndef SQLITE_AMALGAMATION
  105567. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  105568. ** contains the text of SQLITE_VERSION macro.
  105569. */
  105570. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  105571. #endif
  105572. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  105573. ** a pointer to the to the sqlite3_version[] string constant.
  105574. */
  105575. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  105576. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  105577. ** pointer to a string constant whose value is the same as the
  105578. ** SQLITE_SOURCE_ID C preprocessor macro.
  105579. */
  105580. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  105581. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  105582. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  105583. */
  105584. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  105585. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  105586. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  105587. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  105588. */
  105589. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  105590. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  105591. /*
  105592. ** If the following function pointer is not NULL and if
  105593. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  105594. ** I/O active are written using this function. These messages
  105595. ** are intended for debugging activity only.
  105596. */
  105597. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  105598. #endif
  105599. /*
  105600. ** If the following global variable points to a string which is the
  105601. ** name of a directory, then that directory will be used to store
  105602. ** temporary files.
  105603. **
  105604. ** See also the "PRAGMA temp_store_directory" SQL command.
  105605. */
  105606. SQLITE_API char *sqlite3_temp_directory = 0;
  105607. /*
  105608. ** If the following global variable points to a string which is the
  105609. ** name of a directory, then that directory will be used to store
  105610. ** all database files specified with a relative pathname.
  105611. **
  105612. ** See also the "PRAGMA data_store_directory" SQL command.
  105613. */
  105614. SQLITE_API char *sqlite3_data_directory = 0;
  105615. /*
  105616. ** Initialize SQLite.
  105617. **
  105618. ** This routine must be called to initialize the memory allocation,
  105619. ** VFS, and mutex subsystems prior to doing any serious work with
  105620. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  105621. ** this routine will be called automatically by key routines such as
  105622. ** sqlite3_open().
  105623. **
  105624. ** This routine is a no-op except on its very first call for the process,
  105625. ** or for the first call after a call to sqlite3_shutdown.
  105626. **
  105627. ** The first thread to call this routine runs the initialization to
  105628. ** completion. If subsequent threads call this routine before the first
  105629. ** thread has finished the initialization process, then the subsequent
  105630. ** threads must block until the first thread finishes with the initialization.
  105631. **
  105632. ** The first thread might call this routine recursively. Recursive
  105633. ** calls to this routine should not block, of course. Otherwise the
  105634. ** initialization process would never complete.
  105635. **
  105636. ** Let X be the first thread to enter this routine. Let Y be some other
  105637. ** thread. Then while the initial invocation of this routine by X is
  105638. ** incomplete, it is required that:
  105639. **
  105640. ** * Calls to this routine from Y must block until the outer-most
  105641. ** call by X completes.
  105642. **
  105643. ** * Recursive calls to this routine from thread X return immediately
  105644. ** without blocking.
  105645. */
  105646. SQLITE_API int sqlite3_initialize(void){
  105647. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  105648. int rc; /* Result code */
  105649. #ifdef SQLITE_OMIT_WSD
  105650. rc = sqlite3_wsd_init(4096, 24);
  105651. if( rc!=SQLITE_OK ){
  105652. return rc;
  105653. }
  105654. #endif
  105655. /* If SQLite is already completely initialized, then this call
  105656. ** to sqlite3_initialize() should be a no-op. But the initialization
  105657. ** must be complete. So isInit must not be set until the very end
  105658. ** of this routine.
  105659. */
  105660. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  105661. #ifdef SQLITE_ENABLE_SQLLOG
  105662. {
  105663. extern void sqlite3_init_sqllog(void);
  105664. sqlite3_init_sqllog();
  105665. }
  105666. #endif
  105667. /* Make sure the mutex subsystem is initialized. If unable to
  105668. ** initialize the mutex subsystem, return early with the error.
  105669. ** If the system is so sick that we are unable to allocate a mutex,
  105670. ** there is not much SQLite is going to be able to do.
  105671. **
  105672. ** The mutex subsystem must take care of serializing its own
  105673. ** initialization.
  105674. */
  105675. rc = sqlite3MutexInit();
  105676. if( rc ) return rc;
  105677. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  105678. ** This operation is protected by the STATIC_MASTER mutex. Note that
  105679. ** MutexAlloc() is called for a static mutex prior to initializing the
  105680. ** malloc subsystem - this implies that the allocation of a static
  105681. ** mutex must not require support from the malloc subsystem.
  105682. */
  105683. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  105684. sqlite3_mutex_enter(pMaster);
  105685. sqlite3GlobalConfig.isMutexInit = 1;
  105686. if( !sqlite3GlobalConfig.isMallocInit ){
  105687. rc = sqlite3MallocInit();
  105688. }
  105689. if( rc==SQLITE_OK ){
  105690. sqlite3GlobalConfig.isMallocInit = 1;
  105691. if( !sqlite3GlobalConfig.pInitMutex ){
  105692. sqlite3GlobalConfig.pInitMutex =
  105693. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  105694. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  105695. rc = SQLITE_NOMEM;
  105696. }
  105697. }
  105698. }
  105699. if( rc==SQLITE_OK ){
  105700. sqlite3GlobalConfig.nRefInitMutex++;
  105701. }
  105702. sqlite3_mutex_leave(pMaster);
  105703. /* If rc is not SQLITE_OK at this point, then either the malloc
  105704. ** subsystem could not be initialized or the system failed to allocate
  105705. ** the pInitMutex mutex. Return an error in either case. */
  105706. if( rc!=SQLITE_OK ){
  105707. return rc;
  105708. }
  105709. /* Do the rest of the initialization under the recursive mutex so
  105710. ** that we will be able to handle recursive calls into
  105711. ** sqlite3_initialize(). The recursive calls normally come through
  105712. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  105713. ** recursive calls might also be possible.
  105714. **
  105715. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  105716. ** to the xInit method, so the xInit method need not be threadsafe.
  105717. **
  105718. ** The following mutex is what serializes access to the appdef pcache xInit
  105719. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  105720. ** call to sqlite3PcacheInitialize().
  105721. */
  105722. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  105723. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  105724. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  105725. sqlite3GlobalConfig.inProgress = 1;
  105726. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  105727. sqlite3RegisterGlobalFunctions();
  105728. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  105729. rc = sqlite3PcacheInitialize();
  105730. }
  105731. if( rc==SQLITE_OK ){
  105732. sqlite3GlobalConfig.isPCacheInit = 1;
  105733. rc = sqlite3OsInit();
  105734. }
  105735. if( rc==SQLITE_OK ){
  105736. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  105737. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  105738. sqlite3GlobalConfig.isInit = 1;
  105739. }
  105740. sqlite3GlobalConfig.inProgress = 0;
  105741. }
  105742. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  105743. /* Go back under the static mutex and clean up the recursive
  105744. ** mutex to prevent a resource leak.
  105745. */
  105746. sqlite3_mutex_enter(pMaster);
  105747. sqlite3GlobalConfig.nRefInitMutex--;
  105748. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  105749. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  105750. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  105751. sqlite3GlobalConfig.pInitMutex = 0;
  105752. }
  105753. sqlite3_mutex_leave(pMaster);
  105754. /* The following is just a sanity check to make sure SQLite has
  105755. ** been compiled correctly. It is important to run this code, but
  105756. ** we don't want to run it too often and soak up CPU cycles for no
  105757. ** reason. So we run it once during initialization.
  105758. */
  105759. #ifndef NDEBUG
  105760. #ifndef SQLITE_OMIT_FLOATING_POINT
  105761. /* This section of code's only "output" is via assert() statements. */
  105762. if ( rc==SQLITE_OK ){
  105763. u64 x = (((u64)1)<<63)-1;
  105764. double y;
  105765. assert(sizeof(x)==8);
  105766. assert(sizeof(x)==sizeof(y));
  105767. memcpy(&y, &x, 8);
  105768. assert( sqlite3IsNaN(y) );
  105769. }
  105770. #endif
  105771. #endif
  105772. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  105773. ** compile-time option.
  105774. */
  105775. #ifdef SQLITE_EXTRA_INIT
  105776. if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
  105777. int SQLITE_EXTRA_INIT(const char*);
  105778. rc = SQLITE_EXTRA_INIT(0);
  105779. }
  105780. #endif
  105781. return rc;
  105782. }
  105783. /*
  105784. ** Undo the effects of sqlite3_initialize(). Must not be called while
  105785. ** there are outstanding database connections or memory allocations or
  105786. ** while any part of SQLite is otherwise in use in any thread. This
  105787. ** routine is not threadsafe. But it is safe to invoke this routine
  105788. ** on when SQLite is already shut down. If SQLite is already shut down
  105789. ** when this routine is invoked, then this routine is a harmless no-op.
  105790. */
  105791. SQLITE_API int sqlite3_shutdown(void){
  105792. if( sqlite3GlobalConfig.isInit ){
  105793. #ifdef SQLITE_EXTRA_SHUTDOWN
  105794. void SQLITE_EXTRA_SHUTDOWN(void);
  105795. SQLITE_EXTRA_SHUTDOWN();
  105796. #endif
  105797. sqlite3_os_end();
  105798. sqlite3_reset_auto_extension();
  105799. sqlite3GlobalConfig.isInit = 0;
  105800. }
  105801. if( sqlite3GlobalConfig.isPCacheInit ){
  105802. sqlite3PcacheShutdown();
  105803. sqlite3GlobalConfig.isPCacheInit = 0;
  105804. }
  105805. if( sqlite3GlobalConfig.isMallocInit ){
  105806. sqlite3MallocEnd();
  105807. sqlite3GlobalConfig.isMallocInit = 0;
  105808. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  105809. /* The heap subsystem has now been shutdown and these values are supposed
  105810. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  105811. ** which would rely on that heap subsystem; therefore, make sure these
  105812. ** values cannot refer to heap memory that was just invalidated when the
  105813. ** heap subsystem was shutdown. This is only done if the current call to
  105814. ** this function resulted in the heap subsystem actually being shutdown.
  105815. */
  105816. sqlite3_data_directory = 0;
  105817. sqlite3_temp_directory = 0;
  105818. #endif
  105819. }
  105820. if( sqlite3GlobalConfig.isMutexInit ){
  105821. sqlite3MutexEnd();
  105822. sqlite3GlobalConfig.isMutexInit = 0;
  105823. }
  105824. return SQLITE_OK;
  105825. }
  105826. /*
  105827. ** This API allows applications to modify the global configuration of
  105828. ** the SQLite library at run-time.
  105829. **
  105830. ** This routine should only be called when there are no outstanding
  105831. ** database connections or memory allocations. This routine is not
  105832. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  105833. ** behavior.
  105834. */
  105835. SQLITE_API int sqlite3_config(int op, ...){
  105836. va_list ap;
  105837. int rc = SQLITE_OK;
  105838. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  105839. ** the SQLite library is in use. */
  105840. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  105841. va_start(ap, op);
  105842. switch( op ){
  105843. /* Mutex configuration options are only available in a threadsafe
  105844. ** compile.
  105845. */
  105846. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  105847. case SQLITE_CONFIG_SINGLETHREAD: {
  105848. /* Disable all mutexing */
  105849. sqlite3GlobalConfig.bCoreMutex = 0;
  105850. sqlite3GlobalConfig.bFullMutex = 0;
  105851. break;
  105852. }
  105853. case SQLITE_CONFIG_MULTITHREAD: {
  105854. /* Disable mutexing of database connections */
  105855. /* Enable mutexing of core data structures */
  105856. sqlite3GlobalConfig.bCoreMutex = 1;
  105857. sqlite3GlobalConfig.bFullMutex = 0;
  105858. break;
  105859. }
  105860. case SQLITE_CONFIG_SERIALIZED: {
  105861. /* Enable all mutexing */
  105862. sqlite3GlobalConfig.bCoreMutex = 1;
  105863. sqlite3GlobalConfig.bFullMutex = 1;
  105864. break;
  105865. }
  105866. case SQLITE_CONFIG_MUTEX: {
  105867. /* Specify an alternative mutex implementation */
  105868. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  105869. break;
  105870. }
  105871. case SQLITE_CONFIG_GETMUTEX: {
  105872. /* Retrieve the current mutex implementation */
  105873. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  105874. break;
  105875. }
  105876. #endif
  105877. case SQLITE_CONFIG_MALLOC: {
  105878. /* Specify an alternative malloc implementation */
  105879. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  105880. break;
  105881. }
  105882. case SQLITE_CONFIG_GETMALLOC: {
  105883. /* Retrieve the current malloc() implementation */
  105884. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  105885. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  105886. break;
  105887. }
  105888. case SQLITE_CONFIG_MEMSTATUS: {
  105889. /* Enable or disable the malloc status collection */
  105890. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  105891. break;
  105892. }
  105893. case SQLITE_CONFIG_SCRATCH: {
  105894. /* Designate a buffer for scratch memory space */
  105895. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  105896. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  105897. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  105898. break;
  105899. }
  105900. case SQLITE_CONFIG_PAGECACHE: {
  105901. /* Designate a buffer for page cache memory space */
  105902. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  105903. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  105904. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  105905. break;
  105906. }
  105907. case SQLITE_CONFIG_PCACHE: {
  105908. /* no-op */
  105909. break;
  105910. }
  105911. case SQLITE_CONFIG_GETPCACHE: {
  105912. /* now an error */
  105913. rc = SQLITE_ERROR;
  105914. break;
  105915. }
  105916. case SQLITE_CONFIG_PCACHE2: {
  105917. /* Specify an alternative page cache implementation */
  105918. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  105919. break;
  105920. }
  105921. case SQLITE_CONFIG_GETPCACHE2: {
  105922. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  105923. sqlite3PCacheSetDefault();
  105924. }
  105925. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  105926. break;
  105927. }
  105928. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  105929. case SQLITE_CONFIG_HEAP: {
  105930. /* Designate a buffer for heap memory space */
  105931. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  105932. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  105933. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  105934. if( sqlite3GlobalConfig.mnReq<1 ){
  105935. sqlite3GlobalConfig.mnReq = 1;
  105936. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  105937. /* cap min request size at 2^12 */
  105938. sqlite3GlobalConfig.mnReq = (1<<12);
  105939. }
  105940. if( sqlite3GlobalConfig.pHeap==0 ){
  105941. /* If the heap pointer is NULL, then restore the malloc implementation
  105942. ** back to NULL pointers too. This will cause the malloc to go
  105943. ** back to its default implementation when sqlite3_initialize() is
  105944. ** run.
  105945. */
  105946. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  105947. }else{
  105948. /* The heap pointer is not NULL, then install one of the
  105949. ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
  105950. ** ENABLE_MEMSYS5 is defined, return an error.
  105951. */
  105952. #ifdef SQLITE_ENABLE_MEMSYS3
  105953. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  105954. #endif
  105955. #ifdef SQLITE_ENABLE_MEMSYS5
  105956. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  105957. #endif
  105958. }
  105959. break;
  105960. }
  105961. #endif
  105962. case SQLITE_CONFIG_LOOKASIDE: {
  105963. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  105964. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  105965. break;
  105966. }
  105967. /* Record a pointer to the logger funcction and its first argument.
  105968. ** The default is NULL. Logging is disabled if the function pointer is
  105969. ** NULL.
  105970. */
  105971. case SQLITE_CONFIG_LOG: {
  105972. /* MSVC is picky about pulling func ptrs from va lists.
  105973. ** http://support.microsoft.com/kb/47961
  105974. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  105975. */
  105976. typedef void(*LOGFUNC_t)(void*,int,const char*);
  105977. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  105978. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  105979. break;
  105980. }
  105981. case SQLITE_CONFIG_URI: {
  105982. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  105983. break;
  105984. }
  105985. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  105986. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  105987. break;
  105988. }
  105989. #ifdef SQLITE_ENABLE_SQLLOG
  105990. case SQLITE_CONFIG_SQLLOG: {
  105991. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  105992. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  105993. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  105994. break;
  105995. }
  105996. #endif
  105997. default: {
  105998. rc = SQLITE_ERROR;
  105999. break;
  106000. }
  106001. }
  106002. va_end(ap);
  106003. return rc;
  106004. }
  106005. /*
  106006. ** Set up the lookaside buffers for a database connection.
  106007. ** Return SQLITE_OK on success.
  106008. ** If lookaside is already active, return SQLITE_BUSY.
  106009. **
  106010. ** The sz parameter is the number of bytes in each lookaside slot.
  106011. ** The cnt parameter is the number of slots. If pStart is NULL the
  106012. ** space for the lookaside memory is obtained from sqlite3_malloc().
  106013. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  106014. ** the lookaside memory.
  106015. */
  106016. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  106017. void *pStart;
  106018. if( db->lookaside.nOut ){
  106019. return SQLITE_BUSY;
  106020. }
  106021. /* Free any existing lookaside buffer for this handle before
  106022. ** allocating a new one so we don't have to have space for
  106023. ** both at the same time.
  106024. */
  106025. if( db->lookaside.bMalloced ){
  106026. sqlite3_free(db->lookaside.pStart);
  106027. }
  106028. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  106029. ** than a pointer to be useful.
  106030. */
  106031. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  106032. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  106033. if( cnt<0 ) cnt = 0;
  106034. if( sz==0 || cnt==0 ){
  106035. sz = 0;
  106036. pStart = 0;
  106037. }else if( pBuf==0 ){
  106038. sqlite3BeginBenignMalloc();
  106039. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  106040. sqlite3EndBenignMalloc();
  106041. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  106042. }else{
  106043. pStart = pBuf;
  106044. }
  106045. db->lookaside.pStart = pStart;
  106046. db->lookaside.pFree = 0;
  106047. db->lookaside.sz = (u16)sz;
  106048. if( pStart ){
  106049. int i;
  106050. LookasideSlot *p;
  106051. assert( sz > (int)sizeof(LookasideSlot*) );
  106052. p = (LookasideSlot*)pStart;
  106053. for(i=cnt-1; i>=0; i--){
  106054. p->pNext = db->lookaside.pFree;
  106055. db->lookaside.pFree = p;
  106056. p = (LookasideSlot*)&((u8*)p)[sz];
  106057. }
  106058. db->lookaside.pEnd = p;
  106059. db->lookaside.bEnabled = 1;
  106060. db->lookaside.bMalloced = pBuf==0 ?1:0;
  106061. }else{
  106062. db->lookaside.pEnd = 0;
  106063. db->lookaside.bEnabled = 0;
  106064. db->lookaside.bMalloced = 0;
  106065. }
  106066. return SQLITE_OK;
  106067. }
  106068. /*
  106069. ** Return the mutex associated with a database connection.
  106070. */
  106071. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  106072. return db->mutex;
  106073. }
  106074. /*
  106075. ** Free up as much memory as we can from the given database
  106076. ** connection.
  106077. */
  106078. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  106079. int i;
  106080. sqlite3_mutex_enter(db->mutex);
  106081. sqlite3BtreeEnterAll(db);
  106082. for(i=0; i<db->nDb; i++){
  106083. Btree *pBt = db->aDb[i].pBt;
  106084. if( pBt ){
  106085. Pager *pPager = sqlite3BtreePager(pBt);
  106086. sqlite3PagerShrink(pPager);
  106087. }
  106088. }
  106089. sqlite3BtreeLeaveAll(db);
  106090. sqlite3_mutex_leave(db->mutex);
  106091. return SQLITE_OK;
  106092. }
  106093. /*
  106094. ** Configuration settings for an individual database connection
  106095. */
  106096. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  106097. va_list ap;
  106098. int rc;
  106099. va_start(ap, op);
  106100. switch( op ){
  106101. case SQLITE_DBCONFIG_LOOKASIDE: {
  106102. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  106103. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  106104. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  106105. rc = setupLookaside(db, pBuf, sz, cnt);
  106106. break;
  106107. }
  106108. default: {
  106109. static const struct {
  106110. int op; /* The opcode */
  106111. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  106112. } aFlagOp[] = {
  106113. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  106114. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  106115. };
  106116. unsigned int i;
  106117. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  106118. for(i=0; i<ArraySize(aFlagOp); i++){
  106119. if( aFlagOp[i].op==op ){
  106120. int onoff = va_arg(ap, int);
  106121. int *pRes = va_arg(ap, int*);
  106122. int oldFlags = db->flags;
  106123. if( onoff>0 ){
  106124. db->flags |= aFlagOp[i].mask;
  106125. }else if( onoff==0 ){
  106126. db->flags &= ~aFlagOp[i].mask;
  106127. }
  106128. if( oldFlags!=db->flags ){
  106129. sqlite3ExpirePreparedStatements(db);
  106130. }
  106131. if( pRes ){
  106132. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  106133. }
  106134. rc = SQLITE_OK;
  106135. break;
  106136. }
  106137. }
  106138. break;
  106139. }
  106140. }
  106141. va_end(ap);
  106142. return rc;
  106143. }
  106144. /*
  106145. ** Return true if the buffer z[0..n-1] contains all spaces.
  106146. */
  106147. static int allSpaces(const char *z, int n){
  106148. while( n>0 && z[n-1]==' ' ){ n--; }
  106149. return n==0;
  106150. }
  106151. /*
  106152. ** This is the default collating function named "BINARY" which is always
  106153. ** available.
  106154. **
  106155. ** If the padFlag argument is not NULL then space padding at the end
  106156. ** of strings is ignored. This implements the RTRIM collation.
  106157. */
  106158. static int binCollFunc(
  106159. void *padFlag,
  106160. int nKey1, const void *pKey1,
  106161. int nKey2, const void *pKey2
  106162. ){
  106163. int rc, n;
  106164. n = nKey1<nKey2 ? nKey1 : nKey2;
  106165. rc = memcmp(pKey1, pKey2, n);
  106166. if( rc==0 ){
  106167. if( padFlag
  106168. && allSpaces(((char*)pKey1)+n, nKey1-n)
  106169. && allSpaces(((char*)pKey2)+n, nKey2-n)
  106170. ){
  106171. /* Leave rc unchanged at 0 */
  106172. }else{
  106173. rc = nKey1 - nKey2;
  106174. }
  106175. }
  106176. return rc;
  106177. }
  106178. /*
  106179. ** Another built-in collating sequence: NOCASE.
  106180. **
  106181. ** This collating sequence is intended to be used for "case independant
  106182. ** comparison". SQLite's knowledge of upper and lower case equivalents
  106183. ** extends only to the 26 characters used in the English language.
  106184. **
  106185. ** At the moment there is only a UTF-8 implementation.
  106186. */
  106187. static int nocaseCollatingFunc(
  106188. void *NotUsed,
  106189. int nKey1, const void *pKey1,
  106190. int nKey2, const void *pKey2
  106191. ){
  106192. int r = sqlite3StrNICmp(
  106193. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  106194. UNUSED_PARAMETER(NotUsed);
  106195. if( 0==r ){
  106196. r = nKey1-nKey2;
  106197. }
  106198. return r;
  106199. }
  106200. /*
  106201. ** Return the ROWID of the most recent insert
  106202. */
  106203. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  106204. return db->lastRowid;
  106205. }
  106206. /*
  106207. ** Return the number of changes in the most recent call to sqlite3_exec().
  106208. */
  106209. SQLITE_API int sqlite3_changes(sqlite3 *db){
  106210. return db->nChange;
  106211. }
  106212. /*
  106213. ** Return the number of changes since the database handle was opened.
  106214. */
  106215. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  106216. return db->nTotalChange;
  106217. }
  106218. /*
  106219. ** Close all open savepoints. This function only manipulates fields of the
  106220. ** database handle object, it does not close any savepoints that may be open
  106221. ** at the b-tree/pager level.
  106222. */
  106223. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  106224. while( db->pSavepoint ){
  106225. Savepoint *pTmp = db->pSavepoint;
  106226. db->pSavepoint = pTmp->pNext;
  106227. sqlite3DbFree(db, pTmp);
  106228. }
  106229. db->nSavepoint = 0;
  106230. db->nStatement = 0;
  106231. db->isTransactionSavepoint = 0;
  106232. }
  106233. /*
  106234. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  106235. ** if this is not the last copy of the function, do not invoke it. Multiple
  106236. ** copies of a single function are created when create_function() is called
  106237. ** with SQLITE_ANY as the encoding.
  106238. */
  106239. static void functionDestroy(sqlite3 *db, FuncDef *p){
  106240. FuncDestructor *pDestructor = p->pDestructor;
  106241. if( pDestructor ){
  106242. pDestructor->nRef--;
  106243. if( pDestructor->nRef==0 ){
  106244. pDestructor->xDestroy(pDestructor->pUserData);
  106245. sqlite3DbFree(db, pDestructor);
  106246. }
  106247. }
  106248. }
  106249. /*
  106250. ** Disconnect all sqlite3_vtab objects that belong to database connection
  106251. ** db. This is called when db is being closed.
  106252. */
  106253. static void disconnectAllVtab(sqlite3 *db){
  106254. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106255. int i;
  106256. sqlite3BtreeEnterAll(db);
  106257. for(i=0; i<db->nDb; i++){
  106258. Schema *pSchema = db->aDb[i].pSchema;
  106259. if( db->aDb[i].pSchema ){
  106260. HashElem *p;
  106261. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  106262. Table *pTab = (Table *)sqliteHashData(p);
  106263. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  106264. }
  106265. }
  106266. }
  106267. sqlite3BtreeLeaveAll(db);
  106268. #else
  106269. UNUSED_PARAMETER(db);
  106270. #endif
  106271. }
  106272. /*
  106273. ** Return TRUE if database connection db has unfinalized prepared
  106274. ** statements or unfinished sqlite3_backup objects.
  106275. */
  106276. static int connectionIsBusy(sqlite3 *db){
  106277. int j;
  106278. assert( sqlite3_mutex_held(db->mutex) );
  106279. if( db->pVdbe ) return 1;
  106280. for(j=0; j<db->nDb; j++){
  106281. Btree *pBt = db->aDb[j].pBt;
  106282. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  106283. }
  106284. return 0;
  106285. }
  106286. /*
  106287. ** Close an existing SQLite database
  106288. */
  106289. static int sqlite3Close(sqlite3 *db, int forceZombie){
  106290. if( !db ){
  106291. return SQLITE_OK;
  106292. }
  106293. if( !sqlite3SafetyCheckSickOrOk(db) ){
  106294. return SQLITE_MISUSE_BKPT;
  106295. }
  106296. sqlite3_mutex_enter(db->mutex);
  106297. /* Force xDisconnect calls on all virtual tables */
  106298. disconnectAllVtab(db);
  106299. /* If a transaction is open, the disconnectAllVtab() call above
  106300. ** will not have called the xDisconnect() method on any virtual
  106301. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  106302. ** call will do so. We need to do this before the check for active
  106303. ** SQL statements below, as the v-table implementation may be storing
  106304. ** some prepared statements internally.
  106305. */
  106306. sqlite3VtabRollback(db);
  106307. /* Legacy behavior (sqlite3_close() behavior) is to return
  106308. ** SQLITE_BUSY if the connection can not be closed immediately.
  106309. */
  106310. if( !forceZombie && connectionIsBusy(db) ){
  106311. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  106312. "statements or unfinished backups");
  106313. sqlite3_mutex_leave(db->mutex);
  106314. return SQLITE_BUSY;
  106315. }
  106316. #ifdef SQLITE_ENABLE_SQLLOG
  106317. if( sqlite3GlobalConfig.xSqllog ){
  106318. /* Closing the handle. Fourth parameter is passed the value 2. */
  106319. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  106320. }
  106321. #endif
  106322. /* Convert the connection into a zombie and then close it.
  106323. */
  106324. db->magic = SQLITE_MAGIC_ZOMBIE;
  106325. sqlite3LeaveMutexAndCloseZombie(db);
  106326. return SQLITE_OK;
  106327. }
  106328. /*
  106329. ** Two variations on the public interface for closing a database
  106330. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  106331. ** leaves the connection option if there are unfinalized prepared
  106332. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  106333. ** version forces the connection to become a zombie if there are
  106334. ** unclosed resources, and arranges for deallocation when the last
  106335. ** prepare statement or sqlite3_backup closes.
  106336. */
  106337. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  106338. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  106339. /*
  106340. ** Close the mutex on database connection db.
  106341. **
  106342. ** Furthermore, if database connection db is a zombie (meaning that there
  106343. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  106344. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  106345. ** finished, then free all resources.
  106346. */
  106347. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  106348. HashElem *i; /* Hash table iterator */
  106349. int j;
  106350. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  106351. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  106352. ** then just leave the mutex and return.
  106353. */
  106354. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  106355. sqlite3_mutex_leave(db->mutex);
  106356. return;
  106357. }
  106358. /* If we reach this point, it means that the database connection has
  106359. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  106360. ** pased to sqlite3_close (meaning that it is a zombie). Therefore,
  106361. ** go ahead and free all resources.
  106362. */
  106363. /* Free any outstanding Savepoint structures. */
  106364. sqlite3CloseSavepoints(db);
  106365. /* Close all database connections */
  106366. for(j=0; j<db->nDb; j++){
  106367. struct Db *pDb = &db->aDb[j];
  106368. if( pDb->pBt ){
  106369. sqlite3BtreeClose(pDb->pBt);
  106370. pDb->pBt = 0;
  106371. if( j!=1 ){
  106372. pDb->pSchema = 0;
  106373. }
  106374. }
  106375. }
  106376. /* Clear the TEMP schema separately and last */
  106377. if( db->aDb[1].pSchema ){
  106378. sqlite3SchemaClear(db->aDb[1].pSchema);
  106379. }
  106380. sqlite3VtabUnlockList(db);
  106381. /* Free up the array of auxiliary databases */
  106382. sqlite3CollapseDatabaseArray(db);
  106383. assert( db->nDb<=2 );
  106384. assert( db->aDb==db->aDbStatic );
  106385. /* Tell the code in notify.c that the connection no longer holds any
  106386. ** locks and does not require any further unlock-notify callbacks.
  106387. */
  106388. sqlite3ConnectionClosed(db);
  106389. for(j=0; j<ArraySize(db->aFunc.a); j++){
  106390. FuncDef *pNext, *pHash, *p;
  106391. for(p=db->aFunc.a[j]; p; p=pHash){
  106392. pHash = p->pHash;
  106393. while( p ){
  106394. functionDestroy(db, p);
  106395. pNext = p->pNext;
  106396. sqlite3DbFree(db, p);
  106397. p = pNext;
  106398. }
  106399. }
  106400. }
  106401. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  106402. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  106403. /* Invoke any destructors registered for collation sequence user data. */
  106404. for(j=0; j<3; j++){
  106405. if( pColl[j].xDel ){
  106406. pColl[j].xDel(pColl[j].pUser);
  106407. }
  106408. }
  106409. sqlite3DbFree(db, pColl);
  106410. }
  106411. sqlite3HashClear(&db->aCollSeq);
  106412. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106413. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  106414. Module *pMod = (Module *)sqliteHashData(i);
  106415. if( pMod->xDestroy ){
  106416. pMod->xDestroy(pMod->pAux);
  106417. }
  106418. sqlite3DbFree(db, pMod);
  106419. }
  106420. sqlite3HashClear(&db->aModule);
  106421. #endif
  106422. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  106423. if( db->pErr ){
  106424. sqlite3ValueFree(db->pErr);
  106425. }
  106426. sqlite3CloseExtensions(db);
  106427. db->magic = SQLITE_MAGIC_ERROR;
  106428. /* The temp-database schema is allocated differently from the other schema
  106429. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  106430. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  106431. ** the same sqliteMalloc() as the one that allocates the database
  106432. ** structure?
  106433. */
  106434. sqlite3DbFree(db, db->aDb[1].pSchema);
  106435. sqlite3_mutex_leave(db->mutex);
  106436. db->magic = SQLITE_MAGIC_CLOSED;
  106437. sqlite3_mutex_free(db->mutex);
  106438. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  106439. if( db->lookaside.bMalloced ){
  106440. sqlite3_free(db->lookaside.pStart);
  106441. }
  106442. sqlite3_free(db);
  106443. }
  106444. /*
  106445. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  106446. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  106447. ** breaker") and made to return tripCode if there are any further
  106448. ** attempts to use that cursor.
  106449. */
  106450. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  106451. int i;
  106452. int inTrans = 0;
  106453. assert( sqlite3_mutex_held(db->mutex) );
  106454. sqlite3BeginBenignMalloc();
  106455. for(i=0; i<db->nDb; i++){
  106456. Btree *p = db->aDb[i].pBt;
  106457. if( p ){
  106458. if( sqlite3BtreeIsInTrans(p) ){
  106459. inTrans = 1;
  106460. }
  106461. sqlite3BtreeRollback(p, tripCode);
  106462. db->aDb[i].inTrans = 0;
  106463. }
  106464. }
  106465. sqlite3VtabRollback(db);
  106466. sqlite3EndBenignMalloc();
  106467. if( db->flags&SQLITE_InternChanges ){
  106468. sqlite3ExpirePreparedStatements(db);
  106469. sqlite3ResetAllSchemasOfConnection(db);
  106470. }
  106471. /* Any deferred constraint violations have now been resolved. */
  106472. db->nDeferredCons = 0;
  106473. /* If one has been configured, invoke the rollback-hook callback */
  106474. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  106475. db->xRollbackCallback(db->pRollbackArg);
  106476. }
  106477. }
  106478. /*
  106479. ** Return a static string that describes the kind of error specified in the
  106480. ** argument.
  106481. */
  106482. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  106483. static const char* const aMsg[] = {
  106484. /* SQLITE_OK */ "not an error",
  106485. /* SQLITE_ERROR */ "SQL logic error or missing database",
  106486. /* SQLITE_INTERNAL */ 0,
  106487. /* SQLITE_PERM */ "access permission denied",
  106488. /* SQLITE_ABORT */ "callback requested query abort",
  106489. /* SQLITE_BUSY */ "database is locked",
  106490. /* SQLITE_LOCKED */ "database table is locked",
  106491. /* SQLITE_NOMEM */ "out of memory",
  106492. /* SQLITE_READONLY */ "attempt to write a readonly database",
  106493. /* SQLITE_INTERRUPT */ "interrupted",
  106494. /* SQLITE_IOERR */ "disk I/O error",
  106495. /* SQLITE_CORRUPT */ "database disk image is malformed",
  106496. /* SQLITE_NOTFOUND */ "unknown operation",
  106497. /* SQLITE_FULL */ "database or disk is full",
  106498. /* SQLITE_CANTOPEN */ "unable to open database file",
  106499. /* SQLITE_PROTOCOL */ "locking protocol",
  106500. /* SQLITE_EMPTY */ "table contains no data",
  106501. /* SQLITE_SCHEMA */ "database schema has changed",
  106502. /* SQLITE_TOOBIG */ "string or blob too big",
  106503. /* SQLITE_CONSTRAINT */ "constraint failed",
  106504. /* SQLITE_MISMATCH */ "datatype mismatch",
  106505. /* SQLITE_MISUSE */ "library routine called out of sequence",
  106506. /* SQLITE_NOLFS */ "large file support is disabled",
  106507. /* SQLITE_AUTH */ "authorization denied",
  106508. /* SQLITE_FORMAT */ "auxiliary database format error",
  106509. /* SQLITE_RANGE */ "bind or column index out of range",
  106510. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  106511. };
  106512. const char *zErr = "unknown error";
  106513. switch( rc ){
  106514. case SQLITE_ABORT_ROLLBACK: {
  106515. zErr = "abort due to ROLLBACK";
  106516. break;
  106517. }
  106518. default: {
  106519. rc &= 0xff;
  106520. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  106521. zErr = aMsg[rc];
  106522. }
  106523. break;
  106524. }
  106525. }
  106526. return zErr;
  106527. }
  106528. /*
  106529. ** This routine implements a busy callback that sleeps and tries
  106530. ** again until a timeout value is reached. The timeout value is
  106531. ** an integer number of milliseconds passed in as the first
  106532. ** argument.
  106533. */
  106534. static int sqliteDefaultBusyCallback(
  106535. void *ptr, /* Database connection */
  106536. int count /* Number of times table has been busy */
  106537. ){
  106538. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  106539. static const u8 delays[] =
  106540. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  106541. static const u8 totals[] =
  106542. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  106543. # define NDELAY ArraySize(delays)
  106544. sqlite3 *db = (sqlite3 *)ptr;
  106545. int timeout = db->busyTimeout;
  106546. int delay, prior;
  106547. assert( count>=0 );
  106548. if( count < NDELAY ){
  106549. delay = delays[count];
  106550. prior = totals[count];
  106551. }else{
  106552. delay = delays[NDELAY-1];
  106553. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  106554. }
  106555. if( prior + delay > timeout ){
  106556. delay = timeout - prior;
  106557. if( delay<=0 ) return 0;
  106558. }
  106559. sqlite3OsSleep(db->pVfs, delay*1000);
  106560. return 1;
  106561. #else
  106562. sqlite3 *db = (sqlite3 *)ptr;
  106563. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  106564. if( (count+1)*1000 > timeout ){
  106565. return 0;
  106566. }
  106567. sqlite3OsSleep(db->pVfs, 1000000);
  106568. return 1;
  106569. #endif
  106570. }
  106571. /*
  106572. ** Invoke the given busy handler.
  106573. **
  106574. ** This routine is called when an operation failed with a lock.
  106575. ** If this routine returns non-zero, the lock is retried. If it
  106576. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  106577. */
  106578. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  106579. int rc;
  106580. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  106581. rc = p->xFunc(p->pArg, p->nBusy);
  106582. if( rc==0 ){
  106583. p->nBusy = -1;
  106584. }else{
  106585. p->nBusy++;
  106586. }
  106587. return rc;
  106588. }
  106589. /*
  106590. ** This routine sets the busy callback for an Sqlite database to the
  106591. ** given callback function with the given argument.
  106592. */
  106593. SQLITE_API int sqlite3_busy_handler(
  106594. sqlite3 *db,
  106595. int (*xBusy)(void*,int),
  106596. void *pArg
  106597. ){
  106598. sqlite3_mutex_enter(db->mutex);
  106599. db->busyHandler.xFunc = xBusy;
  106600. db->busyHandler.pArg = pArg;
  106601. db->busyHandler.nBusy = 0;
  106602. db->busyTimeout = 0;
  106603. sqlite3_mutex_leave(db->mutex);
  106604. return SQLITE_OK;
  106605. }
  106606. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  106607. /*
  106608. ** This routine sets the progress callback for an Sqlite database to the
  106609. ** given callback function with the given argument. The progress callback will
  106610. ** be invoked every nOps opcodes.
  106611. */
  106612. SQLITE_API void sqlite3_progress_handler(
  106613. sqlite3 *db,
  106614. int nOps,
  106615. int (*xProgress)(void*),
  106616. void *pArg
  106617. ){
  106618. sqlite3_mutex_enter(db->mutex);
  106619. if( nOps>0 ){
  106620. db->xProgress = xProgress;
  106621. db->nProgressOps = nOps;
  106622. db->pProgressArg = pArg;
  106623. }else{
  106624. db->xProgress = 0;
  106625. db->nProgressOps = 0;
  106626. db->pProgressArg = 0;
  106627. }
  106628. sqlite3_mutex_leave(db->mutex);
  106629. }
  106630. #endif
  106631. /*
  106632. ** This routine installs a default busy handler that waits for the
  106633. ** specified number of milliseconds before returning 0.
  106634. */
  106635. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  106636. if( ms>0 ){
  106637. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  106638. db->busyTimeout = ms;
  106639. }else{
  106640. sqlite3_busy_handler(db, 0, 0);
  106641. }
  106642. return SQLITE_OK;
  106643. }
  106644. /*
  106645. ** Cause any pending operation to stop at its earliest opportunity.
  106646. */
  106647. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  106648. db->u1.isInterrupted = 1;
  106649. }
  106650. /*
  106651. ** This function is exactly the same as sqlite3_create_function(), except
  106652. ** that it is designed to be called by internal code. The difference is
  106653. ** that if a malloc() fails in sqlite3_create_function(), an error code
  106654. ** is returned and the mallocFailed flag cleared.
  106655. */
  106656. SQLITE_PRIVATE int sqlite3CreateFunc(
  106657. sqlite3 *db,
  106658. const char *zFunctionName,
  106659. int nArg,
  106660. int enc,
  106661. void *pUserData,
  106662. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  106663. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  106664. void (*xFinal)(sqlite3_context*),
  106665. FuncDestructor *pDestructor
  106666. ){
  106667. FuncDef *p;
  106668. int nName;
  106669. assert( sqlite3_mutex_held(db->mutex) );
  106670. if( zFunctionName==0 ||
  106671. (xFunc && (xFinal || xStep)) ||
  106672. (!xFunc && (xFinal && !xStep)) ||
  106673. (!xFunc && (!xFinal && xStep)) ||
  106674. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  106675. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  106676. return SQLITE_MISUSE_BKPT;
  106677. }
  106678. #ifndef SQLITE_OMIT_UTF16
  106679. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  106680. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  106681. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  106682. **
  106683. ** If SQLITE_ANY is specified, add three versions of the function
  106684. ** to the hash table.
  106685. */
  106686. if( enc==SQLITE_UTF16 ){
  106687. enc = SQLITE_UTF16NATIVE;
  106688. }else if( enc==SQLITE_ANY ){
  106689. int rc;
  106690. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  106691. pUserData, xFunc, xStep, xFinal, pDestructor);
  106692. if( rc==SQLITE_OK ){
  106693. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  106694. pUserData, xFunc, xStep, xFinal, pDestructor);
  106695. }
  106696. if( rc!=SQLITE_OK ){
  106697. return rc;
  106698. }
  106699. enc = SQLITE_UTF16BE;
  106700. }
  106701. #else
  106702. enc = SQLITE_UTF8;
  106703. #endif
  106704. /* Check if an existing function is being overridden or deleted. If so,
  106705. ** and there are active VMs, then return SQLITE_BUSY. If a function
  106706. ** is being overridden/deleted but there are no active VMs, allow the
  106707. ** operation to continue but invalidate all precompiled statements.
  106708. */
  106709. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  106710. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  106711. if( db->activeVdbeCnt ){
  106712. sqlite3Error(db, SQLITE_BUSY,
  106713. "unable to delete/modify user-function due to active statements");
  106714. assert( !db->mallocFailed );
  106715. return SQLITE_BUSY;
  106716. }else{
  106717. sqlite3ExpirePreparedStatements(db);
  106718. }
  106719. }
  106720. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  106721. assert(p || db->mallocFailed);
  106722. if( !p ){
  106723. return SQLITE_NOMEM;
  106724. }
  106725. /* If an older version of the function with a configured destructor is
  106726. ** being replaced invoke the destructor function here. */
  106727. functionDestroy(db, p);
  106728. if( pDestructor ){
  106729. pDestructor->nRef++;
  106730. }
  106731. p->pDestructor = pDestructor;
  106732. p->flags = 0;
  106733. p->xFunc = xFunc;
  106734. p->xStep = xStep;
  106735. p->xFinalize = xFinal;
  106736. p->pUserData = pUserData;
  106737. p->nArg = (u16)nArg;
  106738. return SQLITE_OK;
  106739. }
  106740. /*
  106741. ** Create new user functions.
  106742. */
  106743. SQLITE_API int sqlite3_create_function(
  106744. sqlite3 *db,
  106745. const char *zFunc,
  106746. int nArg,
  106747. int enc,
  106748. void *p,
  106749. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  106750. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  106751. void (*xFinal)(sqlite3_context*)
  106752. ){
  106753. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  106754. xFinal, 0);
  106755. }
  106756. SQLITE_API int sqlite3_create_function_v2(
  106757. sqlite3 *db,
  106758. const char *zFunc,
  106759. int nArg,
  106760. int enc,
  106761. void *p,
  106762. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  106763. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  106764. void (*xFinal)(sqlite3_context*),
  106765. void (*xDestroy)(void *)
  106766. ){
  106767. int rc = SQLITE_ERROR;
  106768. FuncDestructor *pArg = 0;
  106769. sqlite3_mutex_enter(db->mutex);
  106770. if( xDestroy ){
  106771. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  106772. if( !pArg ){
  106773. xDestroy(p);
  106774. goto out;
  106775. }
  106776. pArg->xDestroy = xDestroy;
  106777. pArg->pUserData = p;
  106778. }
  106779. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  106780. if( pArg && pArg->nRef==0 ){
  106781. assert( rc!=SQLITE_OK );
  106782. xDestroy(p);
  106783. sqlite3DbFree(db, pArg);
  106784. }
  106785. out:
  106786. rc = sqlite3ApiExit(db, rc);
  106787. sqlite3_mutex_leave(db->mutex);
  106788. return rc;
  106789. }
  106790. #ifndef SQLITE_OMIT_UTF16
  106791. SQLITE_API int sqlite3_create_function16(
  106792. sqlite3 *db,
  106793. const void *zFunctionName,
  106794. int nArg,
  106795. int eTextRep,
  106796. void *p,
  106797. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  106798. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  106799. void (*xFinal)(sqlite3_context*)
  106800. ){
  106801. int rc;
  106802. char *zFunc8;
  106803. sqlite3_mutex_enter(db->mutex);
  106804. assert( !db->mallocFailed );
  106805. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  106806. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  106807. sqlite3DbFree(db, zFunc8);
  106808. rc = sqlite3ApiExit(db, rc);
  106809. sqlite3_mutex_leave(db->mutex);
  106810. return rc;
  106811. }
  106812. #endif
  106813. /*
  106814. ** Declare that a function has been overloaded by a virtual table.
  106815. **
  106816. ** If the function already exists as a regular global function, then
  106817. ** this routine is a no-op. If the function does not exist, then create
  106818. ** a new one that always throws a run-time error.
  106819. **
  106820. ** When virtual tables intend to provide an overloaded function, they
  106821. ** should call this routine to make sure the global function exists.
  106822. ** A global function must exist in order for name resolution to work
  106823. ** properly.
  106824. */
  106825. SQLITE_API int sqlite3_overload_function(
  106826. sqlite3 *db,
  106827. const char *zName,
  106828. int nArg
  106829. ){
  106830. int nName = sqlite3Strlen30(zName);
  106831. int rc = SQLITE_OK;
  106832. sqlite3_mutex_enter(db->mutex);
  106833. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  106834. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  106835. 0, sqlite3InvalidFunction, 0, 0, 0);
  106836. }
  106837. rc = sqlite3ApiExit(db, rc);
  106838. sqlite3_mutex_leave(db->mutex);
  106839. return rc;
  106840. }
  106841. #ifndef SQLITE_OMIT_TRACE
  106842. /*
  106843. ** Register a trace function. The pArg from the previously registered trace
  106844. ** is returned.
  106845. **
  106846. ** A NULL trace function means that no tracing is executes. A non-NULL
  106847. ** trace is a pointer to a function that is invoked at the start of each
  106848. ** SQL statement.
  106849. */
  106850. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  106851. void *pOld;
  106852. sqlite3_mutex_enter(db->mutex);
  106853. pOld = db->pTraceArg;
  106854. db->xTrace = xTrace;
  106855. db->pTraceArg = pArg;
  106856. sqlite3_mutex_leave(db->mutex);
  106857. return pOld;
  106858. }
  106859. /*
  106860. ** Register a profile function. The pArg from the previously registered
  106861. ** profile function is returned.
  106862. **
  106863. ** A NULL profile function means that no profiling is executes. A non-NULL
  106864. ** profile is a pointer to a function that is invoked at the conclusion of
  106865. ** each SQL statement that is run.
  106866. */
  106867. SQLITE_API void *sqlite3_profile(
  106868. sqlite3 *db,
  106869. void (*xProfile)(void*,const char*,sqlite_uint64),
  106870. void *pArg
  106871. ){
  106872. void *pOld;
  106873. sqlite3_mutex_enter(db->mutex);
  106874. pOld = db->pProfileArg;
  106875. db->xProfile = xProfile;
  106876. db->pProfileArg = pArg;
  106877. sqlite3_mutex_leave(db->mutex);
  106878. return pOld;
  106879. }
  106880. #endif /* SQLITE_OMIT_TRACE */
  106881. /*
  106882. ** Register a function to be invoked when a transaction commits.
  106883. ** If the invoked function returns non-zero, then the commit becomes a
  106884. ** rollback.
  106885. */
  106886. SQLITE_API void *sqlite3_commit_hook(
  106887. sqlite3 *db, /* Attach the hook to this database */
  106888. int (*xCallback)(void*), /* Function to invoke on each commit */
  106889. void *pArg /* Argument to the function */
  106890. ){
  106891. void *pOld;
  106892. sqlite3_mutex_enter(db->mutex);
  106893. pOld = db->pCommitArg;
  106894. db->xCommitCallback = xCallback;
  106895. db->pCommitArg = pArg;
  106896. sqlite3_mutex_leave(db->mutex);
  106897. return pOld;
  106898. }
  106899. /*
  106900. ** Register a callback to be invoked each time a row is updated,
  106901. ** inserted or deleted using this database connection.
  106902. */
  106903. SQLITE_API void *sqlite3_update_hook(
  106904. sqlite3 *db, /* Attach the hook to this database */
  106905. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  106906. void *pArg /* Argument to the function */
  106907. ){
  106908. void *pRet;
  106909. sqlite3_mutex_enter(db->mutex);
  106910. pRet = db->pUpdateArg;
  106911. db->xUpdateCallback = xCallback;
  106912. db->pUpdateArg = pArg;
  106913. sqlite3_mutex_leave(db->mutex);
  106914. return pRet;
  106915. }
  106916. /*
  106917. ** Register a callback to be invoked each time a transaction is rolled
  106918. ** back by this database connection.
  106919. */
  106920. SQLITE_API void *sqlite3_rollback_hook(
  106921. sqlite3 *db, /* Attach the hook to this database */
  106922. void (*xCallback)(void*), /* Callback function */
  106923. void *pArg /* Argument to the function */
  106924. ){
  106925. void *pRet;
  106926. sqlite3_mutex_enter(db->mutex);
  106927. pRet = db->pRollbackArg;
  106928. db->xRollbackCallback = xCallback;
  106929. db->pRollbackArg = pArg;
  106930. sqlite3_mutex_leave(db->mutex);
  106931. return pRet;
  106932. }
  106933. #ifndef SQLITE_OMIT_WAL
  106934. /*
  106935. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  106936. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  106937. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  106938. ** wal_autocheckpoint()).
  106939. */
  106940. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  106941. void *pClientData, /* Argument */
  106942. sqlite3 *db, /* Connection */
  106943. const char *zDb, /* Database */
  106944. int nFrame /* Size of WAL */
  106945. ){
  106946. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  106947. sqlite3BeginBenignMalloc();
  106948. sqlite3_wal_checkpoint(db, zDb);
  106949. sqlite3EndBenignMalloc();
  106950. }
  106951. return SQLITE_OK;
  106952. }
  106953. #endif /* SQLITE_OMIT_WAL */
  106954. /*
  106955. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  106956. ** a database after committing a transaction if there are nFrame or
  106957. ** more frames in the log file. Passing zero or a negative value as the
  106958. ** nFrame parameter disables automatic checkpoints entirely.
  106959. **
  106960. ** The callback registered by this function replaces any existing callback
  106961. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  106962. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  106963. ** configured by this function.
  106964. */
  106965. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  106966. #ifdef SQLITE_OMIT_WAL
  106967. UNUSED_PARAMETER(db);
  106968. UNUSED_PARAMETER(nFrame);
  106969. #else
  106970. if( nFrame>0 ){
  106971. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  106972. }else{
  106973. sqlite3_wal_hook(db, 0, 0);
  106974. }
  106975. #endif
  106976. return SQLITE_OK;
  106977. }
  106978. /*
  106979. ** Register a callback to be invoked each time a transaction is written
  106980. ** into the write-ahead-log by this database connection.
  106981. */
  106982. SQLITE_API void *sqlite3_wal_hook(
  106983. sqlite3 *db, /* Attach the hook to this db handle */
  106984. int(*xCallback)(void *, sqlite3*, const char*, int),
  106985. void *pArg /* First argument passed to xCallback() */
  106986. ){
  106987. #ifndef SQLITE_OMIT_WAL
  106988. void *pRet;
  106989. sqlite3_mutex_enter(db->mutex);
  106990. pRet = db->pWalArg;
  106991. db->xWalCallback = xCallback;
  106992. db->pWalArg = pArg;
  106993. sqlite3_mutex_leave(db->mutex);
  106994. return pRet;
  106995. #else
  106996. return 0;
  106997. #endif
  106998. }
  106999. /*
  107000. ** Checkpoint database zDb.
  107001. */
  107002. SQLITE_API int sqlite3_wal_checkpoint_v2(
  107003. sqlite3 *db, /* Database handle */
  107004. const char *zDb, /* Name of attached database (or NULL) */
  107005. int eMode, /* SQLITE_CHECKPOINT_* value */
  107006. int *pnLog, /* OUT: Size of WAL log in frames */
  107007. int *pnCkpt /* OUT: Total number of frames checkpointed */
  107008. ){
  107009. #ifdef SQLITE_OMIT_WAL
  107010. return SQLITE_OK;
  107011. #else
  107012. int rc; /* Return code */
  107013. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  107014. /* Initialize the output variables to -1 in case an error occurs. */
  107015. if( pnLog ) *pnLog = -1;
  107016. if( pnCkpt ) *pnCkpt = -1;
  107017. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  107018. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  107019. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  107020. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  107021. return SQLITE_MISUSE;
  107022. }
  107023. sqlite3_mutex_enter(db->mutex);
  107024. if( zDb && zDb[0] ){
  107025. iDb = sqlite3FindDbName(db, zDb);
  107026. }
  107027. if( iDb<0 ){
  107028. rc = SQLITE_ERROR;
  107029. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  107030. }else{
  107031. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  107032. sqlite3Error(db, rc, 0);
  107033. }
  107034. rc = sqlite3ApiExit(db, rc);
  107035. sqlite3_mutex_leave(db->mutex);
  107036. return rc;
  107037. #endif
  107038. }
  107039. /*
  107040. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  107041. ** to contains a zero-length string, all attached databases are
  107042. ** checkpointed.
  107043. */
  107044. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  107045. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  107046. }
  107047. #ifndef SQLITE_OMIT_WAL
  107048. /*
  107049. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  107050. ** not currently open in WAL mode.
  107051. **
  107052. ** If a transaction is open on the database being checkpointed, this
  107053. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  107054. ** an error occurs while running the checkpoint, an SQLite error code is
  107055. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  107056. **
  107057. ** The mutex on database handle db should be held by the caller. The mutex
  107058. ** associated with the specific b-tree being checkpointed is taken by
  107059. ** this function while the checkpoint is running.
  107060. **
  107061. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  107062. ** checkpointed. If an error is encountered it is returned immediately -
  107063. ** no attempt is made to checkpoint any remaining databases.
  107064. **
  107065. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  107066. */
  107067. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  107068. int rc = SQLITE_OK; /* Return code */
  107069. int i; /* Used to iterate through attached dbs */
  107070. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  107071. assert( sqlite3_mutex_held(db->mutex) );
  107072. assert( !pnLog || *pnLog==-1 );
  107073. assert( !pnCkpt || *pnCkpt==-1 );
  107074. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  107075. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  107076. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  107077. pnLog = 0;
  107078. pnCkpt = 0;
  107079. if( rc==SQLITE_BUSY ){
  107080. bBusy = 1;
  107081. rc = SQLITE_OK;
  107082. }
  107083. }
  107084. }
  107085. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  107086. }
  107087. #endif /* SQLITE_OMIT_WAL */
  107088. /*
  107089. ** This function returns true if main-memory should be used instead of
  107090. ** a temporary file for transient pager files and statement journals.
  107091. ** The value returned depends on the value of db->temp_store (runtime
  107092. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  107093. ** following table describes the relationship between these two values
  107094. ** and this functions return value.
  107095. **
  107096. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  107097. ** ----------------- -------------- ------------------------------
  107098. ** 0 any file (return 0)
  107099. ** 1 1 file (return 0)
  107100. ** 1 2 memory (return 1)
  107101. ** 1 0 file (return 0)
  107102. ** 2 1 file (return 0)
  107103. ** 2 2 memory (return 1)
  107104. ** 2 0 memory (return 1)
  107105. ** 3 any memory (return 1)
  107106. */
  107107. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  107108. #if SQLITE_TEMP_STORE==1
  107109. return ( db->temp_store==2 );
  107110. #endif
  107111. #if SQLITE_TEMP_STORE==2
  107112. return ( db->temp_store!=1 );
  107113. #endif
  107114. #if SQLITE_TEMP_STORE==3
  107115. return 1;
  107116. #endif
  107117. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  107118. return 0;
  107119. #endif
  107120. }
  107121. /*
  107122. ** Return UTF-8 encoded English language explanation of the most recent
  107123. ** error.
  107124. */
  107125. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  107126. const char *z;
  107127. if( !db ){
  107128. return sqlite3ErrStr(SQLITE_NOMEM);
  107129. }
  107130. if( !sqlite3SafetyCheckSickOrOk(db) ){
  107131. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  107132. }
  107133. sqlite3_mutex_enter(db->mutex);
  107134. if( db->mallocFailed ){
  107135. z = sqlite3ErrStr(SQLITE_NOMEM);
  107136. }else{
  107137. z = (char*)sqlite3_value_text(db->pErr);
  107138. assert( !db->mallocFailed );
  107139. if( z==0 ){
  107140. z = sqlite3ErrStr(db->errCode);
  107141. }
  107142. }
  107143. sqlite3_mutex_leave(db->mutex);
  107144. return z;
  107145. }
  107146. #ifndef SQLITE_OMIT_UTF16
  107147. /*
  107148. ** Return UTF-16 encoded English language explanation of the most recent
  107149. ** error.
  107150. */
  107151. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  107152. static const u16 outOfMem[] = {
  107153. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  107154. };
  107155. static const u16 misuse[] = {
  107156. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  107157. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  107158. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  107159. 'o', 'u', 't', ' ',
  107160. 'o', 'f', ' ',
  107161. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  107162. };
  107163. const void *z;
  107164. if( !db ){
  107165. return (void *)outOfMem;
  107166. }
  107167. if( !sqlite3SafetyCheckSickOrOk(db) ){
  107168. return (void *)misuse;
  107169. }
  107170. sqlite3_mutex_enter(db->mutex);
  107171. if( db->mallocFailed ){
  107172. z = (void *)outOfMem;
  107173. }else{
  107174. z = sqlite3_value_text16(db->pErr);
  107175. if( z==0 ){
  107176. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  107177. SQLITE_UTF8, SQLITE_STATIC);
  107178. z = sqlite3_value_text16(db->pErr);
  107179. }
  107180. /* A malloc() may have failed within the call to sqlite3_value_text16()
  107181. ** above. If this is the case, then the db->mallocFailed flag needs to
  107182. ** be cleared before returning. Do this directly, instead of via
  107183. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  107184. */
  107185. db->mallocFailed = 0;
  107186. }
  107187. sqlite3_mutex_leave(db->mutex);
  107188. return z;
  107189. }
  107190. #endif /* SQLITE_OMIT_UTF16 */
  107191. /*
  107192. ** Return the most recent error code generated by an SQLite routine. If NULL is
  107193. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  107194. */
  107195. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  107196. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  107197. return SQLITE_MISUSE_BKPT;
  107198. }
  107199. if( !db || db->mallocFailed ){
  107200. return SQLITE_NOMEM;
  107201. }
  107202. return db->errCode & db->errMask;
  107203. }
  107204. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  107205. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  107206. return SQLITE_MISUSE_BKPT;
  107207. }
  107208. if( !db || db->mallocFailed ){
  107209. return SQLITE_NOMEM;
  107210. }
  107211. return db->errCode;
  107212. }
  107213. /*
  107214. ** Return a string that describes the kind of error specified in the
  107215. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  107216. ** function.
  107217. */
  107218. SQLITE_API const char *sqlite3_errstr(int rc){
  107219. return sqlite3ErrStr(rc);
  107220. }
  107221. /*
  107222. ** Create a new collating function for database "db". The name is zName
  107223. ** and the encoding is enc.
  107224. */
  107225. static int createCollation(
  107226. sqlite3* db,
  107227. const char *zName,
  107228. u8 enc,
  107229. void* pCtx,
  107230. int(*xCompare)(void*,int,const void*,int,const void*),
  107231. void(*xDel)(void*)
  107232. ){
  107233. CollSeq *pColl;
  107234. int enc2;
  107235. int nName = sqlite3Strlen30(zName);
  107236. assert( sqlite3_mutex_held(db->mutex) );
  107237. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  107238. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  107239. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  107240. */
  107241. enc2 = enc;
  107242. testcase( enc2==SQLITE_UTF16 );
  107243. testcase( enc2==SQLITE_UTF16_ALIGNED );
  107244. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  107245. enc2 = SQLITE_UTF16NATIVE;
  107246. }
  107247. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  107248. return SQLITE_MISUSE_BKPT;
  107249. }
  107250. /* Check if this call is removing or replacing an existing collation
  107251. ** sequence. If so, and there are active VMs, return busy. If there
  107252. ** are no active VMs, invalidate any pre-compiled statements.
  107253. */
  107254. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  107255. if( pColl && pColl->xCmp ){
  107256. if( db->activeVdbeCnt ){
  107257. sqlite3Error(db, SQLITE_BUSY,
  107258. "unable to delete/modify collation sequence due to active statements");
  107259. return SQLITE_BUSY;
  107260. }
  107261. sqlite3ExpirePreparedStatements(db);
  107262. /* If collation sequence pColl was created directly by a call to
  107263. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  107264. ** then any copies made by synthCollSeq() need to be invalidated.
  107265. ** Also, collation destructor - CollSeq.xDel() - function may need
  107266. ** to be called.
  107267. */
  107268. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  107269. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  107270. int j;
  107271. for(j=0; j<3; j++){
  107272. CollSeq *p = &aColl[j];
  107273. if( p->enc==pColl->enc ){
  107274. if( p->xDel ){
  107275. p->xDel(p->pUser);
  107276. }
  107277. p->xCmp = 0;
  107278. }
  107279. }
  107280. }
  107281. }
  107282. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  107283. if( pColl==0 ) return SQLITE_NOMEM;
  107284. pColl->xCmp = xCompare;
  107285. pColl->pUser = pCtx;
  107286. pColl->xDel = xDel;
  107287. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  107288. sqlite3Error(db, SQLITE_OK, 0);
  107289. return SQLITE_OK;
  107290. }
  107291. /*
  107292. ** This array defines hard upper bounds on limit values. The
  107293. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  107294. ** #defines in sqlite3.h.
  107295. */
  107296. static const int aHardLimit[] = {
  107297. SQLITE_MAX_LENGTH,
  107298. SQLITE_MAX_SQL_LENGTH,
  107299. SQLITE_MAX_COLUMN,
  107300. SQLITE_MAX_EXPR_DEPTH,
  107301. SQLITE_MAX_COMPOUND_SELECT,
  107302. SQLITE_MAX_VDBE_OP,
  107303. SQLITE_MAX_FUNCTION_ARG,
  107304. SQLITE_MAX_ATTACHED,
  107305. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  107306. SQLITE_MAX_VARIABLE_NUMBER,
  107307. SQLITE_MAX_TRIGGER_DEPTH,
  107308. };
  107309. /*
  107310. ** Make sure the hard limits are set to reasonable values
  107311. */
  107312. #if SQLITE_MAX_LENGTH<100
  107313. # error SQLITE_MAX_LENGTH must be at least 100
  107314. #endif
  107315. #if SQLITE_MAX_SQL_LENGTH<100
  107316. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  107317. #endif
  107318. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  107319. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  107320. #endif
  107321. #if SQLITE_MAX_COMPOUND_SELECT<2
  107322. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  107323. #endif
  107324. #if SQLITE_MAX_VDBE_OP<40
  107325. # error SQLITE_MAX_VDBE_OP must be at least 40
  107326. #endif
  107327. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  107328. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  107329. #endif
  107330. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  107331. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  107332. #endif
  107333. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  107334. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  107335. #endif
  107336. #if SQLITE_MAX_COLUMN>32767
  107337. # error SQLITE_MAX_COLUMN must not exceed 32767
  107338. #endif
  107339. #if SQLITE_MAX_TRIGGER_DEPTH<1
  107340. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  107341. #endif
  107342. /*
  107343. ** Change the value of a limit. Report the old value.
  107344. ** If an invalid limit index is supplied, report -1.
  107345. ** Make no changes but still report the old value if the
  107346. ** new limit is negative.
  107347. **
  107348. ** A new lower limit does not shrink existing constructs.
  107349. ** It merely prevents new constructs that exceed the limit
  107350. ** from forming.
  107351. */
  107352. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  107353. int oldLimit;
  107354. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  107355. ** there is a hard upper bound set at compile-time by a C preprocessor
  107356. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  107357. ** "_MAX_".)
  107358. */
  107359. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  107360. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  107361. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  107362. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  107363. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  107364. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  107365. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  107366. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  107367. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  107368. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  107369. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  107370. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  107371. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  107372. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  107373. return -1;
  107374. }
  107375. oldLimit = db->aLimit[limitId];
  107376. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  107377. if( newLimit>aHardLimit[limitId] ){
  107378. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  107379. }
  107380. db->aLimit[limitId] = newLimit;
  107381. }
  107382. return oldLimit; /* IMP: R-53341-35419 */
  107383. }
  107384. /*
  107385. ** This function is used to parse both URIs and non-URI filenames passed by the
  107386. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  107387. ** URIs specified as part of ATTACH statements.
  107388. **
  107389. ** The first argument to this function is the name of the VFS to use (or
  107390. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  107391. ** query parameter. The second argument contains the URI (or non-URI filename)
  107392. ** itself. When this function is called the *pFlags variable should contain
  107393. ** the default flags to open the database handle with. The value stored in
  107394. ** *pFlags may be updated before returning if the URI filename contains
  107395. ** "cache=xxx" or "mode=xxx" query parameters.
  107396. **
  107397. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  107398. ** the VFS that should be used to open the database file. *pzFile is set to
  107399. ** point to a buffer containing the name of the file to open. It is the
  107400. ** responsibility of the caller to eventually call sqlite3_free() to release
  107401. ** this buffer.
  107402. **
  107403. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  107404. ** may be set to point to a buffer containing an English language error
  107405. ** message. It is the responsibility of the caller to eventually release
  107406. ** this buffer by calling sqlite3_free().
  107407. */
  107408. SQLITE_PRIVATE int sqlite3ParseUri(
  107409. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  107410. const char *zUri, /* Nul-terminated URI to parse */
  107411. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  107412. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  107413. char **pzFile, /* OUT: Filename component of URI */
  107414. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  107415. ){
  107416. int rc = SQLITE_OK;
  107417. unsigned int flags = *pFlags;
  107418. const char *zVfs = zDefaultVfs;
  107419. char *zFile;
  107420. char c;
  107421. int nUri = sqlite3Strlen30(zUri);
  107422. assert( *pzErrMsg==0 );
  107423. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  107424. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  107425. ){
  107426. char *zOpt;
  107427. int eState; /* Parser state when parsing URI */
  107428. int iIn; /* Input character index */
  107429. int iOut = 0; /* Output character index */
  107430. int nByte = nUri+2; /* Bytes of space to allocate */
  107431. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  107432. ** method that there may be extra parameters following the file-name. */
  107433. flags |= SQLITE_OPEN_URI;
  107434. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  107435. zFile = sqlite3_malloc(nByte);
  107436. if( !zFile ) return SQLITE_NOMEM;
  107437. /* Discard the scheme and authority segments of the URI. */
  107438. if( zUri[5]=='/' && zUri[6]=='/' ){
  107439. iIn = 7;
  107440. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  107441. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  107442. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  107443. iIn-7, &zUri[7]);
  107444. rc = SQLITE_ERROR;
  107445. goto parse_uri_out;
  107446. }
  107447. }else{
  107448. iIn = 5;
  107449. }
  107450. /* Copy the filename and any query parameters into the zFile buffer.
  107451. ** Decode %HH escape codes along the way.
  107452. **
  107453. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  107454. ** on the parsing context. As follows:
  107455. **
  107456. ** 0: Parsing file-name.
  107457. ** 1: Parsing name section of a name=value query parameter.
  107458. ** 2: Parsing value section of a name=value query parameter.
  107459. */
  107460. eState = 0;
  107461. while( (c = zUri[iIn])!=0 && c!='#' ){
  107462. iIn++;
  107463. if( c=='%'
  107464. && sqlite3Isxdigit(zUri[iIn])
  107465. && sqlite3Isxdigit(zUri[iIn+1])
  107466. ){
  107467. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  107468. octet += sqlite3HexToInt(zUri[iIn++]);
  107469. assert( octet>=0 && octet<256 );
  107470. if( octet==0 ){
  107471. /* This branch is taken when "%00" appears within the URI. In this
  107472. ** case we ignore all text in the remainder of the path, name or
  107473. ** value currently being parsed. So ignore the current character
  107474. ** and skip to the next "?", "=" or "&", as appropriate. */
  107475. while( (c = zUri[iIn])!=0 && c!='#'
  107476. && (eState!=0 || c!='?')
  107477. && (eState!=1 || (c!='=' && c!='&'))
  107478. && (eState!=2 || c!='&')
  107479. ){
  107480. iIn++;
  107481. }
  107482. continue;
  107483. }
  107484. c = octet;
  107485. }else if( eState==1 && (c=='&' || c=='=') ){
  107486. if( zFile[iOut-1]==0 ){
  107487. /* An empty option name. Ignore this option altogether. */
  107488. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  107489. continue;
  107490. }
  107491. if( c=='&' ){
  107492. zFile[iOut++] = '\0';
  107493. }else{
  107494. eState = 2;
  107495. }
  107496. c = 0;
  107497. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  107498. c = 0;
  107499. eState = 1;
  107500. }
  107501. zFile[iOut++] = c;
  107502. }
  107503. if( eState==1 ) zFile[iOut++] = '\0';
  107504. zFile[iOut++] = '\0';
  107505. zFile[iOut++] = '\0';
  107506. /* Check if there were any options specified that should be interpreted
  107507. ** here. Options that are interpreted here include "vfs" and those that
  107508. ** correspond to flags that may be passed to the sqlite3_open_v2()
  107509. ** method. */
  107510. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  107511. while( zOpt[0] ){
  107512. int nOpt = sqlite3Strlen30(zOpt);
  107513. char *zVal = &zOpt[nOpt+1];
  107514. int nVal = sqlite3Strlen30(zVal);
  107515. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  107516. zVfs = zVal;
  107517. }else{
  107518. struct OpenMode {
  107519. const char *z;
  107520. int mode;
  107521. } *aMode = 0;
  107522. char *zModeType = 0;
  107523. int mask = 0;
  107524. int limit = 0;
  107525. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  107526. static struct OpenMode aCacheMode[] = {
  107527. { "shared", SQLITE_OPEN_SHAREDCACHE },
  107528. { "private", SQLITE_OPEN_PRIVATECACHE },
  107529. { 0, 0 }
  107530. };
  107531. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  107532. aMode = aCacheMode;
  107533. limit = mask;
  107534. zModeType = "cache";
  107535. }
  107536. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  107537. static struct OpenMode aOpenMode[] = {
  107538. { "ro", SQLITE_OPEN_READONLY },
  107539. { "rw", SQLITE_OPEN_READWRITE },
  107540. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  107541. { "memory", SQLITE_OPEN_MEMORY },
  107542. { 0, 0 }
  107543. };
  107544. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  107545. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  107546. aMode = aOpenMode;
  107547. limit = mask & flags;
  107548. zModeType = "access";
  107549. }
  107550. if( aMode ){
  107551. int i;
  107552. int mode = 0;
  107553. for(i=0; aMode[i].z; i++){
  107554. const char *z = aMode[i].z;
  107555. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  107556. mode = aMode[i].mode;
  107557. break;
  107558. }
  107559. }
  107560. if( mode==0 ){
  107561. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  107562. rc = SQLITE_ERROR;
  107563. goto parse_uri_out;
  107564. }
  107565. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  107566. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  107567. zModeType, zVal);
  107568. rc = SQLITE_PERM;
  107569. goto parse_uri_out;
  107570. }
  107571. flags = (flags & ~mask) | mode;
  107572. }
  107573. }
  107574. zOpt = &zVal[nVal+1];
  107575. }
  107576. }else{
  107577. zFile = sqlite3_malloc(nUri+2);
  107578. if( !zFile ) return SQLITE_NOMEM;
  107579. memcpy(zFile, zUri, nUri);
  107580. zFile[nUri] = '\0';
  107581. zFile[nUri+1] = '\0';
  107582. flags &= ~SQLITE_OPEN_URI;
  107583. }
  107584. *ppVfs = sqlite3_vfs_find(zVfs);
  107585. if( *ppVfs==0 ){
  107586. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  107587. rc = SQLITE_ERROR;
  107588. }
  107589. parse_uri_out:
  107590. if( rc!=SQLITE_OK ){
  107591. sqlite3_free(zFile);
  107592. zFile = 0;
  107593. }
  107594. *pFlags = flags;
  107595. *pzFile = zFile;
  107596. return rc;
  107597. }
  107598. /*
  107599. ** This routine does the work of opening a database on behalf of
  107600. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  107601. ** is UTF-8 encoded.
  107602. */
  107603. static int openDatabase(
  107604. const char *zFilename, /* Database filename UTF-8 encoded */
  107605. sqlite3 **ppDb, /* OUT: Returned database handle */
  107606. unsigned int flags, /* Operational flags */
  107607. const char *zVfs /* Name of the VFS to use */
  107608. ){
  107609. sqlite3 *db; /* Store allocated handle here */
  107610. int rc; /* Return code */
  107611. int isThreadsafe; /* True for threadsafe connections */
  107612. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  107613. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  107614. *ppDb = 0;
  107615. #ifndef SQLITE_OMIT_AUTOINIT
  107616. rc = sqlite3_initialize();
  107617. if( rc ) return rc;
  107618. #endif
  107619. /* Only allow sensible combinations of bits in the flags argument.
  107620. ** Throw an error if any non-sense combination is used. If we
  107621. ** do not block illegal combinations here, it could trigger
  107622. ** assert() statements in deeper layers. Sensible combinations
  107623. ** are:
  107624. **
  107625. ** 1: SQLITE_OPEN_READONLY
  107626. ** 2: SQLITE_OPEN_READWRITE
  107627. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  107628. */
  107629. assert( SQLITE_OPEN_READONLY == 0x01 );
  107630. assert( SQLITE_OPEN_READWRITE == 0x02 );
  107631. assert( SQLITE_OPEN_CREATE == 0x04 );
  107632. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  107633. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  107634. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  107635. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  107636. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  107637. isThreadsafe = 0;
  107638. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  107639. isThreadsafe = 0;
  107640. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  107641. isThreadsafe = 1;
  107642. }else{
  107643. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  107644. }
  107645. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  107646. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  107647. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  107648. flags |= SQLITE_OPEN_SHAREDCACHE;
  107649. }
  107650. /* Remove harmful bits from the flags parameter
  107651. **
  107652. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  107653. ** dealt with in the previous code block. Besides these, the only
  107654. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  107655. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  107656. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  107657. ** off all other flags.
  107658. */
  107659. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  107660. SQLITE_OPEN_EXCLUSIVE |
  107661. SQLITE_OPEN_MAIN_DB |
  107662. SQLITE_OPEN_TEMP_DB |
  107663. SQLITE_OPEN_TRANSIENT_DB |
  107664. SQLITE_OPEN_MAIN_JOURNAL |
  107665. SQLITE_OPEN_TEMP_JOURNAL |
  107666. SQLITE_OPEN_SUBJOURNAL |
  107667. SQLITE_OPEN_MASTER_JOURNAL |
  107668. SQLITE_OPEN_NOMUTEX |
  107669. SQLITE_OPEN_FULLMUTEX |
  107670. SQLITE_OPEN_WAL
  107671. );
  107672. /* Allocate the sqlite data structure */
  107673. db = sqlite3MallocZero( sizeof(sqlite3) );
  107674. if( db==0 ) goto opendb_out;
  107675. if( isThreadsafe ){
  107676. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  107677. if( db->mutex==0 ){
  107678. sqlite3_free(db);
  107679. db = 0;
  107680. goto opendb_out;
  107681. }
  107682. }
  107683. sqlite3_mutex_enter(db->mutex);
  107684. db->errMask = 0xff;
  107685. db->nDb = 2;
  107686. db->magic = SQLITE_MAGIC_BUSY;
  107687. db->aDb = db->aDbStatic;
  107688. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  107689. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  107690. db->autoCommit = 1;
  107691. db->nextAutovac = -1;
  107692. db->nextPagesize = 0;
  107693. db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
  107694. #if SQLITE_DEFAULT_FILE_FORMAT<4
  107695. | SQLITE_LegacyFileFmt
  107696. #endif
  107697. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  107698. | SQLITE_LoadExtension
  107699. #endif
  107700. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  107701. | SQLITE_RecTriggers
  107702. #endif
  107703. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  107704. | SQLITE_ForeignKeys
  107705. #endif
  107706. ;
  107707. sqlite3HashInit(&db->aCollSeq);
  107708. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107709. sqlite3HashInit(&db->aModule);
  107710. #endif
  107711. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  107712. ** and UTF-16, so add a version for each to avoid any unnecessary
  107713. ** conversions. The only error that can occur here is a malloc() failure.
  107714. */
  107715. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  107716. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  107717. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  107718. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  107719. if( db->mallocFailed ){
  107720. goto opendb_out;
  107721. }
  107722. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  107723. assert( db->pDfltColl!=0 );
  107724. /* Also add a UTF-8 case-insensitive collation sequence. */
  107725. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  107726. /* Parse the filename/URI argument. */
  107727. db->openFlags = flags;
  107728. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  107729. if( rc!=SQLITE_OK ){
  107730. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  107731. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  107732. sqlite3_free(zErrMsg);
  107733. goto opendb_out;
  107734. }
  107735. /* Open the backend database driver */
  107736. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  107737. flags | SQLITE_OPEN_MAIN_DB);
  107738. if( rc!=SQLITE_OK ){
  107739. if( rc==SQLITE_IOERR_NOMEM ){
  107740. rc = SQLITE_NOMEM;
  107741. }
  107742. sqlite3Error(db, rc, 0);
  107743. goto opendb_out;
  107744. }
  107745. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  107746. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  107747. /* The default safety_level for the main database is 'full'; for the temp
  107748. ** database it is 'NONE'. This matches the pager layer defaults.
  107749. */
  107750. db->aDb[0].zName = "main";
  107751. db->aDb[0].safety_level = 3;
  107752. db->aDb[1].zName = "temp";
  107753. db->aDb[1].safety_level = 1;
  107754. db->magic = SQLITE_MAGIC_OPEN;
  107755. if( db->mallocFailed ){
  107756. goto opendb_out;
  107757. }
  107758. /* Register all built-in functions, but do not attempt to read the
  107759. ** database schema yet. This is delayed until the first time the database
  107760. ** is accessed.
  107761. */
  107762. sqlite3Error(db, SQLITE_OK, 0);
  107763. sqlite3RegisterBuiltinFunctions(db);
  107764. /* Load automatic extensions - extensions that have been registered
  107765. ** using the sqlite3_automatic_extension() API.
  107766. */
  107767. rc = sqlite3_errcode(db);
  107768. if( rc==SQLITE_OK ){
  107769. sqlite3AutoLoadExtensions(db);
  107770. rc = sqlite3_errcode(db);
  107771. if( rc!=SQLITE_OK ){
  107772. goto opendb_out;
  107773. }
  107774. }
  107775. #ifdef SQLITE_ENABLE_FTS1
  107776. if( !db->mallocFailed ){
  107777. extern int sqlite3Fts1Init(sqlite3*);
  107778. rc = sqlite3Fts1Init(db);
  107779. }
  107780. #endif
  107781. #ifdef SQLITE_ENABLE_FTS2
  107782. if( !db->mallocFailed && rc==SQLITE_OK ){
  107783. extern int sqlite3Fts2Init(sqlite3*);
  107784. rc = sqlite3Fts2Init(db);
  107785. }
  107786. #endif
  107787. #ifdef SQLITE_ENABLE_FTS3
  107788. if( !db->mallocFailed && rc==SQLITE_OK ){
  107789. rc = sqlite3Fts3Init(db);
  107790. }
  107791. #endif
  107792. #ifdef SQLITE_ENABLE_ICU
  107793. if( !db->mallocFailed && rc==SQLITE_OK ){
  107794. rc = sqlite3IcuInit(db);
  107795. }
  107796. #endif
  107797. #ifdef SQLITE_ENABLE_RTREE
  107798. if( !db->mallocFailed && rc==SQLITE_OK){
  107799. rc = sqlite3RtreeInit(db);
  107800. }
  107801. #endif
  107802. sqlite3Error(db, rc, 0);
  107803. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  107804. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  107805. ** mode. Doing nothing at all also makes NORMAL the default.
  107806. */
  107807. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  107808. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  107809. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  107810. SQLITE_DEFAULT_LOCKING_MODE);
  107811. #endif
  107812. /* Enable the lookaside-malloc subsystem */
  107813. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  107814. sqlite3GlobalConfig.nLookaside);
  107815. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  107816. opendb_out:
  107817. sqlite3_free(zOpen);
  107818. if( db ){
  107819. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  107820. sqlite3_mutex_leave(db->mutex);
  107821. }
  107822. rc = sqlite3_errcode(db);
  107823. assert( db!=0 || rc==SQLITE_NOMEM );
  107824. if( rc==SQLITE_NOMEM ){
  107825. sqlite3_close(db);
  107826. db = 0;
  107827. }else if( rc!=SQLITE_OK ){
  107828. db->magic = SQLITE_MAGIC_SICK;
  107829. }
  107830. *ppDb = db;
  107831. #ifdef SQLITE_ENABLE_SQLLOG
  107832. if( sqlite3GlobalConfig.xSqllog ){
  107833. /* Opening a db handle. Fourth parameter is passed 0. */
  107834. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  107835. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  107836. }
  107837. #endif
  107838. return sqlite3ApiExit(0, rc);
  107839. }
  107840. /*
  107841. ** Open a new database handle.
  107842. */
  107843. SQLITE_API int sqlite3_open(
  107844. const char *zFilename,
  107845. sqlite3 **ppDb
  107846. ){
  107847. return openDatabase(zFilename, ppDb,
  107848. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  107849. }
  107850. SQLITE_API int sqlite3_open_v2(
  107851. const char *filename, /* Database filename (UTF-8) */
  107852. sqlite3 **ppDb, /* OUT: SQLite db handle */
  107853. int flags, /* Flags */
  107854. const char *zVfs /* Name of VFS module to use */
  107855. ){
  107856. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  107857. }
  107858. #ifndef SQLITE_OMIT_UTF16
  107859. /*
  107860. ** Open a new database handle.
  107861. */
  107862. SQLITE_API int sqlite3_open16(
  107863. const void *zFilename,
  107864. sqlite3 **ppDb
  107865. ){
  107866. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  107867. sqlite3_value *pVal;
  107868. int rc;
  107869. assert( zFilename );
  107870. assert( ppDb );
  107871. *ppDb = 0;
  107872. #ifndef SQLITE_OMIT_AUTOINIT
  107873. rc = sqlite3_initialize();
  107874. if( rc ) return rc;
  107875. #endif
  107876. pVal = sqlite3ValueNew(0);
  107877. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  107878. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  107879. if( zFilename8 ){
  107880. rc = openDatabase(zFilename8, ppDb,
  107881. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  107882. assert( *ppDb || rc==SQLITE_NOMEM );
  107883. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  107884. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  107885. }
  107886. }else{
  107887. rc = SQLITE_NOMEM;
  107888. }
  107889. sqlite3ValueFree(pVal);
  107890. return sqlite3ApiExit(0, rc);
  107891. }
  107892. #endif /* SQLITE_OMIT_UTF16 */
  107893. /*
  107894. ** Register a new collation sequence with the database handle db.
  107895. */
  107896. SQLITE_API int sqlite3_create_collation(
  107897. sqlite3* db,
  107898. const char *zName,
  107899. int enc,
  107900. void* pCtx,
  107901. int(*xCompare)(void*,int,const void*,int,const void*)
  107902. ){
  107903. int rc;
  107904. sqlite3_mutex_enter(db->mutex);
  107905. assert( !db->mallocFailed );
  107906. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  107907. rc = sqlite3ApiExit(db, rc);
  107908. sqlite3_mutex_leave(db->mutex);
  107909. return rc;
  107910. }
  107911. /*
  107912. ** Register a new collation sequence with the database handle db.
  107913. */
  107914. SQLITE_API int sqlite3_create_collation_v2(
  107915. sqlite3* db,
  107916. const char *zName,
  107917. int enc,
  107918. void* pCtx,
  107919. int(*xCompare)(void*,int,const void*,int,const void*),
  107920. void(*xDel)(void*)
  107921. ){
  107922. int rc;
  107923. sqlite3_mutex_enter(db->mutex);
  107924. assert( !db->mallocFailed );
  107925. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  107926. rc = sqlite3ApiExit(db, rc);
  107927. sqlite3_mutex_leave(db->mutex);
  107928. return rc;
  107929. }
  107930. #ifndef SQLITE_OMIT_UTF16
  107931. /*
  107932. ** Register a new collation sequence with the database handle db.
  107933. */
  107934. SQLITE_API int sqlite3_create_collation16(
  107935. sqlite3* db,
  107936. const void *zName,
  107937. int enc,
  107938. void* pCtx,
  107939. int(*xCompare)(void*,int,const void*,int,const void*)
  107940. ){
  107941. int rc = SQLITE_OK;
  107942. char *zName8;
  107943. sqlite3_mutex_enter(db->mutex);
  107944. assert( !db->mallocFailed );
  107945. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  107946. if( zName8 ){
  107947. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  107948. sqlite3DbFree(db, zName8);
  107949. }
  107950. rc = sqlite3ApiExit(db, rc);
  107951. sqlite3_mutex_leave(db->mutex);
  107952. return rc;
  107953. }
  107954. #endif /* SQLITE_OMIT_UTF16 */
  107955. /*
  107956. ** Register a collation sequence factory callback with the database handle
  107957. ** db. Replace any previously installed collation sequence factory.
  107958. */
  107959. SQLITE_API int sqlite3_collation_needed(
  107960. sqlite3 *db,
  107961. void *pCollNeededArg,
  107962. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  107963. ){
  107964. sqlite3_mutex_enter(db->mutex);
  107965. db->xCollNeeded = xCollNeeded;
  107966. db->xCollNeeded16 = 0;
  107967. db->pCollNeededArg = pCollNeededArg;
  107968. sqlite3_mutex_leave(db->mutex);
  107969. return SQLITE_OK;
  107970. }
  107971. #ifndef SQLITE_OMIT_UTF16
  107972. /*
  107973. ** Register a collation sequence factory callback with the database handle
  107974. ** db. Replace any previously installed collation sequence factory.
  107975. */
  107976. SQLITE_API int sqlite3_collation_needed16(
  107977. sqlite3 *db,
  107978. void *pCollNeededArg,
  107979. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  107980. ){
  107981. sqlite3_mutex_enter(db->mutex);
  107982. db->xCollNeeded = 0;
  107983. db->xCollNeeded16 = xCollNeeded16;
  107984. db->pCollNeededArg = pCollNeededArg;
  107985. sqlite3_mutex_leave(db->mutex);
  107986. return SQLITE_OK;
  107987. }
  107988. #endif /* SQLITE_OMIT_UTF16 */
  107989. #ifndef SQLITE_OMIT_DEPRECATED
  107990. /*
  107991. ** This function is now an anachronism. It used to be used to recover from a
  107992. ** malloc() failure, but SQLite now does this automatically.
  107993. */
  107994. SQLITE_API int sqlite3_global_recover(void){
  107995. return SQLITE_OK;
  107996. }
  107997. #endif
  107998. /*
  107999. ** Test to see whether or not the database connection is in autocommit
  108000. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  108001. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  108002. ** by the next COMMIT or ROLLBACK.
  108003. **
  108004. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  108005. */
  108006. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  108007. return db->autoCommit;
  108008. }
  108009. /*
  108010. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  108011. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  108012. ** constants. They server two purposes:
  108013. **
  108014. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  108015. ** to detect when version error conditions occurs.
  108016. **
  108017. ** 2. Invoke sqlite3_log() to provide the source code location where
  108018. ** a low-level error is first detected.
  108019. */
  108020. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  108021. testcase( sqlite3GlobalConfig.xLog!=0 );
  108022. sqlite3_log(SQLITE_CORRUPT,
  108023. "database corruption at line %d of [%.10s]",
  108024. lineno, 20+sqlite3_sourceid());
  108025. return SQLITE_CORRUPT;
  108026. }
  108027. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  108028. testcase( sqlite3GlobalConfig.xLog!=0 );
  108029. sqlite3_log(SQLITE_MISUSE,
  108030. "misuse at line %d of [%.10s]",
  108031. lineno, 20+sqlite3_sourceid());
  108032. return SQLITE_MISUSE;
  108033. }
  108034. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  108035. testcase( sqlite3GlobalConfig.xLog!=0 );
  108036. sqlite3_log(SQLITE_CANTOPEN,
  108037. "cannot open file at line %d of [%.10s]",
  108038. lineno, 20+sqlite3_sourceid());
  108039. return SQLITE_CANTOPEN;
  108040. }
  108041. #ifndef SQLITE_OMIT_DEPRECATED
  108042. /*
  108043. ** This is a convenience routine that makes sure that all thread-specific
  108044. ** data for this thread has been deallocated.
  108045. **
  108046. ** SQLite no longer uses thread-specific data so this routine is now a
  108047. ** no-op. It is retained for historical compatibility.
  108048. */
  108049. SQLITE_API void sqlite3_thread_cleanup(void){
  108050. }
  108051. #endif
  108052. /*
  108053. ** Return meta information about a specific column of a database table.
  108054. ** See comment in sqlite3.h (sqlite.h.in) for details.
  108055. */
  108056. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  108057. SQLITE_API int sqlite3_table_column_metadata(
  108058. sqlite3 *db, /* Connection handle */
  108059. const char *zDbName, /* Database name or NULL */
  108060. const char *zTableName, /* Table name */
  108061. const char *zColumnName, /* Column name */
  108062. char const **pzDataType, /* OUTPUT: Declared data type */
  108063. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  108064. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  108065. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  108066. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  108067. ){
  108068. int rc;
  108069. char *zErrMsg = 0;
  108070. Table *pTab = 0;
  108071. Column *pCol = 0;
  108072. int iCol;
  108073. char const *zDataType = 0;
  108074. char const *zCollSeq = 0;
  108075. int notnull = 0;
  108076. int primarykey = 0;
  108077. int autoinc = 0;
  108078. /* Ensure the database schema has been loaded */
  108079. sqlite3_mutex_enter(db->mutex);
  108080. sqlite3BtreeEnterAll(db);
  108081. rc = sqlite3Init(db, &zErrMsg);
  108082. if( SQLITE_OK!=rc ){
  108083. goto error_out;
  108084. }
  108085. /* Locate the table in question */
  108086. pTab = sqlite3FindTable(db, zTableName, zDbName);
  108087. if( !pTab || pTab->pSelect ){
  108088. pTab = 0;
  108089. goto error_out;
  108090. }
  108091. /* Find the column for which info is requested */
  108092. if( sqlite3IsRowid(zColumnName) ){
  108093. iCol = pTab->iPKey;
  108094. if( iCol>=0 ){
  108095. pCol = &pTab->aCol[iCol];
  108096. }
  108097. }else{
  108098. for(iCol=0; iCol<pTab->nCol; iCol++){
  108099. pCol = &pTab->aCol[iCol];
  108100. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  108101. break;
  108102. }
  108103. }
  108104. if( iCol==pTab->nCol ){
  108105. pTab = 0;
  108106. goto error_out;
  108107. }
  108108. }
  108109. /* The following block stores the meta information that will be returned
  108110. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  108111. ** and autoinc. At this point there are two possibilities:
  108112. **
  108113. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  108114. ** and there is no explicitly declared IPK column.
  108115. **
  108116. ** 2. The table is not a view and the column name identified an
  108117. ** explicitly declared column. Copy meta information from *pCol.
  108118. */
  108119. if( pCol ){
  108120. zDataType = pCol->zType;
  108121. zCollSeq = pCol->zColl;
  108122. notnull = pCol->notNull!=0;
  108123. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  108124. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  108125. }else{
  108126. zDataType = "INTEGER";
  108127. primarykey = 1;
  108128. }
  108129. if( !zCollSeq ){
  108130. zCollSeq = "BINARY";
  108131. }
  108132. error_out:
  108133. sqlite3BtreeLeaveAll(db);
  108134. /* Whether the function call succeeded or failed, set the output parameters
  108135. ** to whatever their local counterparts contain. If an error did occur,
  108136. ** this has the effect of zeroing all output parameters.
  108137. */
  108138. if( pzDataType ) *pzDataType = zDataType;
  108139. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  108140. if( pNotNull ) *pNotNull = notnull;
  108141. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  108142. if( pAutoinc ) *pAutoinc = autoinc;
  108143. if( SQLITE_OK==rc && !pTab ){
  108144. sqlite3DbFree(db, zErrMsg);
  108145. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  108146. zColumnName);
  108147. rc = SQLITE_ERROR;
  108148. }
  108149. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  108150. sqlite3DbFree(db, zErrMsg);
  108151. rc = sqlite3ApiExit(db, rc);
  108152. sqlite3_mutex_leave(db->mutex);
  108153. return rc;
  108154. }
  108155. #endif
  108156. /*
  108157. ** Sleep for a little while. Return the amount of time slept.
  108158. */
  108159. SQLITE_API int sqlite3_sleep(int ms){
  108160. sqlite3_vfs *pVfs;
  108161. int rc;
  108162. pVfs = sqlite3_vfs_find(0);
  108163. if( pVfs==0 ) return 0;
  108164. /* This function works in milliseconds, but the underlying OsSleep()
  108165. ** API uses microseconds. Hence the 1000's.
  108166. */
  108167. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  108168. return rc;
  108169. }
  108170. /*
  108171. ** Enable or disable the extended result codes.
  108172. */
  108173. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  108174. sqlite3_mutex_enter(db->mutex);
  108175. db->errMask = onoff ? 0xffffffff : 0xff;
  108176. sqlite3_mutex_leave(db->mutex);
  108177. return SQLITE_OK;
  108178. }
  108179. /*
  108180. ** Invoke the xFileControl method on a particular database.
  108181. */
  108182. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  108183. int rc = SQLITE_ERROR;
  108184. Btree *pBtree;
  108185. sqlite3_mutex_enter(db->mutex);
  108186. pBtree = sqlite3DbNameToBtree(db, zDbName);
  108187. if( pBtree ){
  108188. Pager *pPager;
  108189. sqlite3_file *fd;
  108190. sqlite3BtreeEnter(pBtree);
  108191. pPager = sqlite3BtreePager(pBtree);
  108192. assert( pPager!=0 );
  108193. fd = sqlite3PagerFile(pPager);
  108194. assert( fd!=0 );
  108195. if( op==SQLITE_FCNTL_FILE_POINTER ){
  108196. *(sqlite3_file**)pArg = fd;
  108197. rc = SQLITE_OK;
  108198. }else if( fd->pMethods ){
  108199. rc = sqlite3OsFileControl(fd, op, pArg);
  108200. }else{
  108201. rc = SQLITE_NOTFOUND;
  108202. }
  108203. sqlite3BtreeLeave(pBtree);
  108204. }
  108205. sqlite3_mutex_leave(db->mutex);
  108206. return rc;
  108207. }
  108208. /*
  108209. ** Interface to the testing logic.
  108210. */
  108211. SQLITE_API int sqlite3_test_control(int op, ...){
  108212. int rc = 0;
  108213. #ifndef SQLITE_OMIT_BUILTIN_TEST
  108214. va_list ap;
  108215. va_start(ap, op);
  108216. switch( op ){
  108217. /*
  108218. ** Save the current state of the PRNG.
  108219. */
  108220. case SQLITE_TESTCTRL_PRNG_SAVE: {
  108221. sqlite3PrngSaveState();
  108222. break;
  108223. }
  108224. /*
  108225. ** Restore the state of the PRNG to the last state saved using
  108226. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  108227. ** this verb acts like PRNG_RESET.
  108228. */
  108229. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  108230. sqlite3PrngRestoreState();
  108231. break;
  108232. }
  108233. /*
  108234. ** Reset the PRNG back to its uninitialized state. The next call
  108235. ** to sqlite3_randomness() will reseed the PRNG using a single call
  108236. ** to the xRandomness method of the default VFS.
  108237. */
  108238. case SQLITE_TESTCTRL_PRNG_RESET: {
  108239. sqlite3PrngResetState();
  108240. break;
  108241. }
  108242. /*
  108243. ** sqlite3_test_control(BITVEC_TEST, size, program)
  108244. **
  108245. ** Run a test against a Bitvec object of size. The program argument
  108246. ** is an array of integers that defines the test. Return -1 on a
  108247. ** memory allocation error, 0 on success, or non-zero for an error.
  108248. ** See the sqlite3BitvecBuiltinTest() for additional information.
  108249. */
  108250. case SQLITE_TESTCTRL_BITVEC_TEST: {
  108251. int sz = va_arg(ap, int);
  108252. int *aProg = va_arg(ap, int*);
  108253. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  108254. break;
  108255. }
  108256. /*
  108257. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  108258. **
  108259. ** Register hooks to call to indicate which malloc() failures
  108260. ** are benign.
  108261. */
  108262. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  108263. typedef void (*void_function)(void);
  108264. void_function xBenignBegin;
  108265. void_function xBenignEnd;
  108266. xBenignBegin = va_arg(ap, void_function);
  108267. xBenignEnd = va_arg(ap, void_function);
  108268. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  108269. break;
  108270. }
  108271. /*
  108272. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  108273. **
  108274. ** Set the PENDING byte to the value in the argument, if X>0.
  108275. ** Make no changes if X==0. Return the value of the pending byte
  108276. ** as it existing before this routine was called.
  108277. **
  108278. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  108279. ** an incompatible database file format. Changing the PENDING byte
  108280. ** while any database connection is open results in undefined and
  108281. ** dileterious behavior.
  108282. */
  108283. case SQLITE_TESTCTRL_PENDING_BYTE: {
  108284. rc = PENDING_BYTE;
  108285. #ifndef SQLITE_OMIT_WSD
  108286. {
  108287. unsigned int newVal = va_arg(ap, unsigned int);
  108288. if( newVal ) sqlite3PendingByte = newVal;
  108289. }
  108290. #endif
  108291. break;
  108292. }
  108293. /*
  108294. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  108295. **
  108296. ** This action provides a run-time test to see whether or not
  108297. ** assert() was enabled at compile-time. If X is true and assert()
  108298. ** is enabled, then the return value is true. If X is true and
  108299. ** assert() is disabled, then the return value is zero. If X is
  108300. ** false and assert() is enabled, then the assertion fires and the
  108301. ** process aborts. If X is false and assert() is disabled, then the
  108302. ** return value is zero.
  108303. */
  108304. case SQLITE_TESTCTRL_ASSERT: {
  108305. volatile int x = 0;
  108306. assert( (x = va_arg(ap,int))!=0 );
  108307. rc = x;
  108308. break;
  108309. }
  108310. /*
  108311. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  108312. **
  108313. ** This action provides a run-time test to see how the ALWAYS and
  108314. ** NEVER macros were defined at compile-time.
  108315. **
  108316. ** The return value is ALWAYS(X).
  108317. **
  108318. ** The recommended test is X==2. If the return value is 2, that means
  108319. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  108320. ** default setting. If the return value is 1, then ALWAYS() is either
  108321. ** hard-coded to true or else it asserts if its argument is false.
  108322. ** The first behavior (hard-coded to true) is the case if
  108323. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  108324. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  108325. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  108326. **
  108327. ** The run-time test procedure might look something like this:
  108328. **
  108329. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  108330. ** // ALWAYS() and NEVER() are no-op pass-through macros
  108331. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  108332. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  108333. ** }else{
  108334. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  108335. ** }
  108336. */
  108337. case SQLITE_TESTCTRL_ALWAYS: {
  108338. int x = va_arg(ap,int);
  108339. rc = ALWAYS(x);
  108340. break;
  108341. }
  108342. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  108343. **
  108344. ** Set the nReserve size to N for the main database on the database
  108345. ** connection db.
  108346. */
  108347. case SQLITE_TESTCTRL_RESERVE: {
  108348. sqlite3 *db = va_arg(ap, sqlite3*);
  108349. int x = va_arg(ap,int);
  108350. sqlite3_mutex_enter(db->mutex);
  108351. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  108352. sqlite3_mutex_leave(db->mutex);
  108353. break;
  108354. }
  108355. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  108356. **
  108357. ** Enable or disable various optimizations for testing purposes. The
  108358. ** argument N is a bitmask of optimizations to be disabled. For normal
  108359. ** operation N should be 0. The idea is that a test program (like the
  108360. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  108361. ** with various optimizations disabled to verify that the same answer
  108362. ** is obtained in every case.
  108363. */
  108364. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  108365. sqlite3 *db = va_arg(ap, sqlite3*);
  108366. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  108367. break;
  108368. }
  108369. #ifdef SQLITE_N_KEYWORD
  108370. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  108371. **
  108372. ** If zWord is a keyword recognized by the parser, then return the
  108373. ** number of keywords. Or if zWord is not a keyword, return 0.
  108374. **
  108375. ** This test feature is only available in the amalgamation since
  108376. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  108377. ** is built using separate source files.
  108378. */
  108379. case SQLITE_TESTCTRL_ISKEYWORD: {
  108380. const char *zWord = va_arg(ap, const char*);
  108381. int n = sqlite3Strlen30(zWord);
  108382. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  108383. break;
  108384. }
  108385. #endif
  108386. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  108387. **
  108388. ** Pass pFree into sqlite3ScratchFree().
  108389. ** If sz>0 then allocate a scratch buffer into pNew.
  108390. */
  108391. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  108392. void *pFree, **ppNew;
  108393. int sz;
  108394. sz = va_arg(ap, int);
  108395. ppNew = va_arg(ap, void**);
  108396. pFree = va_arg(ap, void*);
  108397. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  108398. sqlite3ScratchFree(pFree);
  108399. break;
  108400. }
  108401. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  108402. **
  108403. ** If parameter onoff is non-zero, configure the wrappers so that all
  108404. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  108405. ** undo this setting.
  108406. */
  108407. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  108408. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  108409. break;
  108410. }
  108411. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  108412. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  108413. ** sqlite3_stmt*,const char**);
  108414. **
  108415. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  108416. ** a string that describes the optimized parse tree. This test-control
  108417. ** returns a pointer to that string.
  108418. */
  108419. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  108420. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  108421. const char **pzRet = va_arg(ap, const char**);
  108422. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  108423. break;
  108424. }
  108425. #endif
  108426. }
  108427. va_end(ap);
  108428. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  108429. return rc;
  108430. }
  108431. /*
  108432. ** This is a utility routine, useful to VFS implementations, that checks
  108433. ** to see if a database file was a URI that contained a specific query
  108434. ** parameter, and if so obtains the value of the query parameter.
  108435. **
  108436. ** The zFilename argument is the filename pointer passed into the xOpen()
  108437. ** method of a VFS implementation. The zParam argument is the name of the
  108438. ** query parameter we seek. This routine returns the value of the zParam
  108439. ** parameter if it exists. If the parameter does not exist, this routine
  108440. ** returns a NULL pointer.
  108441. */
  108442. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  108443. if( zFilename==0 ) return 0;
  108444. zFilename += sqlite3Strlen30(zFilename) + 1;
  108445. while( zFilename[0] ){
  108446. int x = strcmp(zFilename, zParam);
  108447. zFilename += sqlite3Strlen30(zFilename) + 1;
  108448. if( x==0 ) return zFilename;
  108449. zFilename += sqlite3Strlen30(zFilename) + 1;
  108450. }
  108451. return 0;
  108452. }
  108453. /*
  108454. ** Return a boolean value for a query parameter.
  108455. */
  108456. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  108457. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  108458. bDflt = bDflt!=0;
  108459. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  108460. }
  108461. /*
  108462. ** Return a 64-bit integer value for a query parameter.
  108463. */
  108464. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  108465. const char *zFilename, /* Filename as passed to xOpen */
  108466. const char *zParam, /* URI parameter sought */
  108467. sqlite3_int64 bDflt /* return if parameter is missing */
  108468. ){
  108469. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  108470. sqlite3_int64 v;
  108471. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  108472. bDflt = v;
  108473. }
  108474. return bDflt;
  108475. }
  108476. /*
  108477. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  108478. */
  108479. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  108480. int i;
  108481. for(i=0; i<db->nDb; i++){
  108482. if( db->aDb[i].pBt
  108483. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  108484. ){
  108485. return db->aDb[i].pBt;
  108486. }
  108487. }
  108488. return 0;
  108489. }
  108490. /*
  108491. ** Return the filename of the database associated with a database
  108492. ** connection.
  108493. */
  108494. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  108495. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  108496. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  108497. }
  108498. /*
  108499. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  108500. ** no such database exists.
  108501. */
  108502. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  108503. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  108504. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  108505. }
  108506. /************** End of main.c ************************************************/
  108507. /************** Begin file notify.c ******************************************/
  108508. /*
  108509. ** 2009 March 3
  108510. **
  108511. ** The author disclaims copyright to this source code. In place of
  108512. ** a legal notice, here is a blessing:
  108513. **
  108514. ** May you do good and not evil.
  108515. ** May you find forgiveness for yourself and forgive others.
  108516. ** May you share freely, never taking more than you give.
  108517. **
  108518. *************************************************************************
  108519. **
  108520. ** This file contains the implementation of the sqlite3_unlock_notify()
  108521. ** API method and its associated functionality.
  108522. */
  108523. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  108524. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  108525. /*
  108526. ** Public interfaces:
  108527. **
  108528. ** sqlite3ConnectionBlocked()
  108529. ** sqlite3ConnectionUnlocked()
  108530. ** sqlite3ConnectionClosed()
  108531. ** sqlite3_unlock_notify()
  108532. */
  108533. #define assertMutexHeld() \
  108534. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  108535. /*
  108536. ** Head of a linked list of all sqlite3 objects created by this process
  108537. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  108538. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  108539. ** mutex is held.
  108540. */
  108541. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  108542. #ifndef NDEBUG
  108543. /*
  108544. ** This function is a complex assert() that verifies the following
  108545. ** properties of the blocked connections list:
  108546. **
  108547. ** 1) Each entry in the list has a non-NULL value for either
  108548. ** pUnlockConnection or pBlockingConnection, or both.
  108549. **
  108550. ** 2) All entries in the list that share a common value for
  108551. ** xUnlockNotify are grouped together.
  108552. **
  108553. ** 3) If the argument db is not NULL, then none of the entries in the
  108554. ** blocked connections list have pUnlockConnection or pBlockingConnection
  108555. ** set to db. This is used when closing connection db.
  108556. */
  108557. static void checkListProperties(sqlite3 *db){
  108558. sqlite3 *p;
  108559. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  108560. int seen = 0;
  108561. sqlite3 *p2;
  108562. /* Verify property (1) */
  108563. assert( p->pUnlockConnection || p->pBlockingConnection );
  108564. /* Verify property (2) */
  108565. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  108566. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  108567. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  108568. assert( db==0 || p->pUnlockConnection!=db );
  108569. assert( db==0 || p->pBlockingConnection!=db );
  108570. }
  108571. }
  108572. }
  108573. #else
  108574. # define checkListProperties(x)
  108575. #endif
  108576. /*
  108577. ** Remove connection db from the blocked connections list. If connection
  108578. ** db is not currently a part of the list, this function is a no-op.
  108579. */
  108580. static void removeFromBlockedList(sqlite3 *db){
  108581. sqlite3 **pp;
  108582. assertMutexHeld();
  108583. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  108584. if( *pp==db ){
  108585. *pp = (*pp)->pNextBlocked;
  108586. break;
  108587. }
  108588. }
  108589. }
  108590. /*
  108591. ** Add connection db to the blocked connections list. It is assumed
  108592. ** that it is not already a part of the list.
  108593. */
  108594. static void addToBlockedList(sqlite3 *db){
  108595. sqlite3 **pp;
  108596. assertMutexHeld();
  108597. for(
  108598. pp=&sqlite3BlockedList;
  108599. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  108600. pp=&(*pp)->pNextBlocked
  108601. );
  108602. db->pNextBlocked = *pp;
  108603. *pp = db;
  108604. }
  108605. /*
  108606. ** Obtain the STATIC_MASTER mutex.
  108607. */
  108608. static void enterMutex(void){
  108609. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  108610. checkListProperties(0);
  108611. }
  108612. /*
  108613. ** Release the STATIC_MASTER mutex.
  108614. */
  108615. static void leaveMutex(void){
  108616. assertMutexHeld();
  108617. checkListProperties(0);
  108618. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  108619. }
  108620. /*
  108621. ** Register an unlock-notify callback.
  108622. **
  108623. ** This is called after connection "db" has attempted some operation
  108624. ** but has received an SQLITE_LOCKED error because another connection
  108625. ** (call it pOther) in the same process was busy using the same shared
  108626. ** cache. pOther is found by looking at db->pBlockingConnection.
  108627. **
  108628. ** If there is no blocking connection, the callback is invoked immediately,
  108629. ** before this routine returns.
  108630. **
  108631. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  108632. ** a deadlock.
  108633. **
  108634. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  108635. ** its locks.
  108636. **
  108637. ** Each call to this routine overrides any prior callbacks registered
  108638. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  108639. ** cancelled.
  108640. */
  108641. SQLITE_API int sqlite3_unlock_notify(
  108642. sqlite3 *db,
  108643. void (*xNotify)(void **, int),
  108644. void *pArg
  108645. ){
  108646. int rc = SQLITE_OK;
  108647. sqlite3_mutex_enter(db->mutex);
  108648. enterMutex();
  108649. if( xNotify==0 ){
  108650. removeFromBlockedList(db);
  108651. db->pBlockingConnection = 0;
  108652. db->pUnlockConnection = 0;
  108653. db->xUnlockNotify = 0;
  108654. db->pUnlockArg = 0;
  108655. }else if( 0==db->pBlockingConnection ){
  108656. /* The blocking transaction has been concluded. Or there never was a
  108657. ** blocking transaction. In either case, invoke the notify callback
  108658. ** immediately.
  108659. */
  108660. xNotify(&pArg, 1);
  108661. }else{
  108662. sqlite3 *p;
  108663. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  108664. if( p ){
  108665. rc = SQLITE_LOCKED; /* Deadlock detected. */
  108666. }else{
  108667. db->pUnlockConnection = db->pBlockingConnection;
  108668. db->xUnlockNotify = xNotify;
  108669. db->pUnlockArg = pArg;
  108670. removeFromBlockedList(db);
  108671. addToBlockedList(db);
  108672. }
  108673. }
  108674. leaveMutex();
  108675. assert( !db->mallocFailed );
  108676. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  108677. sqlite3_mutex_leave(db->mutex);
  108678. return rc;
  108679. }
  108680. /*
  108681. ** This function is called while stepping or preparing a statement
  108682. ** associated with connection db. The operation will return SQLITE_LOCKED
  108683. ** to the user because it requires a lock that will not be available
  108684. ** until connection pBlocker concludes its current transaction.
  108685. */
  108686. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  108687. enterMutex();
  108688. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  108689. addToBlockedList(db);
  108690. }
  108691. db->pBlockingConnection = pBlocker;
  108692. leaveMutex();
  108693. }
  108694. /*
  108695. ** This function is called when
  108696. ** the transaction opened by database db has just finished. Locks held
  108697. ** by database connection db have been released.
  108698. **
  108699. ** This function loops through each entry in the blocked connections
  108700. ** list and does the following:
  108701. **
  108702. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  108703. ** set to db, then set pBlockingConnection=0.
  108704. **
  108705. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  108706. ** set to db, then invoke the configured unlock-notify callback and
  108707. ** set pUnlockConnection=0.
  108708. **
  108709. ** 3) If the two steps above mean that pBlockingConnection==0 and
  108710. ** pUnlockConnection==0, remove the entry from the blocked connections
  108711. ** list.
  108712. */
  108713. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  108714. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  108715. int nArg = 0; /* Number of entries in aArg[] */
  108716. sqlite3 **pp; /* Iterator variable */
  108717. void **aArg; /* Arguments to the unlock callback */
  108718. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  108719. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  108720. aArg = aStatic;
  108721. enterMutex(); /* Enter STATIC_MASTER mutex */
  108722. /* This loop runs once for each entry in the blocked-connections list. */
  108723. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  108724. sqlite3 *p = *pp;
  108725. /* Step 1. */
  108726. if( p->pBlockingConnection==db ){
  108727. p->pBlockingConnection = 0;
  108728. }
  108729. /* Step 2. */
  108730. if( p->pUnlockConnection==db ){
  108731. assert( p->xUnlockNotify );
  108732. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  108733. xUnlockNotify(aArg, nArg);
  108734. nArg = 0;
  108735. }
  108736. sqlite3BeginBenignMalloc();
  108737. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  108738. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  108739. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  108740. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  108741. ){
  108742. /* The aArg[] array needs to grow. */
  108743. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  108744. if( pNew ){
  108745. memcpy(pNew, aArg, nArg*sizeof(void *));
  108746. sqlite3_free(aDyn);
  108747. aDyn = aArg = pNew;
  108748. }else{
  108749. /* This occurs when the array of context pointers that need to
  108750. ** be passed to the unlock-notify callback is larger than the
  108751. ** aStatic[] array allocated on the stack and the attempt to
  108752. ** allocate a larger array from the heap has failed.
  108753. **
  108754. ** This is a difficult situation to handle. Returning an error
  108755. ** code to the caller is insufficient, as even if an error code
  108756. ** is returned the transaction on connection db will still be
  108757. ** closed and the unlock-notify callbacks on blocked connections
  108758. ** will go unissued. This might cause the application to wait
  108759. ** indefinitely for an unlock-notify callback that will never
  108760. ** arrive.
  108761. **
  108762. ** Instead, invoke the unlock-notify callback with the context
  108763. ** array already accumulated. We can then clear the array and
  108764. ** begin accumulating any further context pointers without
  108765. ** requiring any dynamic allocation. This is sub-optimal because
  108766. ** it means that instead of one callback with a large array of
  108767. ** context pointers the application will receive two or more
  108768. ** callbacks with smaller arrays of context pointers, which will
  108769. ** reduce the applications ability to prioritize multiple
  108770. ** connections. But it is the best that can be done under the
  108771. ** circumstances.
  108772. */
  108773. xUnlockNotify(aArg, nArg);
  108774. nArg = 0;
  108775. }
  108776. }
  108777. sqlite3EndBenignMalloc();
  108778. aArg[nArg++] = p->pUnlockArg;
  108779. xUnlockNotify = p->xUnlockNotify;
  108780. p->pUnlockConnection = 0;
  108781. p->xUnlockNotify = 0;
  108782. p->pUnlockArg = 0;
  108783. }
  108784. /* Step 3. */
  108785. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  108786. /* Remove connection p from the blocked connections list. */
  108787. *pp = p->pNextBlocked;
  108788. p->pNextBlocked = 0;
  108789. }else{
  108790. pp = &p->pNextBlocked;
  108791. }
  108792. }
  108793. if( nArg!=0 ){
  108794. xUnlockNotify(aArg, nArg);
  108795. }
  108796. sqlite3_free(aDyn);
  108797. leaveMutex(); /* Leave STATIC_MASTER mutex */
  108798. }
  108799. /*
  108800. ** This is called when the database connection passed as an argument is
  108801. ** being closed. The connection is removed from the blocked list.
  108802. */
  108803. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  108804. sqlite3ConnectionUnlocked(db);
  108805. enterMutex();
  108806. removeFromBlockedList(db);
  108807. checkListProperties(db);
  108808. leaveMutex();
  108809. }
  108810. #endif
  108811. /************** End of notify.c **********************************************/
  108812. /************** Begin file fts3.c ********************************************/
  108813. /*
  108814. ** 2006 Oct 10
  108815. **
  108816. ** The author disclaims copyright to this source code. In place of
  108817. ** a legal notice, here is a blessing:
  108818. **
  108819. ** May you do good and not evil.
  108820. ** May you find forgiveness for yourself and forgive others.
  108821. ** May you share freely, never taking more than you give.
  108822. **
  108823. ******************************************************************************
  108824. **
  108825. ** This is an SQLite module implementing full-text search.
  108826. */
  108827. /*
  108828. ** The code in this file is only compiled if:
  108829. **
  108830. ** * The FTS3 module is being built as an extension
  108831. ** (in which case SQLITE_CORE is not defined), or
  108832. **
  108833. ** * The FTS3 module is being built into the core of
  108834. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  108835. */
  108836. /* The full-text index is stored in a series of b+tree (-like)
  108837. ** structures called segments which map terms to doclists. The
  108838. ** structures are like b+trees in layout, but are constructed from the
  108839. ** bottom up in optimal fashion and are not updatable. Since trees
  108840. ** are built from the bottom up, things will be described from the
  108841. ** bottom up.
  108842. **
  108843. **
  108844. **** Varints ****
  108845. ** The basic unit of encoding is a variable-length integer called a
  108846. ** varint. We encode variable-length integers in little-endian order
  108847. ** using seven bits * per byte as follows:
  108848. **
  108849. ** KEY:
  108850. ** A = 0xxxxxxx 7 bits of data and one flag bit
  108851. ** B = 1xxxxxxx 7 bits of data and one flag bit
  108852. **
  108853. ** 7 bits - A
  108854. ** 14 bits - BA
  108855. ** 21 bits - BBA
  108856. ** and so on.
  108857. **
  108858. ** This is similar in concept to how sqlite encodes "varints" but
  108859. ** the encoding is not the same. SQLite varints are big-endian
  108860. ** are are limited to 9 bytes in length whereas FTS3 varints are
  108861. ** little-endian and can be up to 10 bytes in length (in theory).
  108862. **
  108863. ** Example encodings:
  108864. **
  108865. ** 1: 0x01
  108866. ** 127: 0x7f
  108867. ** 128: 0x81 0x00
  108868. **
  108869. **
  108870. **** Document lists ****
  108871. ** A doclist (document list) holds a docid-sorted list of hits for a
  108872. ** given term. Doclists hold docids and associated token positions.
  108873. ** A docid is the unique integer identifier for a single document.
  108874. ** A position is the index of a word within the document. The first
  108875. ** word of the document has a position of 0.
  108876. **
  108877. ** FTS3 used to optionally store character offsets using a compile-time
  108878. ** option. But that functionality is no longer supported.
  108879. **
  108880. ** A doclist is stored like this:
  108881. **
  108882. ** array {
  108883. ** varint docid; (delta from previous doclist)
  108884. ** array { (position list for column 0)
  108885. ** varint position; (2 more than the delta from previous position)
  108886. ** }
  108887. ** array {
  108888. ** varint POS_COLUMN; (marks start of position list for new column)
  108889. ** varint column; (index of new column)
  108890. ** array {
  108891. ** varint position; (2 more than the delta from previous position)
  108892. ** }
  108893. ** }
  108894. ** varint POS_END; (marks end of positions for this document.
  108895. ** }
  108896. **
  108897. ** Here, array { X } means zero or more occurrences of X, adjacent in
  108898. ** memory. A "position" is an index of a token in the token stream
  108899. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  108900. ** in the same logical place as the position element, and act as sentinals
  108901. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  108902. ** The positions numbers are not stored literally but rather as two more
  108903. ** than the difference from the prior position, or the just the position plus
  108904. ** 2 for the first position. Example:
  108905. **
  108906. ** label: A B C D E F G H I J K
  108907. ** value: 123 5 9 1 1 14 35 0 234 72 0
  108908. **
  108909. ** The 123 value is the first docid. For column zero in this document
  108910. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  108911. ** at D signals the start of a new column; the 1 at E indicates that the
  108912. ** new column is column number 1. There are two positions at 12 and 45
  108913. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  108914. ** 234 at I is the delta to next docid (357). It has one position 70
  108915. ** (72-2) and then terminates with the 0 at K.
  108916. **
  108917. ** A "position-list" is the list of positions for multiple columns for
  108918. ** a single docid. A "column-list" is the set of positions for a single
  108919. ** column. Hence, a position-list consists of one or more column-lists,
  108920. ** a document record consists of a docid followed by a position-list and
  108921. ** a doclist consists of one or more document records.
  108922. **
  108923. ** A bare doclist omits the position information, becoming an
  108924. ** array of varint-encoded docids.
  108925. **
  108926. **** Segment leaf nodes ****
  108927. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  108928. ** nodes are written using LeafWriter, and read using LeafReader (to
  108929. ** iterate through a single leaf node's data) and LeavesReader (to
  108930. ** iterate through a segment's entire leaf layer). Leaf nodes have
  108931. ** the format:
  108932. **
  108933. ** varint iHeight; (height from leaf level, always 0)
  108934. ** varint nTerm; (length of first term)
  108935. ** char pTerm[nTerm]; (content of first term)
  108936. ** varint nDoclist; (length of term's associated doclist)
  108937. ** char pDoclist[nDoclist]; (content of doclist)
  108938. ** array {
  108939. ** (further terms are delta-encoded)
  108940. ** varint nPrefix; (length of prefix shared with previous term)
  108941. ** varint nSuffix; (length of unshared suffix)
  108942. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  108943. ** varint nDoclist; (length of term's associated doclist)
  108944. ** char pDoclist[nDoclist]; (content of doclist)
  108945. ** }
  108946. **
  108947. ** Here, array { X } means zero or more occurrences of X, adjacent in
  108948. ** memory.
  108949. **
  108950. ** Leaf nodes are broken into blocks which are stored contiguously in
  108951. ** the %_segments table in sorted order. This means that when the end
  108952. ** of a node is reached, the next term is in the node with the next
  108953. ** greater node id.
  108954. **
  108955. ** New data is spilled to a new leaf node when the current node
  108956. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  108957. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  108958. ** node (a leaf node with a single term and doclist). The goal of
  108959. ** these settings is to pack together groups of small doclists while
  108960. ** making it efficient to directly access large doclists. The
  108961. ** assumption is that large doclists represent terms which are more
  108962. ** likely to be query targets.
  108963. **
  108964. ** TODO(shess) It may be useful for blocking decisions to be more
  108965. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  108966. ** node rather than splitting into 2k and .5k nodes. My intuition is
  108967. ** that this might extend through 2x or 4x the pagesize.
  108968. **
  108969. **
  108970. **** Segment interior nodes ****
  108971. ** Segment interior nodes store blockids for subtree nodes and terms
  108972. ** to describe what data is stored by the each subtree. Interior
  108973. ** nodes are written using InteriorWriter, and read using
  108974. ** InteriorReader. InteriorWriters are created as needed when
  108975. ** SegmentWriter creates new leaf nodes, or when an interior node
  108976. ** itself grows too big and must be split. The format of interior
  108977. ** nodes:
  108978. **
  108979. ** varint iHeight; (height from leaf level, always >0)
  108980. ** varint iBlockid; (block id of node's leftmost subtree)
  108981. ** optional {
  108982. ** varint nTerm; (length of first term)
  108983. ** char pTerm[nTerm]; (content of first term)
  108984. ** array {
  108985. ** (further terms are delta-encoded)
  108986. ** varint nPrefix; (length of shared prefix with previous term)
  108987. ** varint nSuffix; (length of unshared suffix)
  108988. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  108989. ** }
  108990. ** }
  108991. **
  108992. ** Here, optional { X } means an optional element, while array { X }
  108993. ** means zero or more occurrences of X, adjacent in memory.
  108994. **
  108995. ** An interior node encodes n terms separating n+1 subtrees. The
  108996. ** subtree blocks are contiguous, so only the first subtree's blockid
  108997. ** is encoded. The subtree at iBlockid will contain all terms less
  108998. ** than the first term encoded (or all terms if no term is encoded).
  108999. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  109000. ** than pTerm[i+1], the subtree for that term will be rooted at
  109001. ** iBlockid+i. Interior nodes only store enough term data to
  109002. ** distinguish adjacent children (if the rightmost term of the left
  109003. ** child is "something", and the leftmost term of the right child is
  109004. ** "wicked", only "w" is stored).
  109005. **
  109006. ** New data is spilled to a new interior node at the same height when
  109007. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  109008. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  109009. ** interior nodes and making the tree too skinny. The interior nodes
  109010. ** at a given height are naturally tracked by interior nodes at
  109011. ** height+1, and so on.
  109012. **
  109013. **
  109014. **** Segment directory ****
  109015. ** The segment directory in table %_segdir stores meta-information for
  109016. ** merging and deleting segments, and also the root node of the
  109017. ** segment's tree.
  109018. **
  109019. ** The root node is the top node of the segment's tree after encoding
  109020. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  109021. ** This could be either a leaf node or an interior node. If the top
  109022. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  109023. ** and a new root interior node is generated (which should always fit
  109024. ** within ROOT_MAX because it only needs space for 2 varints, the
  109025. ** height and the blockid of the previous root).
  109026. **
  109027. ** The meta-information in the segment directory is:
  109028. ** level - segment level (see below)
  109029. ** idx - index within level
  109030. ** - (level,idx uniquely identify a segment)
  109031. ** start_block - first leaf node
  109032. ** leaves_end_block - last leaf node
  109033. ** end_block - last block (including interior nodes)
  109034. ** root - contents of root node
  109035. **
  109036. ** If the root node is a leaf node, then start_block,
  109037. ** leaves_end_block, and end_block are all 0.
  109038. **
  109039. **
  109040. **** Segment merging ****
  109041. ** To amortize update costs, segments are grouped into levels and
  109042. ** merged in batches. Each increase in level represents exponentially
  109043. ** more documents.
  109044. **
  109045. ** New documents (actually, document updates) are tokenized and
  109046. ** written individually (using LeafWriter) to a level 0 segment, with
  109047. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  109048. ** level 0 segments are merged into a single level 1 segment. Level 1
  109049. ** is populated like level 0, and eventually MERGE_COUNT level 1
  109050. ** segments are merged to a single level 2 segment (representing
  109051. ** MERGE_COUNT^2 updates), and so on.
  109052. **
  109053. ** A segment merge traverses all segments at a given level in
  109054. ** parallel, performing a straightforward sorted merge. Since segment
  109055. ** leaf nodes are written in to the %_segments table in order, this
  109056. ** merge traverses the underlying sqlite disk structures efficiently.
  109057. ** After the merge, all segment blocks from the merged level are
  109058. ** deleted.
  109059. **
  109060. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  109061. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  109062. ** very similar performance numbers to 16 on insertion, though they're
  109063. ** a tiny bit slower (perhaps due to more overhead in merge-time
  109064. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  109065. ** 16, 2 about 66% slower than 16.
  109066. **
  109067. ** At query time, high MERGE_COUNT increases the number of segments
  109068. ** which need to be scanned and merged. For instance, with 100k docs
  109069. ** inserted:
  109070. **
  109071. ** MERGE_COUNT segments
  109072. ** 16 25
  109073. ** 8 12
  109074. ** 4 10
  109075. ** 2 6
  109076. **
  109077. ** This appears to have only a moderate impact on queries for very
  109078. ** frequent terms (which are somewhat dominated by segment merge
  109079. ** costs), and infrequent and non-existent terms still seem to be fast
  109080. ** even with many segments.
  109081. **
  109082. ** TODO(shess) That said, it would be nice to have a better query-side
  109083. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  109084. ** optimizations to things like doclist merging will swing the sweet
  109085. ** spot around.
  109086. **
  109087. **
  109088. **
  109089. **** Handling of deletions and updates ****
  109090. ** Since we're using a segmented structure, with no docid-oriented
  109091. ** index into the term index, we clearly cannot simply update the term
  109092. ** index when a document is deleted or updated. For deletions, we
  109093. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  109094. ** we simply write the new doclist. Segment merges overwrite older
  109095. ** data for a particular docid with newer data, so deletes or updates
  109096. ** will eventually overtake the earlier data and knock it out. The
  109097. ** query logic likewise merges doclists so that newer data knocks out
  109098. ** older data.
  109099. */
  109100. /************** Include fts3Int.h in the middle of fts3.c ********************/
  109101. /************** Begin file fts3Int.h *****************************************/
  109102. /*
  109103. ** 2009 Nov 12
  109104. **
  109105. ** The author disclaims copyright to this source code. In place of
  109106. ** a legal notice, here is a blessing:
  109107. **
  109108. ** May you do good and not evil.
  109109. ** May you find forgiveness for yourself and forgive others.
  109110. ** May you share freely, never taking more than you give.
  109111. **
  109112. ******************************************************************************
  109113. **
  109114. */
  109115. #ifndef _FTSINT_H
  109116. #define _FTSINT_H
  109117. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  109118. # define NDEBUG 1
  109119. #endif
  109120. /*
  109121. ** FTS4 is really an extension for FTS3. It is enabled using the
  109122. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  109123. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  109124. */
  109125. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  109126. # define SQLITE_ENABLE_FTS3
  109127. #endif
  109128. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109129. /* If not building as part of the core, include sqlite3ext.h. */
  109130. #ifndef SQLITE_CORE
  109131. SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
  109132. #endif
  109133. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  109134. /************** Begin file fts3_tokenizer.h **********************************/
  109135. /*
  109136. ** 2006 July 10
  109137. **
  109138. ** The author disclaims copyright to this source code.
  109139. **
  109140. *************************************************************************
  109141. ** Defines the interface to tokenizers used by fulltext-search. There
  109142. ** are three basic components:
  109143. **
  109144. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  109145. ** interface functions. This is essentially the class structure for
  109146. ** tokenizers.
  109147. **
  109148. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  109149. ** including customization information defined at creation time.
  109150. **
  109151. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  109152. ** tokens from a particular input.
  109153. */
  109154. #ifndef _FTS3_TOKENIZER_H_
  109155. #define _FTS3_TOKENIZER_H_
  109156. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  109157. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  109158. ** we will need a way to register the API consistently.
  109159. */
  109160. /*
  109161. ** Structures used by the tokenizer interface. When a new tokenizer
  109162. ** implementation is registered, the caller provides a pointer to
  109163. ** an sqlite3_tokenizer_module containing pointers to the callback
  109164. ** functions that make up an implementation.
  109165. **
  109166. ** When an fts3 table is created, it passes any arguments passed to
  109167. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  109168. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  109169. ** implementation. The xCreate() function in turn returns an
  109170. ** sqlite3_tokenizer structure representing the specific tokenizer to
  109171. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  109172. **
  109173. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  109174. ** method is called. It returns an sqlite3_tokenizer_cursor object
  109175. ** that may be used to tokenize a specific input buffer based on
  109176. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  109177. ** object.
  109178. */
  109179. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  109180. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  109181. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  109182. struct sqlite3_tokenizer_module {
  109183. /*
  109184. ** Structure version. Should always be set to 0 or 1.
  109185. */
  109186. int iVersion;
  109187. /*
  109188. ** Create a new tokenizer. The values in the argv[] array are the
  109189. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  109190. ** TABLE statement that created the fts3 table. For example, if
  109191. ** the following SQL is executed:
  109192. **
  109193. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  109194. **
  109195. ** then argc is set to 2, and the argv[] array contains pointers
  109196. ** to the strings "arg1" and "arg2".
  109197. **
  109198. ** This method should return either SQLITE_OK (0), or an SQLite error
  109199. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  109200. ** to point at the newly created tokenizer structure. The generic
  109201. ** sqlite3_tokenizer.pModule variable should not be initialised by
  109202. ** this callback. The caller will do so.
  109203. */
  109204. int (*xCreate)(
  109205. int argc, /* Size of argv array */
  109206. const char *const*argv, /* Tokenizer argument strings */
  109207. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  109208. );
  109209. /*
  109210. ** Destroy an existing tokenizer. The fts3 module calls this method
  109211. ** exactly once for each successful call to xCreate().
  109212. */
  109213. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  109214. /*
  109215. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  109216. ** is responsible for ensuring that the input buffer remains valid
  109217. ** until the cursor is closed (using the xClose() method).
  109218. */
  109219. int (*xOpen)(
  109220. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  109221. const char *pInput, int nBytes, /* Input buffer */
  109222. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  109223. );
  109224. /*
  109225. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  109226. ** method exactly once for each successful call to xOpen().
  109227. */
  109228. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  109229. /*
  109230. ** Retrieve the next token from the tokenizer cursor pCursor. This
  109231. ** method should either return SQLITE_OK and set the values of the
  109232. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  109233. ** the end of the buffer has been reached, or an SQLite error code.
  109234. **
  109235. ** *ppToken should be set to point at a buffer containing the
  109236. ** normalized version of the token (i.e. after any case-folding and/or
  109237. ** stemming has been performed). *pnBytes should be set to the length
  109238. ** of this buffer in bytes. The input text that generated the token is
  109239. ** identified by the byte offsets returned in *piStartOffset and
  109240. ** *piEndOffset. *piStartOffset should be set to the index of the first
  109241. ** byte of the token in the input buffer. *piEndOffset should be set
  109242. ** to the index of the first byte just past the end of the token in
  109243. ** the input buffer.
  109244. **
  109245. ** The buffer *ppToken is set to point at is managed by the tokenizer
  109246. ** implementation. It is only required to be valid until the next call
  109247. ** to xNext() or xClose().
  109248. */
  109249. /* TODO(shess) current implementation requires pInput to be
  109250. ** nul-terminated. This should either be fixed, or pInput/nBytes
  109251. ** should be converted to zInput.
  109252. */
  109253. int (*xNext)(
  109254. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  109255. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  109256. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  109257. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  109258. int *piPosition /* OUT: Number of tokens returned before this one */
  109259. );
  109260. /***********************************************************************
  109261. ** Methods below this point are only available if iVersion>=1.
  109262. */
  109263. /*
  109264. ** Configure the language id of a tokenizer cursor.
  109265. */
  109266. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  109267. };
  109268. struct sqlite3_tokenizer {
  109269. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  109270. /* Tokenizer implementations will typically add additional fields */
  109271. };
  109272. struct sqlite3_tokenizer_cursor {
  109273. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  109274. /* Tokenizer implementations will typically add additional fields */
  109275. };
  109276. int fts3_global_term_cnt(int iTerm, int iCol);
  109277. int fts3_term_cnt(int iTerm, int iCol);
  109278. #endif /* _FTS3_TOKENIZER_H_ */
  109279. /************** End of fts3_tokenizer.h **************************************/
  109280. /************** Continuing where we left off in fts3Int.h ********************/
  109281. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  109282. /************** Begin file fts3_hash.h ***************************************/
  109283. /*
  109284. ** 2001 September 22
  109285. **
  109286. ** The author disclaims copyright to this source code. In place of
  109287. ** a legal notice, here is a blessing:
  109288. **
  109289. ** May you do good and not evil.
  109290. ** May you find forgiveness for yourself and forgive others.
  109291. ** May you share freely, never taking more than you give.
  109292. **
  109293. *************************************************************************
  109294. ** This is the header file for the generic hash-table implemenation
  109295. ** used in SQLite. We've modified it slightly to serve as a standalone
  109296. ** hash table implementation for the full-text indexing module.
  109297. **
  109298. */
  109299. #ifndef _FTS3_HASH_H_
  109300. #define _FTS3_HASH_H_
  109301. /* Forward declarations of structures. */
  109302. typedef struct Fts3Hash Fts3Hash;
  109303. typedef struct Fts3HashElem Fts3HashElem;
  109304. /* A complete hash table is an instance of the following structure.
  109305. ** The internals of this structure are intended to be opaque -- client
  109306. ** code should not attempt to access or modify the fields of this structure
  109307. ** directly. Change this structure only by using the routines below.
  109308. ** However, many of the "procedures" and "functions" for modifying and
  109309. ** accessing this structure are really macros, so we can't really make
  109310. ** this structure opaque.
  109311. */
  109312. struct Fts3Hash {
  109313. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  109314. char copyKey; /* True if copy of key made on insert */
  109315. int count; /* Number of entries in this table */
  109316. Fts3HashElem *first; /* The first element of the array */
  109317. int htsize; /* Number of buckets in the hash table */
  109318. struct _fts3ht { /* the hash table */
  109319. int count; /* Number of entries with this hash */
  109320. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  109321. } *ht;
  109322. };
  109323. /* Each element in the hash table is an instance of the following
  109324. ** structure. All elements are stored on a single doubly-linked list.
  109325. **
  109326. ** Again, this structure is intended to be opaque, but it can't really
  109327. ** be opaque because it is used by macros.
  109328. */
  109329. struct Fts3HashElem {
  109330. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  109331. void *data; /* Data associated with this element */
  109332. void *pKey; int nKey; /* Key associated with this element */
  109333. };
  109334. /*
  109335. ** There are 2 different modes of operation for a hash table:
  109336. **
  109337. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  109338. ** (including the null-terminator, if any). Case
  109339. ** is respected in comparisons.
  109340. **
  109341. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  109342. ** memcmp() is used to compare keys.
  109343. **
  109344. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  109345. */
  109346. #define FTS3_HASH_STRING 1
  109347. #define FTS3_HASH_BINARY 2
  109348. /*
  109349. ** Access routines. To delete, insert a NULL pointer.
  109350. */
  109351. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  109352. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  109353. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  109354. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  109355. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  109356. /*
  109357. ** Shorthand for the functions above
  109358. */
  109359. #define fts3HashInit sqlite3Fts3HashInit
  109360. #define fts3HashInsert sqlite3Fts3HashInsert
  109361. #define fts3HashFind sqlite3Fts3HashFind
  109362. #define fts3HashClear sqlite3Fts3HashClear
  109363. #define fts3HashFindElem sqlite3Fts3HashFindElem
  109364. /*
  109365. ** Macros for looping over all elements of a hash table. The idiom is
  109366. ** like this:
  109367. **
  109368. ** Fts3Hash h;
  109369. ** Fts3HashElem *p;
  109370. ** ...
  109371. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  109372. ** SomeStructure *pData = fts3HashData(p);
  109373. ** // do something with pData
  109374. ** }
  109375. */
  109376. #define fts3HashFirst(H) ((H)->first)
  109377. #define fts3HashNext(E) ((E)->next)
  109378. #define fts3HashData(E) ((E)->data)
  109379. #define fts3HashKey(E) ((E)->pKey)
  109380. #define fts3HashKeysize(E) ((E)->nKey)
  109381. /*
  109382. ** Number of entries in a hash table
  109383. */
  109384. #define fts3HashCount(H) ((H)->count)
  109385. #endif /* _FTS3_HASH_H_ */
  109386. /************** End of fts3_hash.h *******************************************/
  109387. /************** Continuing where we left off in fts3Int.h ********************/
  109388. /*
  109389. ** This constant controls how often segments are merged. Once there are
  109390. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  109391. ** segment of level N+1.
  109392. */
  109393. #define FTS3_MERGE_COUNT 16
  109394. /*
  109395. ** This is the maximum amount of data (in bytes) to store in the
  109396. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  109397. ** populated as documents are inserted/updated/deleted in a transaction
  109398. ** and used to create a new segment when the transaction is committed.
  109399. ** However if this limit is reached midway through a transaction, a new
  109400. ** segment is created and the hash table cleared immediately.
  109401. */
  109402. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  109403. /*
  109404. ** Macro to return the number of elements in an array. SQLite has a
  109405. ** similar macro called ArraySize(). Use a different name to avoid
  109406. ** a collision when building an amalgamation with built-in FTS3.
  109407. */
  109408. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  109409. #ifndef MIN
  109410. # define MIN(x,y) ((x)<(y)?(x):(y))
  109411. #endif
  109412. #ifndef MAX
  109413. # define MAX(x,y) ((x)>(y)?(x):(y))
  109414. #endif
  109415. /*
  109416. ** Maximum length of a varint encoded integer. The varint format is different
  109417. ** from that used by SQLite, so the maximum length is 10, not 9.
  109418. */
  109419. #define FTS3_VARINT_MAX 10
  109420. /*
  109421. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  109422. ** in the document set and zero or more prefix indexes. All indexes are stored
  109423. ** as one or more b+-trees in the %_segments and %_segdir tables.
  109424. **
  109425. ** It is possible to determine which index a b+-tree belongs to based on the
  109426. ** value stored in the "%_segdir.level" column. Given this value L, the index
  109427. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  109428. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  109429. ** between 1024 and 2047 to index 1, and so on.
  109430. **
  109431. ** It is considered impossible for an index to use more than 1024 levels. In
  109432. ** theory though this may happen, but only after at least
  109433. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  109434. */
  109435. #define FTS3_SEGDIR_MAXLEVEL 1024
  109436. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  109437. /*
  109438. ** The testcase() macro is only used by the amalgamation. If undefined,
  109439. ** make it a no-op.
  109440. */
  109441. #ifndef testcase
  109442. # define testcase(X)
  109443. #endif
  109444. /*
  109445. ** Terminator values for position-lists and column-lists.
  109446. */
  109447. #define POS_COLUMN (1) /* Column-list terminator */
  109448. #define POS_END (0) /* Position-list terminator */
  109449. /*
  109450. ** This section provides definitions to allow the
  109451. ** FTS3 extension to be compiled outside of the
  109452. ** amalgamation.
  109453. */
  109454. #ifndef SQLITE_AMALGAMATION
  109455. /*
  109456. ** Macros indicating that conditional expressions are always true or
  109457. ** false.
  109458. */
  109459. #ifdef SQLITE_COVERAGE_TEST
  109460. # define ALWAYS(x) (1)
  109461. # define NEVER(X) (0)
  109462. #else
  109463. # define ALWAYS(x) (x)
  109464. # define NEVER(x) (x)
  109465. #endif
  109466. /*
  109467. ** Internal types used by SQLite.
  109468. */
  109469. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  109470. typedef short int i16; /* 2-byte (or larger) signed integer */
  109471. typedef unsigned int u32; /* 4-byte unsigned integer */
  109472. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  109473. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  109474. /*
  109475. ** Macro used to suppress compiler warnings for unused parameters.
  109476. */
  109477. #define UNUSED_PARAMETER(x) (void)(x)
  109478. /*
  109479. ** Activate assert() only if SQLITE_TEST is enabled.
  109480. */
  109481. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  109482. # define NDEBUG 1
  109483. #endif
  109484. /*
  109485. ** The TESTONLY macro is used to enclose variable declarations or
  109486. ** other bits of code that are needed to support the arguments
  109487. ** within testcase() and assert() macros.
  109488. */
  109489. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  109490. # define TESTONLY(X) X
  109491. #else
  109492. # define TESTONLY(X)
  109493. #endif
  109494. #endif /* SQLITE_AMALGAMATION */
  109495. #ifdef SQLITE_DEBUG
  109496. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  109497. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  109498. #else
  109499. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  109500. #endif
  109501. typedef struct Fts3Table Fts3Table;
  109502. typedef struct Fts3Cursor Fts3Cursor;
  109503. typedef struct Fts3Expr Fts3Expr;
  109504. typedef struct Fts3Phrase Fts3Phrase;
  109505. typedef struct Fts3PhraseToken Fts3PhraseToken;
  109506. typedef struct Fts3Doclist Fts3Doclist;
  109507. typedef struct Fts3SegFilter Fts3SegFilter;
  109508. typedef struct Fts3DeferredToken Fts3DeferredToken;
  109509. typedef struct Fts3SegReader Fts3SegReader;
  109510. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  109511. /*
  109512. ** A connection to a fulltext index is an instance of the following
  109513. ** structure. The xCreate and xConnect methods create an instance
  109514. ** of this structure and xDestroy and xDisconnect free that instance.
  109515. ** All other methods receive a pointer to the structure as one of their
  109516. ** arguments.
  109517. */
  109518. struct Fts3Table {
  109519. sqlite3_vtab base; /* Base class used by SQLite core */
  109520. sqlite3 *db; /* The database connection */
  109521. const char *zDb; /* logical database name */
  109522. const char *zName; /* virtual table name */
  109523. int nColumn; /* number of named columns in virtual table */
  109524. char **azColumn; /* column names. malloced */
  109525. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  109526. char *zContentTbl; /* content=xxx option, or NULL */
  109527. char *zLanguageid; /* languageid=xxx option, or NULL */
  109528. u8 bAutoincrmerge; /* True if automerge=1 */
  109529. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  109530. /* Precompiled statements used by the implementation. Each of these
  109531. ** statements is run and reset within a single virtual table API call.
  109532. */
  109533. sqlite3_stmt *aStmt[37];
  109534. char *zReadExprlist;
  109535. char *zWriteExprlist;
  109536. int nNodeSize; /* Soft limit for node size */
  109537. u8 bFts4; /* True for FTS4, false for FTS3 */
  109538. u8 bHasStat; /* True if %_stat table exists */
  109539. u8 bHasDocsize; /* True if %_docsize table exists */
  109540. u8 bDescIdx; /* True if doclists are in reverse order */
  109541. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  109542. int nPgsz; /* Page size for host database */
  109543. char *zSegmentsTbl; /* Name of %_segments table */
  109544. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  109545. /*
  109546. ** The following array of hash tables is used to buffer pending index
  109547. ** updates during transactions. All pending updates buffered at any one
  109548. ** time must share a common language-id (see the FTS4 langid= feature).
  109549. ** The current language id is stored in variable iPrevLangid.
  109550. **
  109551. ** A single FTS4 table may have multiple full-text indexes. For each index
  109552. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  109553. ** terms that appear in the document set. Each subsequent index in aIndex[]
  109554. ** is an index of prefixes of a specific length.
  109555. **
  109556. ** Variable nPendingData contains an estimate the memory consumed by the
  109557. ** pending data structures, including hash table overhead, but not including
  109558. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  109559. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  109560. ** recently inserted record.
  109561. */
  109562. int nIndex; /* Size of aIndex[] */
  109563. struct Fts3Index {
  109564. int nPrefix; /* Prefix length (0 for main terms index) */
  109565. Fts3Hash hPending; /* Pending terms table for this index */
  109566. } *aIndex;
  109567. int nMaxPendingData; /* Max pending data before flush to disk */
  109568. int nPendingData; /* Current bytes of pending data */
  109569. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  109570. int iPrevLangid; /* Langid of recently inserted document */
  109571. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  109572. /* State variables used for validating that the transaction control
  109573. ** methods of the virtual table are called at appropriate times. These
  109574. ** values do not contribute to FTS functionality; they are used for
  109575. ** verifying the operation of the SQLite core.
  109576. */
  109577. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  109578. int mxSavepoint; /* Largest valid xSavepoint integer */
  109579. #endif
  109580. };
  109581. /*
  109582. ** When the core wants to read from the virtual table, it creates a
  109583. ** virtual table cursor (an instance of the following structure) using
  109584. ** the xOpen method. Cursors are destroyed using the xClose method.
  109585. */
  109586. struct Fts3Cursor {
  109587. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  109588. i16 eSearch; /* Search strategy (see below) */
  109589. u8 isEof; /* True if at End Of Results */
  109590. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  109591. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  109592. Fts3Expr *pExpr; /* Parsed MATCH query string */
  109593. int iLangid; /* Language being queried for */
  109594. int nPhrase; /* Number of matchable phrases in query */
  109595. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  109596. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  109597. char *pNextId; /* Pointer into the body of aDoclist */
  109598. char *aDoclist; /* List of docids for full-text queries */
  109599. int nDoclist; /* Size of buffer at aDoclist */
  109600. u8 bDesc; /* True to sort in descending order */
  109601. int eEvalmode; /* An FTS3_EVAL_XX constant */
  109602. int nRowAvg; /* Average size of database rows, in pages */
  109603. sqlite3_int64 nDoc; /* Documents in table */
  109604. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  109605. u32 *aMatchinfo; /* Information about most recent match */
  109606. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  109607. char *zMatchinfo; /* Matchinfo specification */
  109608. };
  109609. #define FTS3_EVAL_FILTER 0
  109610. #define FTS3_EVAL_NEXT 1
  109611. #define FTS3_EVAL_MATCHINFO 2
  109612. /*
  109613. ** The Fts3Cursor.eSearch member is always set to one of the following.
  109614. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  109615. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  109616. ** of the column to be searched. For example, in
  109617. **
  109618. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  109619. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  109620. **
  109621. ** Because the LHS of the MATCH operator is 2nd column "b",
  109622. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  109623. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  109624. ** indicating that all columns should be searched,
  109625. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  109626. */
  109627. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  109628. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  109629. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  109630. struct Fts3Doclist {
  109631. char *aAll; /* Array containing doclist (or NULL) */
  109632. int nAll; /* Size of a[] in bytes */
  109633. char *pNextDocid; /* Pointer to next docid */
  109634. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  109635. int bFreeList; /* True if pList should be sqlite3_free()d */
  109636. char *pList; /* Pointer to position list following iDocid */
  109637. int nList; /* Length of position list */
  109638. };
  109639. /*
  109640. ** A "phrase" is a sequence of one or more tokens that must match in
  109641. ** sequence. A single token is the base case and the most common case.
  109642. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  109643. ** nToken will be the number of tokens in the string.
  109644. */
  109645. struct Fts3PhraseToken {
  109646. char *z; /* Text of the token */
  109647. int n; /* Number of bytes in buffer z */
  109648. int isPrefix; /* True if token ends with a "*" character */
  109649. int bFirst; /* True if token must appear at position 0 */
  109650. /* Variables above this point are populated when the expression is
  109651. ** parsed (by code in fts3_expr.c). Below this point the variables are
  109652. ** used when evaluating the expression. */
  109653. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  109654. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  109655. };
  109656. struct Fts3Phrase {
  109657. /* Cache of doclist for this phrase. */
  109658. Fts3Doclist doclist;
  109659. int bIncr; /* True if doclist is loaded incrementally */
  109660. int iDoclistToken;
  109661. /* Variables below this point are populated by fts3_expr.c when parsing
  109662. ** a MATCH expression. Everything above is part of the evaluation phase.
  109663. */
  109664. int nToken; /* Number of tokens in the phrase */
  109665. int iColumn; /* Index of column this phrase must match */
  109666. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  109667. };
  109668. /*
  109669. ** A tree of these objects forms the RHS of a MATCH operator.
  109670. **
  109671. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  109672. ** points to a malloced buffer, size nDoclist bytes, containing the results
  109673. ** of this phrase query in FTS3 doclist format. As usual, the initial
  109674. ** "Length" field found in doclists stored on disk is omitted from this
  109675. ** buffer.
  109676. **
  109677. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  109678. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  109679. ** where nCol is the number of columns in the queried FTS table. The array
  109680. ** is populated as follows:
  109681. **
  109682. ** aMI[iCol*3 + 0] = Undefined
  109683. ** aMI[iCol*3 + 1] = Number of occurrences
  109684. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  109685. **
  109686. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  109687. ** when the expression node is.
  109688. */
  109689. struct Fts3Expr {
  109690. int eType; /* One of the FTSQUERY_XXX values defined below */
  109691. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  109692. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  109693. Fts3Expr *pLeft; /* Left operand */
  109694. Fts3Expr *pRight; /* Right operand */
  109695. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  109696. /* The following are used by the fts3_eval.c module. */
  109697. sqlite3_int64 iDocid; /* Current docid */
  109698. u8 bEof; /* True this expression is at EOF already */
  109699. u8 bStart; /* True if iDocid is valid */
  109700. u8 bDeferred; /* True if this expression is entirely deferred */
  109701. u32 *aMI;
  109702. };
  109703. /*
  109704. ** Candidate values for Fts3Query.eType. Note that the order of the first
  109705. ** four values is in order of precedence when parsing expressions. For
  109706. ** example, the following:
  109707. **
  109708. ** "a OR b AND c NOT d NEAR e"
  109709. **
  109710. ** is equivalent to:
  109711. **
  109712. ** "a OR (b AND (c NOT (d NEAR e)))"
  109713. */
  109714. #define FTSQUERY_NEAR 1
  109715. #define FTSQUERY_NOT 2
  109716. #define FTSQUERY_AND 3
  109717. #define FTSQUERY_OR 4
  109718. #define FTSQUERY_PHRASE 5
  109719. /* fts3_write.c */
  109720. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  109721. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  109722. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  109723. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  109724. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  109725. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  109726. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  109727. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  109728. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  109729. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  109730. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
  109731. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  109732. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  109733. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  109734. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  109735. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  109736. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  109737. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  109738. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  109739. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  109740. #else
  109741. # define sqlite3Fts3FreeDeferredTokens(x)
  109742. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  109743. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  109744. # define sqlite3Fts3FreeDeferredDoclists(x)
  109745. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  109746. #endif
  109747. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  109748. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  109749. /* Special values interpreted by sqlite3SegReaderCursor() */
  109750. #define FTS3_SEGCURSOR_PENDING -1
  109751. #define FTS3_SEGCURSOR_ALL -2
  109752. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  109753. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  109754. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  109755. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  109756. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  109757. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  109758. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  109759. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  109760. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  109761. #define FTS3_SEGMENT_PREFIX 0x00000008
  109762. #define FTS3_SEGMENT_SCAN 0x00000010
  109763. #define FTS3_SEGMENT_FIRST 0x00000020
  109764. /* Type passed as 4th argument to SegmentReaderIterate() */
  109765. struct Fts3SegFilter {
  109766. const char *zTerm;
  109767. int nTerm;
  109768. int iCol;
  109769. int flags;
  109770. };
  109771. struct Fts3MultiSegReader {
  109772. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  109773. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  109774. int nSegment; /* Size of apSegment array */
  109775. int nAdvance; /* How many seg-readers to advance */
  109776. Fts3SegFilter *pFilter; /* Pointer to filter object */
  109777. char *aBuffer; /* Buffer to merge doclists in */
  109778. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  109779. int iColFilter; /* If >=0, filter for this column */
  109780. int bRestart;
  109781. /* Used by fts3.c only. */
  109782. int nCost; /* Cost of running iterator */
  109783. int bLookup; /* True if a lookup of a single entry. */
  109784. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  109785. char *zTerm; /* Pointer to term buffer */
  109786. int nTerm; /* Size of zTerm in bytes */
  109787. char *aDoclist; /* Pointer to doclist buffer */
  109788. int nDoclist; /* Size of aDoclist[] in bytes */
  109789. };
  109790. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  109791. /* fts3.c */
  109792. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  109793. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  109794. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  109795. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  109796. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  109797. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  109798. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  109799. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  109800. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  109801. /* fts3_tokenizer.c */
  109802. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  109803. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  109804. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  109805. sqlite3_tokenizer **, char **
  109806. );
  109807. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  109808. /* fts3_snippet.c */
  109809. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  109810. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  109811. const char *, const char *, int, int
  109812. );
  109813. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  109814. /* fts3_expr.c */
  109815. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  109816. char **, int, int, int, const char *, int, Fts3Expr **
  109817. );
  109818. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  109819. #ifdef SQLITE_TEST
  109820. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  109821. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  109822. #endif
  109823. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  109824. sqlite3_tokenizer_cursor **
  109825. );
  109826. /* fts3_aux.c */
  109827. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  109828. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  109829. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  109830. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  109831. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  109832. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  109833. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  109834. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  109835. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  109836. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  109837. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  109838. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  109839. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  109840. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  109841. #endif
  109842. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  109843. #endif /* _FTSINT_H */
  109844. /************** End of fts3Int.h *********************************************/
  109845. /************** Continuing where we left off in fts3.c ***********************/
  109846. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109847. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  109848. # define SQLITE_CORE 1
  109849. #endif
  109850. /* #include <assert.h> */
  109851. /* #include <stdlib.h> */
  109852. /* #include <stddef.h> */
  109853. /* #include <stdio.h> */
  109854. /* #include <string.h> */
  109855. /* #include <stdarg.h> */
  109856. #ifndef SQLITE_CORE
  109857. SQLITE_EXTENSION_INIT1
  109858. #endif
  109859. static int fts3EvalNext(Fts3Cursor *pCsr);
  109860. static int fts3EvalStart(Fts3Cursor *pCsr);
  109861. static int fts3TermSegReaderCursor(
  109862. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  109863. /*
  109864. ** Write a 64-bit variable-length integer to memory starting at p[0].
  109865. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  109866. ** The number of bytes written is returned.
  109867. */
  109868. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  109869. unsigned char *q = (unsigned char *) p;
  109870. sqlite_uint64 vu = v;
  109871. do{
  109872. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  109873. vu >>= 7;
  109874. }while( vu!=0 );
  109875. q[-1] &= 0x7f; /* turn off high bit in final byte */
  109876. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  109877. return (int) (q - (unsigned char *)p);
  109878. }
  109879. /*
  109880. ** Read a 64-bit variable-length integer from memory starting at p[0].
  109881. ** Return the number of bytes read, or 0 on error.
  109882. ** The value is stored in *v.
  109883. */
  109884. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  109885. const unsigned char *q = (const unsigned char *) p;
  109886. sqlite_uint64 x = 0, y = 1;
  109887. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  109888. x += y * (*q++ & 0x7f);
  109889. y <<= 7;
  109890. }
  109891. x += y * (*q++);
  109892. *v = (sqlite_int64) x;
  109893. return (int) (q - (unsigned char *)p);
  109894. }
  109895. /*
  109896. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  109897. ** 32-bit integer before it is returned.
  109898. */
  109899. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  109900. sqlite_int64 i;
  109901. int ret = sqlite3Fts3GetVarint(p, &i);
  109902. *pi = (int) i;
  109903. return ret;
  109904. }
  109905. /*
  109906. ** Return the number of bytes required to encode v as a varint
  109907. */
  109908. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  109909. int i = 0;
  109910. do{
  109911. i++;
  109912. v >>= 7;
  109913. }while( v!=0 );
  109914. return i;
  109915. }
  109916. /*
  109917. ** Convert an SQL-style quoted string into a normal string by removing
  109918. ** the quote characters. The conversion is done in-place. If the
  109919. ** input does not begin with a quote character, then this routine
  109920. ** is a no-op.
  109921. **
  109922. ** Examples:
  109923. **
  109924. ** "abc" becomes abc
  109925. ** 'xyz' becomes xyz
  109926. ** [pqr] becomes pqr
  109927. ** `mno` becomes mno
  109928. **
  109929. */
  109930. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  109931. char quote; /* Quote character (if any ) */
  109932. quote = z[0];
  109933. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  109934. int iIn = 1; /* Index of next byte to read from input */
  109935. int iOut = 0; /* Index of next byte to write to output */
  109936. /* If the first byte was a '[', then the close-quote character is a ']' */
  109937. if( quote=='[' ) quote = ']';
  109938. while( ALWAYS(z[iIn]) ){
  109939. if( z[iIn]==quote ){
  109940. if( z[iIn+1]!=quote ) break;
  109941. z[iOut++] = quote;
  109942. iIn += 2;
  109943. }else{
  109944. z[iOut++] = z[iIn++];
  109945. }
  109946. }
  109947. z[iOut] = '\0';
  109948. }
  109949. }
  109950. /*
  109951. ** Read a single varint from the doclist at *pp and advance *pp to point
  109952. ** to the first byte past the end of the varint. Add the value of the varint
  109953. ** to *pVal.
  109954. */
  109955. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  109956. sqlite3_int64 iVal;
  109957. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  109958. *pVal += iVal;
  109959. }
  109960. /*
  109961. ** When this function is called, *pp points to the first byte following a
  109962. ** varint that is part of a doclist (or position-list, or any other list
  109963. ** of varints). This function moves *pp to point to the start of that varint,
  109964. ** and sets *pVal by the varint value.
  109965. **
  109966. ** Argument pStart points to the first byte of the doclist that the
  109967. ** varint is part of.
  109968. */
  109969. static void fts3GetReverseVarint(
  109970. char **pp,
  109971. char *pStart,
  109972. sqlite3_int64 *pVal
  109973. ){
  109974. sqlite3_int64 iVal;
  109975. char *p;
  109976. /* Pointer p now points at the first byte past the varint we are
  109977. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  109978. ** clear on character p[-1]. */
  109979. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  109980. p++;
  109981. *pp = p;
  109982. sqlite3Fts3GetVarint(p, &iVal);
  109983. *pVal = iVal;
  109984. }
  109985. /*
  109986. ** The xDisconnect() virtual table method.
  109987. */
  109988. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  109989. Fts3Table *p = (Fts3Table *)pVtab;
  109990. int i;
  109991. assert( p->nPendingData==0 );
  109992. assert( p->pSegments==0 );
  109993. /* Free any prepared statements held */
  109994. for(i=0; i<SizeofArray(p->aStmt); i++){
  109995. sqlite3_finalize(p->aStmt[i]);
  109996. }
  109997. sqlite3_free(p->zSegmentsTbl);
  109998. sqlite3_free(p->zReadExprlist);
  109999. sqlite3_free(p->zWriteExprlist);
  110000. sqlite3_free(p->zContentTbl);
  110001. sqlite3_free(p->zLanguageid);
  110002. /* Invoke the tokenizer destructor to free the tokenizer. */
  110003. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  110004. sqlite3_free(p);
  110005. return SQLITE_OK;
  110006. }
  110007. /*
  110008. ** Construct one or more SQL statements from the format string given
  110009. ** and then evaluate those statements. The success code is written
  110010. ** into *pRc.
  110011. **
  110012. ** If *pRc is initially non-zero then this routine is a no-op.
  110013. */
  110014. static void fts3DbExec(
  110015. int *pRc, /* Success code */
  110016. sqlite3 *db, /* Database in which to run SQL */
  110017. const char *zFormat, /* Format string for SQL */
  110018. ... /* Arguments to the format string */
  110019. ){
  110020. va_list ap;
  110021. char *zSql;
  110022. if( *pRc ) return;
  110023. va_start(ap, zFormat);
  110024. zSql = sqlite3_vmprintf(zFormat, ap);
  110025. va_end(ap);
  110026. if( zSql==0 ){
  110027. *pRc = SQLITE_NOMEM;
  110028. }else{
  110029. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  110030. sqlite3_free(zSql);
  110031. }
  110032. }
  110033. /*
  110034. ** The xDestroy() virtual table method.
  110035. */
  110036. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  110037. Fts3Table *p = (Fts3Table *)pVtab;
  110038. int rc = SQLITE_OK; /* Return code */
  110039. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  110040. sqlite3 *db = p->db; /* Database handle */
  110041. /* Drop the shadow tables */
  110042. if( p->zContentTbl==0 ){
  110043. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  110044. }
  110045. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  110046. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  110047. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  110048. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  110049. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  110050. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  110051. ** Otherwise, return an SQLite error code.
  110052. */
  110053. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  110054. }
  110055. /*
  110056. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  110057. ** passed as the first argument. This is done as part of the xConnect()
  110058. ** and xCreate() methods.
  110059. **
  110060. ** If *pRc is non-zero when this function is called, it is a no-op.
  110061. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  110062. ** before returning.
  110063. */
  110064. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  110065. if( *pRc==SQLITE_OK ){
  110066. int i; /* Iterator variable */
  110067. int rc; /* Return code */
  110068. char *zSql; /* SQL statement passed to declare_vtab() */
  110069. char *zCols; /* List of user defined columns */
  110070. const char *zLanguageid;
  110071. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  110072. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  110073. /* Create a list of user columns for the virtual table */
  110074. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  110075. for(i=1; zCols && i<p->nColumn; i++){
  110076. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  110077. }
  110078. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  110079. zSql = sqlite3_mprintf(
  110080. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  110081. zCols, p->zName, zLanguageid
  110082. );
  110083. if( !zCols || !zSql ){
  110084. rc = SQLITE_NOMEM;
  110085. }else{
  110086. rc = sqlite3_declare_vtab(p->db, zSql);
  110087. }
  110088. sqlite3_free(zSql);
  110089. sqlite3_free(zCols);
  110090. *pRc = rc;
  110091. }
  110092. }
  110093. /*
  110094. ** Create the %_stat table if it does not already exist.
  110095. */
  110096. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  110097. fts3DbExec(pRc, p->db,
  110098. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  110099. "(id INTEGER PRIMARY KEY, value BLOB);",
  110100. p->zDb, p->zName
  110101. );
  110102. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  110103. }
  110104. /*
  110105. ** Create the backing store tables (%_content, %_segments and %_segdir)
  110106. ** required by the FTS3 table passed as the only argument. This is done
  110107. ** as part of the vtab xCreate() method.
  110108. **
  110109. ** If the p->bHasDocsize boolean is true (indicating that this is an
  110110. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  110111. ** %_stat tables required by FTS4.
  110112. */
  110113. static int fts3CreateTables(Fts3Table *p){
  110114. int rc = SQLITE_OK; /* Return code */
  110115. int i; /* Iterator variable */
  110116. sqlite3 *db = p->db; /* The database connection */
  110117. if( p->zContentTbl==0 ){
  110118. const char *zLanguageid = p->zLanguageid;
  110119. char *zContentCols; /* Columns of %_content table */
  110120. /* Create a list of user columns for the content table */
  110121. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  110122. for(i=0; zContentCols && i<p->nColumn; i++){
  110123. char *z = p->azColumn[i];
  110124. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  110125. }
  110126. if( zLanguageid && zContentCols ){
  110127. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  110128. }
  110129. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  110130. /* Create the content table */
  110131. fts3DbExec(&rc, db,
  110132. "CREATE TABLE %Q.'%q_content'(%s)",
  110133. p->zDb, p->zName, zContentCols
  110134. );
  110135. sqlite3_free(zContentCols);
  110136. }
  110137. /* Create other tables */
  110138. fts3DbExec(&rc, db,
  110139. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  110140. p->zDb, p->zName
  110141. );
  110142. fts3DbExec(&rc, db,
  110143. "CREATE TABLE %Q.'%q_segdir'("
  110144. "level INTEGER,"
  110145. "idx INTEGER,"
  110146. "start_block INTEGER,"
  110147. "leaves_end_block INTEGER,"
  110148. "end_block INTEGER,"
  110149. "root BLOB,"
  110150. "PRIMARY KEY(level, idx)"
  110151. ");",
  110152. p->zDb, p->zName
  110153. );
  110154. if( p->bHasDocsize ){
  110155. fts3DbExec(&rc, db,
  110156. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  110157. p->zDb, p->zName
  110158. );
  110159. }
  110160. assert( p->bHasStat==p->bFts4 );
  110161. if( p->bHasStat ){
  110162. sqlite3Fts3CreateStatTable(&rc, p);
  110163. }
  110164. return rc;
  110165. }
  110166. /*
  110167. ** Store the current database page-size in bytes in p->nPgsz.
  110168. **
  110169. ** If *pRc is non-zero when this function is called, it is a no-op.
  110170. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  110171. ** before returning.
  110172. */
  110173. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  110174. if( *pRc==SQLITE_OK ){
  110175. int rc; /* Return code */
  110176. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  110177. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  110178. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  110179. if( !zSql ){
  110180. rc = SQLITE_NOMEM;
  110181. }else{
  110182. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  110183. if( rc==SQLITE_OK ){
  110184. sqlite3_step(pStmt);
  110185. p->nPgsz = sqlite3_column_int(pStmt, 0);
  110186. rc = sqlite3_finalize(pStmt);
  110187. }else if( rc==SQLITE_AUTH ){
  110188. p->nPgsz = 1024;
  110189. rc = SQLITE_OK;
  110190. }
  110191. }
  110192. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  110193. sqlite3_free(zSql);
  110194. *pRc = rc;
  110195. }
  110196. }
  110197. /*
  110198. ** "Special" FTS4 arguments are column specifications of the following form:
  110199. **
  110200. ** <key> = <value>
  110201. **
  110202. ** There may not be whitespace surrounding the "=" character. The <value>
  110203. ** term may be quoted, but the <key> may not.
  110204. */
  110205. static int fts3IsSpecialColumn(
  110206. const char *z,
  110207. int *pnKey,
  110208. char **pzValue
  110209. ){
  110210. char *zValue;
  110211. const char *zCsr = z;
  110212. while( *zCsr!='=' ){
  110213. if( *zCsr=='\0' ) return 0;
  110214. zCsr++;
  110215. }
  110216. *pnKey = (int)(zCsr-z);
  110217. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  110218. if( zValue ){
  110219. sqlite3Fts3Dequote(zValue);
  110220. }
  110221. *pzValue = zValue;
  110222. return 1;
  110223. }
  110224. /*
  110225. ** Append the output of a printf() style formatting to an existing string.
  110226. */
  110227. static void fts3Appendf(
  110228. int *pRc, /* IN/OUT: Error code */
  110229. char **pz, /* IN/OUT: Pointer to string buffer */
  110230. const char *zFormat, /* Printf format string to append */
  110231. ... /* Arguments for printf format string */
  110232. ){
  110233. if( *pRc==SQLITE_OK ){
  110234. va_list ap;
  110235. char *z;
  110236. va_start(ap, zFormat);
  110237. z = sqlite3_vmprintf(zFormat, ap);
  110238. va_end(ap);
  110239. if( z && *pz ){
  110240. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  110241. sqlite3_free(z);
  110242. z = z2;
  110243. }
  110244. if( z==0 ) *pRc = SQLITE_NOMEM;
  110245. sqlite3_free(*pz);
  110246. *pz = z;
  110247. }
  110248. }
  110249. /*
  110250. ** Return a copy of input string zInput enclosed in double-quotes (") and
  110251. ** with all double quote characters escaped. For example:
  110252. **
  110253. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  110254. **
  110255. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  110256. ** is the callers responsibility to call sqlite3_free() to release this
  110257. ** memory.
  110258. */
  110259. static char *fts3QuoteId(char const *zInput){
  110260. int nRet;
  110261. char *zRet;
  110262. nRet = 2 + (int)strlen(zInput)*2 + 1;
  110263. zRet = sqlite3_malloc(nRet);
  110264. if( zRet ){
  110265. int i;
  110266. char *z = zRet;
  110267. *(z++) = '"';
  110268. for(i=0; zInput[i]; i++){
  110269. if( zInput[i]=='"' ) *(z++) = '"';
  110270. *(z++) = zInput[i];
  110271. }
  110272. *(z++) = '"';
  110273. *(z++) = '\0';
  110274. }
  110275. return zRet;
  110276. }
  110277. /*
  110278. ** Return a list of comma separated SQL expressions and a FROM clause that
  110279. ** could be used in a SELECT statement such as the following:
  110280. **
  110281. ** SELECT <list of expressions> FROM %_content AS x ...
  110282. **
  110283. ** to return the docid, followed by each column of text data in order
  110284. ** from left to write. If parameter zFunc is not NULL, then instead of
  110285. ** being returned directly each column of text data is passed to an SQL
  110286. ** function named zFunc first. For example, if zFunc is "unzip" and the
  110287. ** table has the three user-defined columns "a", "b", and "c", the following
  110288. ** string is returned:
  110289. **
  110290. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  110291. **
  110292. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  110293. ** is the responsibility of the caller to eventually free it.
  110294. **
  110295. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  110296. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  110297. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  110298. ** no error occurs, *pRc is left unmodified.
  110299. */
  110300. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  110301. char *zRet = 0;
  110302. char *zFree = 0;
  110303. char *zFunction;
  110304. int i;
  110305. if( p->zContentTbl==0 ){
  110306. if( !zFunc ){
  110307. zFunction = "";
  110308. }else{
  110309. zFree = zFunction = fts3QuoteId(zFunc);
  110310. }
  110311. fts3Appendf(pRc, &zRet, "docid");
  110312. for(i=0; i<p->nColumn; i++){
  110313. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  110314. }
  110315. if( p->zLanguageid ){
  110316. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  110317. }
  110318. sqlite3_free(zFree);
  110319. }else{
  110320. fts3Appendf(pRc, &zRet, "rowid");
  110321. for(i=0; i<p->nColumn; i++){
  110322. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  110323. }
  110324. if( p->zLanguageid ){
  110325. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  110326. }
  110327. }
  110328. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  110329. p->zDb,
  110330. (p->zContentTbl ? p->zContentTbl : p->zName),
  110331. (p->zContentTbl ? "" : "_content")
  110332. );
  110333. return zRet;
  110334. }
  110335. /*
  110336. ** Return a list of N comma separated question marks, where N is the number
  110337. ** of columns in the %_content table (one for the docid plus one for each
  110338. ** user-defined text column).
  110339. **
  110340. ** If argument zFunc is not NULL, then all but the first question mark
  110341. ** is preceded by zFunc and an open bracket, and followed by a closed
  110342. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  110343. ** user-defined text columns, the following string is returned:
  110344. **
  110345. ** "?, zip(?), zip(?), zip(?)"
  110346. **
  110347. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  110348. ** is the responsibility of the caller to eventually free it.
  110349. **
  110350. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  110351. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  110352. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  110353. ** no error occurs, *pRc is left unmodified.
  110354. */
  110355. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  110356. char *zRet = 0;
  110357. char *zFree = 0;
  110358. char *zFunction;
  110359. int i;
  110360. if( !zFunc ){
  110361. zFunction = "";
  110362. }else{
  110363. zFree = zFunction = fts3QuoteId(zFunc);
  110364. }
  110365. fts3Appendf(pRc, &zRet, "?");
  110366. for(i=0; i<p->nColumn; i++){
  110367. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  110368. }
  110369. if( p->zLanguageid ){
  110370. fts3Appendf(pRc, &zRet, ", ?");
  110371. }
  110372. sqlite3_free(zFree);
  110373. return zRet;
  110374. }
  110375. /*
  110376. ** This function interprets the string at (*pp) as a non-negative integer
  110377. ** value. It reads the integer and sets *pnOut to the value read, then
  110378. ** sets *pp to point to the byte immediately following the last byte of
  110379. ** the integer value.
  110380. **
  110381. ** Only decimal digits ('0'..'9') may be part of an integer value.
  110382. **
  110383. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  110384. ** the output value undefined. Otherwise SQLITE_OK is returned.
  110385. **
  110386. ** This function is used when parsing the "prefix=" FTS4 parameter.
  110387. */
  110388. static int fts3GobbleInt(const char **pp, int *pnOut){
  110389. const char *p; /* Iterator pointer */
  110390. int nInt = 0; /* Output value */
  110391. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  110392. nInt = nInt * 10 + (p[0] - '0');
  110393. }
  110394. if( p==*pp ) return SQLITE_ERROR;
  110395. *pnOut = nInt;
  110396. *pp = p;
  110397. return SQLITE_OK;
  110398. }
  110399. /*
  110400. ** This function is called to allocate an array of Fts3Index structures
  110401. ** representing the indexes maintained by the current FTS table. FTS tables
  110402. ** always maintain the main "terms" index, but may also maintain one or
  110403. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  110404. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  110405. **
  110406. ** Argument zParam is passed the value of the "prefix=" option if one was
  110407. ** specified, or NULL otherwise.
  110408. **
  110409. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  110410. ** the allocated array. *pnIndex is set to the number of elements in the
  110411. ** array. If an error does occur, an SQLite error code is returned.
  110412. **
  110413. ** Regardless of whether or not an error is returned, it is the responsibility
  110414. ** of the caller to call sqlite3_free() on the output array to free it.
  110415. */
  110416. static int fts3PrefixParameter(
  110417. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  110418. int *pnIndex, /* OUT: size of *apIndex[] array */
  110419. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  110420. ){
  110421. struct Fts3Index *aIndex; /* Allocated array */
  110422. int nIndex = 1; /* Number of entries in array */
  110423. if( zParam && zParam[0] ){
  110424. const char *p;
  110425. nIndex++;
  110426. for(p=zParam; *p; p++){
  110427. if( *p==',' ) nIndex++;
  110428. }
  110429. }
  110430. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  110431. *apIndex = aIndex;
  110432. *pnIndex = nIndex;
  110433. if( !aIndex ){
  110434. return SQLITE_NOMEM;
  110435. }
  110436. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  110437. if( zParam ){
  110438. const char *p = zParam;
  110439. int i;
  110440. for(i=1; i<nIndex; i++){
  110441. int nPrefix;
  110442. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  110443. aIndex[i].nPrefix = nPrefix;
  110444. p++;
  110445. }
  110446. }
  110447. return SQLITE_OK;
  110448. }
  110449. /*
  110450. ** This function is called when initializing an FTS4 table that uses the
  110451. ** content=xxx option. It determines the number of and names of the columns
  110452. ** of the new FTS4 table.
  110453. **
  110454. ** The third argument passed to this function is the value passed to the
  110455. ** config=xxx option (i.e. "xxx"). This function queries the database for
  110456. ** a table of that name. If found, the output variables are populated
  110457. ** as follows:
  110458. **
  110459. ** *pnCol: Set to the number of columns table xxx has,
  110460. **
  110461. ** *pnStr: Set to the total amount of space required to store a copy
  110462. ** of each columns name, including the nul-terminator.
  110463. **
  110464. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  110465. ** the name of the corresponding column in table xxx. The array
  110466. ** and its contents are allocated using a single allocation. It
  110467. ** is the responsibility of the caller to free this allocation
  110468. ** by eventually passing the *pazCol value to sqlite3_free().
  110469. **
  110470. ** If the table cannot be found, an error code is returned and the output
  110471. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  110472. ** returned (and the output variables are undefined).
  110473. */
  110474. static int fts3ContentColumns(
  110475. sqlite3 *db, /* Database handle */
  110476. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  110477. const char *zTbl, /* Name of content table */
  110478. const char ***pazCol, /* OUT: Malloc'd array of column names */
  110479. int *pnCol, /* OUT: Size of array *pazCol */
  110480. int *pnStr /* OUT: Bytes of string content */
  110481. ){
  110482. int rc = SQLITE_OK; /* Return code */
  110483. char *zSql; /* "SELECT *" statement on zTbl */
  110484. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  110485. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  110486. if( !zSql ){
  110487. rc = SQLITE_NOMEM;
  110488. }else{
  110489. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  110490. }
  110491. sqlite3_free(zSql);
  110492. if( rc==SQLITE_OK ){
  110493. const char **azCol; /* Output array */
  110494. int nStr = 0; /* Size of all column names (incl. 0x00) */
  110495. int nCol; /* Number of table columns */
  110496. int i; /* Used to iterate through columns */
  110497. /* Loop through the returned columns. Set nStr to the number of bytes of
  110498. ** space required to store a copy of each column name, including the
  110499. ** nul-terminator byte. */
  110500. nCol = sqlite3_column_count(pStmt);
  110501. for(i=0; i<nCol; i++){
  110502. const char *zCol = sqlite3_column_name(pStmt, i);
  110503. nStr += (int)strlen(zCol) + 1;
  110504. }
  110505. /* Allocate and populate the array to return. */
  110506. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  110507. if( azCol==0 ){
  110508. rc = SQLITE_NOMEM;
  110509. }else{
  110510. char *p = (char *)&azCol[nCol];
  110511. for(i=0; i<nCol; i++){
  110512. const char *zCol = sqlite3_column_name(pStmt, i);
  110513. int n = (int)strlen(zCol)+1;
  110514. memcpy(p, zCol, n);
  110515. azCol[i] = p;
  110516. p += n;
  110517. }
  110518. }
  110519. sqlite3_finalize(pStmt);
  110520. /* Set the output variables. */
  110521. *pnCol = nCol;
  110522. *pnStr = nStr;
  110523. *pazCol = azCol;
  110524. }
  110525. return rc;
  110526. }
  110527. /*
  110528. ** This function is the implementation of both the xConnect and xCreate
  110529. ** methods of the FTS3 virtual table.
  110530. **
  110531. ** The argv[] array contains the following:
  110532. **
  110533. ** argv[0] -> module name ("fts3" or "fts4")
  110534. ** argv[1] -> database name
  110535. ** argv[2] -> table name
  110536. ** argv[...] -> "column name" and other module argument fields.
  110537. */
  110538. static int fts3InitVtab(
  110539. int isCreate, /* True for xCreate, false for xConnect */
  110540. sqlite3 *db, /* The SQLite database connection */
  110541. void *pAux, /* Hash table containing tokenizers */
  110542. int argc, /* Number of elements in argv array */
  110543. const char * const *argv, /* xCreate/xConnect argument array */
  110544. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  110545. char **pzErr /* Write any error message here */
  110546. ){
  110547. Fts3Hash *pHash = (Fts3Hash *)pAux;
  110548. Fts3Table *p = 0; /* Pointer to allocated vtab */
  110549. int rc = SQLITE_OK; /* Return code */
  110550. int i; /* Iterator variable */
  110551. int nByte; /* Size of allocation used for *p */
  110552. int iCol; /* Column index */
  110553. int nString = 0; /* Bytes required to hold all column names */
  110554. int nCol = 0; /* Number of columns in the FTS table */
  110555. char *zCsr; /* Space for holding column names */
  110556. int nDb; /* Bytes required to hold database name */
  110557. int nName; /* Bytes required to hold table name */
  110558. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  110559. const char **aCol; /* Array of column names */
  110560. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  110561. int nIndex; /* Size of aIndex[] array */
  110562. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  110563. /* The results of parsing supported FTS4 key=value options: */
  110564. int bNoDocsize = 0; /* True to omit %_docsize table */
  110565. int bDescIdx = 0; /* True to store descending indexes */
  110566. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  110567. char *zCompress = 0; /* compress=? parameter (or NULL) */
  110568. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  110569. char *zContent = 0; /* content=? parameter (or NULL) */
  110570. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  110571. assert( strlen(argv[0])==4 );
  110572. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  110573. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  110574. );
  110575. nDb = (int)strlen(argv[1]) + 1;
  110576. nName = (int)strlen(argv[2]) + 1;
  110577. aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
  110578. if( !aCol ) return SQLITE_NOMEM;
  110579. memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
  110580. /* Loop through all of the arguments passed by the user to the FTS3/4
  110581. ** module (i.e. all the column names and special arguments). This loop
  110582. ** does the following:
  110583. **
  110584. ** + Figures out the number of columns the FTSX table will have, and
  110585. ** the number of bytes of space that must be allocated to store copies
  110586. ** of the column names.
  110587. **
  110588. ** + If there is a tokenizer specification included in the arguments,
  110589. ** initializes the tokenizer pTokenizer.
  110590. */
  110591. for(i=3; rc==SQLITE_OK && i<argc; i++){
  110592. char const *z = argv[i];
  110593. int nKey;
  110594. char *zVal;
  110595. /* Check if this is a tokenizer specification */
  110596. if( !pTokenizer
  110597. && strlen(z)>8
  110598. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  110599. && 0==sqlite3Fts3IsIdChar(z[8])
  110600. ){
  110601. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  110602. }
  110603. /* Check if it is an FTS4 special argument. */
  110604. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  110605. struct Fts4Option {
  110606. const char *zOpt;
  110607. int nOpt;
  110608. } aFts4Opt[] = {
  110609. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  110610. { "prefix", 6 }, /* 1 -> PREFIX */
  110611. { "compress", 8 }, /* 2 -> COMPRESS */
  110612. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  110613. { "order", 5 }, /* 4 -> ORDER */
  110614. { "content", 7 }, /* 5 -> CONTENT */
  110615. { "languageid", 10 } /* 6 -> LANGUAGEID */
  110616. };
  110617. int iOpt;
  110618. if( !zVal ){
  110619. rc = SQLITE_NOMEM;
  110620. }else{
  110621. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  110622. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  110623. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  110624. break;
  110625. }
  110626. }
  110627. if( iOpt==SizeofArray(aFts4Opt) ){
  110628. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  110629. rc = SQLITE_ERROR;
  110630. }else{
  110631. switch( iOpt ){
  110632. case 0: /* MATCHINFO */
  110633. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  110634. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  110635. rc = SQLITE_ERROR;
  110636. }
  110637. bNoDocsize = 1;
  110638. break;
  110639. case 1: /* PREFIX */
  110640. sqlite3_free(zPrefix);
  110641. zPrefix = zVal;
  110642. zVal = 0;
  110643. break;
  110644. case 2: /* COMPRESS */
  110645. sqlite3_free(zCompress);
  110646. zCompress = zVal;
  110647. zVal = 0;
  110648. break;
  110649. case 3: /* UNCOMPRESS */
  110650. sqlite3_free(zUncompress);
  110651. zUncompress = zVal;
  110652. zVal = 0;
  110653. break;
  110654. case 4: /* ORDER */
  110655. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  110656. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  110657. ){
  110658. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  110659. rc = SQLITE_ERROR;
  110660. }
  110661. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  110662. break;
  110663. case 5: /* CONTENT */
  110664. sqlite3_free(zContent);
  110665. zContent = zVal;
  110666. zVal = 0;
  110667. break;
  110668. case 6: /* LANGUAGEID */
  110669. assert( iOpt==6 );
  110670. sqlite3_free(zLanguageid);
  110671. zLanguageid = zVal;
  110672. zVal = 0;
  110673. break;
  110674. }
  110675. }
  110676. sqlite3_free(zVal);
  110677. }
  110678. }
  110679. /* Otherwise, the argument is a column name. */
  110680. else {
  110681. nString += (int)(strlen(z) + 1);
  110682. aCol[nCol++] = z;
  110683. }
  110684. }
  110685. /* If a content=xxx option was specified, the following:
  110686. **
  110687. ** 1. Ignore any compress= and uncompress= options.
  110688. **
  110689. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  110690. ** TABLE statement, use all columns from the content table.
  110691. */
  110692. if( rc==SQLITE_OK && zContent ){
  110693. sqlite3_free(zCompress);
  110694. sqlite3_free(zUncompress);
  110695. zCompress = 0;
  110696. zUncompress = 0;
  110697. if( nCol==0 ){
  110698. sqlite3_free((void*)aCol);
  110699. aCol = 0;
  110700. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  110701. /* If a languageid= option was specified, remove the language id
  110702. ** column from the aCol[] array. */
  110703. if( rc==SQLITE_OK && zLanguageid ){
  110704. int j;
  110705. for(j=0; j<nCol; j++){
  110706. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  110707. int k;
  110708. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  110709. nCol--;
  110710. break;
  110711. }
  110712. }
  110713. }
  110714. }
  110715. }
  110716. if( rc!=SQLITE_OK ) goto fts3_init_out;
  110717. if( nCol==0 ){
  110718. assert( nString==0 );
  110719. aCol[0] = "content";
  110720. nString = 8;
  110721. nCol = 1;
  110722. }
  110723. if( pTokenizer==0 ){
  110724. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  110725. if( rc!=SQLITE_OK ) goto fts3_init_out;
  110726. }
  110727. assert( pTokenizer );
  110728. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  110729. if( rc==SQLITE_ERROR ){
  110730. assert( zPrefix );
  110731. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  110732. }
  110733. if( rc!=SQLITE_OK ) goto fts3_init_out;
  110734. /* Allocate and populate the Fts3Table structure. */
  110735. nByte = sizeof(Fts3Table) + /* Fts3Table */
  110736. nCol * sizeof(char *) + /* azColumn */
  110737. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  110738. nName + /* zName */
  110739. nDb + /* zDb */
  110740. nString; /* Space for azColumn strings */
  110741. p = (Fts3Table*)sqlite3_malloc(nByte);
  110742. if( p==0 ){
  110743. rc = SQLITE_NOMEM;
  110744. goto fts3_init_out;
  110745. }
  110746. memset(p, 0, nByte);
  110747. p->db = db;
  110748. p->nColumn = nCol;
  110749. p->nPendingData = 0;
  110750. p->azColumn = (char **)&p[1];
  110751. p->pTokenizer = pTokenizer;
  110752. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  110753. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  110754. p->bHasStat = isFts4;
  110755. p->bFts4 = isFts4;
  110756. p->bDescIdx = bDescIdx;
  110757. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  110758. p->zContentTbl = zContent;
  110759. p->zLanguageid = zLanguageid;
  110760. zContent = 0;
  110761. zLanguageid = 0;
  110762. TESTONLY( p->inTransaction = -1 );
  110763. TESTONLY( p->mxSavepoint = -1 );
  110764. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  110765. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  110766. p->nIndex = nIndex;
  110767. for(i=0; i<nIndex; i++){
  110768. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  110769. }
  110770. /* Fill in the zName and zDb fields of the vtab structure. */
  110771. zCsr = (char *)&p->aIndex[nIndex];
  110772. p->zName = zCsr;
  110773. memcpy(zCsr, argv[2], nName);
  110774. zCsr += nName;
  110775. p->zDb = zCsr;
  110776. memcpy(zCsr, argv[1], nDb);
  110777. zCsr += nDb;
  110778. /* Fill in the azColumn array */
  110779. for(iCol=0; iCol<nCol; iCol++){
  110780. char *z;
  110781. int n = 0;
  110782. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  110783. memcpy(zCsr, z, n);
  110784. zCsr[n] = '\0';
  110785. sqlite3Fts3Dequote(zCsr);
  110786. p->azColumn[iCol] = zCsr;
  110787. zCsr += n+1;
  110788. assert( zCsr <= &((char *)p)[nByte] );
  110789. }
  110790. if( (zCompress==0)!=(zUncompress==0) ){
  110791. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  110792. rc = SQLITE_ERROR;
  110793. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  110794. }
  110795. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  110796. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  110797. if( rc!=SQLITE_OK ) goto fts3_init_out;
  110798. /* If this is an xCreate call, create the underlying tables in the
  110799. ** database. TODO: For xConnect(), it could verify that said tables exist.
  110800. */
  110801. if( isCreate ){
  110802. rc = fts3CreateTables(p);
  110803. }
  110804. /* Check to see if a legacy fts3 table has been "upgraded" by the
  110805. ** addition of a %_stat table so that it can use incremental merge.
  110806. */
  110807. if( !isFts4 && !isCreate ){
  110808. int rc2 = SQLITE_OK;
  110809. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  110810. p->zDb, p->zName);
  110811. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  110812. }
  110813. /* Figure out the page-size for the database. This is required in order to
  110814. ** estimate the cost of loading large doclists from the database. */
  110815. fts3DatabasePageSize(&rc, p);
  110816. p->nNodeSize = p->nPgsz-35;
  110817. /* Declare the table schema to SQLite. */
  110818. fts3DeclareVtab(&rc, p);
  110819. fts3_init_out:
  110820. sqlite3_free(zPrefix);
  110821. sqlite3_free(aIndex);
  110822. sqlite3_free(zCompress);
  110823. sqlite3_free(zUncompress);
  110824. sqlite3_free(zContent);
  110825. sqlite3_free(zLanguageid);
  110826. sqlite3_free((void *)aCol);
  110827. if( rc!=SQLITE_OK ){
  110828. if( p ){
  110829. fts3DisconnectMethod((sqlite3_vtab *)p);
  110830. }else if( pTokenizer ){
  110831. pTokenizer->pModule->xDestroy(pTokenizer);
  110832. }
  110833. }else{
  110834. assert( p->pSegments==0 );
  110835. *ppVTab = &p->base;
  110836. }
  110837. return rc;
  110838. }
  110839. /*
  110840. ** The xConnect() and xCreate() methods for the virtual table. All the
  110841. ** work is done in function fts3InitVtab().
  110842. */
  110843. static int fts3ConnectMethod(
  110844. sqlite3 *db, /* Database connection */
  110845. void *pAux, /* Pointer to tokenizer hash table */
  110846. int argc, /* Number of elements in argv array */
  110847. const char * const *argv, /* xCreate/xConnect argument array */
  110848. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  110849. char **pzErr /* OUT: sqlite3_malloc'd error message */
  110850. ){
  110851. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  110852. }
  110853. static int fts3CreateMethod(
  110854. sqlite3 *db, /* Database connection */
  110855. void *pAux, /* Pointer to tokenizer hash table */
  110856. int argc, /* Number of elements in argv array */
  110857. const char * const *argv, /* xCreate/xConnect argument array */
  110858. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  110859. char **pzErr /* OUT: sqlite3_malloc'd error message */
  110860. ){
  110861. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  110862. }
  110863. /*
  110864. ** Implementation of the xBestIndex method for FTS3 tables. There
  110865. ** are three possible strategies, in order of preference:
  110866. **
  110867. ** 1. Direct lookup by rowid or docid.
  110868. ** 2. Full-text search using a MATCH operator on a non-docid column.
  110869. ** 3. Linear scan of %_content table.
  110870. */
  110871. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  110872. Fts3Table *p = (Fts3Table *)pVTab;
  110873. int i; /* Iterator variable */
  110874. int iCons = -1; /* Index of constraint to use */
  110875. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  110876. /* By default use a full table scan. This is an expensive option,
  110877. ** so search through the constraints to see if a more efficient
  110878. ** strategy is possible.
  110879. */
  110880. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  110881. pInfo->estimatedCost = 500000;
  110882. for(i=0; i<pInfo->nConstraint; i++){
  110883. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  110884. if( pCons->usable==0 ) continue;
  110885. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  110886. if( iCons<0
  110887. && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  110888. && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
  110889. ){
  110890. pInfo->idxNum = FTS3_DOCID_SEARCH;
  110891. pInfo->estimatedCost = 1.0;
  110892. iCons = i;
  110893. }
  110894. /* A MATCH constraint. Use a full-text search.
  110895. **
  110896. ** If there is more than one MATCH constraint available, use the first
  110897. ** one encountered. If there is both a MATCH constraint and a direct
  110898. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  110899. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  110900. ** it would lead to an "unable to use function MATCH in the requested
  110901. ** context" error.
  110902. */
  110903. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  110904. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  110905. ){
  110906. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  110907. pInfo->estimatedCost = 2.0;
  110908. iCons = i;
  110909. }
  110910. /* Equality constraint on the langid column */
  110911. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  110912. && pCons->iColumn==p->nColumn + 2
  110913. ){
  110914. iLangidCons = i;
  110915. }
  110916. }
  110917. if( iCons>=0 ){
  110918. pInfo->aConstraintUsage[iCons].argvIndex = 1;
  110919. pInfo->aConstraintUsage[iCons].omit = 1;
  110920. }
  110921. if( iLangidCons>=0 ){
  110922. pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
  110923. }
  110924. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  110925. ** docid) order. Both ascending and descending are possible.
  110926. */
  110927. if( pInfo->nOrderBy==1 ){
  110928. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  110929. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  110930. if( pOrder->desc ){
  110931. pInfo->idxStr = "DESC";
  110932. }else{
  110933. pInfo->idxStr = "ASC";
  110934. }
  110935. pInfo->orderByConsumed = 1;
  110936. }
  110937. }
  110938. assert( p->pSegments==0 );
  110939. return SQLITE_OK;
  110940. }
  110941. /*
  110942. ** Implementation of xOpen method.
  110943. */
  110944. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  110945. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  110946. UNUSED_PARAMETER(pVTab);
  110947. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  110948. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  110949. ** if the allocation fails, return SQLITE_NOMEM.
  110950. */
  110951. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  110952. if( !pCsr ){
  110953. return SQLITE_NOMEM;
  110954. }
  110955. memset(pCsr, 0, sizeof(Fts3Cursor));
  110956. return SQLITE_OK;
  110957. }
  110958. /*
  110959. ** Close the cursor. For additional information see the documentation
  110960. ** on the xClose method of the virtual table interface.
  110961. */
  110962. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  110963. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  110964. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  110965. sqlite3_finalize(pCsr->pStmt);
  110966. sqlite3Fts3ExprFree(pCsr->pExpr);
  110967. sqlite3Fts3FreeDeferredTokens(pCsr);
  110968. sqlite3_free(pCsr->aDoclist);
  110969. sqlite3_free(pCsr->aMatchinfo);
  110970. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  110971. sqlite3_free(pCsr);
  110972. return SQLITE_OK;
  110973. }
  110974. /*
  110975. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  110976. ** compose and prepare an SQL statement of the form:
  110977. **
  110978. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  110979. **
  110980. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  110981. ** it. If an error occurs, return an SQLite error code.
  110982. **
  110983. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  110984. */
  110985. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  110986. int rc = SQLITE_OK;
  110987. if( pCsr->pStmt==0 ){
  110988. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  110989. char *zSql;
  110990. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  110991. if( !zSql ) return SQLITE_NOMEM;
  110992. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  110993. sqlite3_free(zSql);
  110994. }
  110995. *ppStmt = pCsr->pStmt;
  110996. return rc;
  110997. }
  110998. /*
  110999. ** Position the pCsr->pStmt statement so that it is on the row
  111000. ** of the %_content table that contains the last match. Return
  111001. ** SQLITE_OK on success.
  111002. */
  111003. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  111004. int rc = SQLITE_OK;
  111005. if( pCsr->isRequireSeek ){
  111006. sqlite3_stmt *pStmt = 0;
  111007. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  111008. if( rc==SQLITE_OK ){
  111009. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  111010. pCsr->isRequireSeek = 0;
  111011. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  111012. return SQLITE_OK;
  111013. }else{
  111014. rc = sqlite3_reset(pCsr->pStmt);
  111015. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  111016. /* If no row was found and no error has occured, then the %_content
  111017. ** table is missing a row that is present in the full-text index.
  111018. ** The data structures are corrupt. */
  111019. rc = FTS_CORRUPT_VTAB;
  111020. pCsr->isEof = 1;
  111021. }
  111022. }
  111023. }
  111024. }
  111025. if( rc!=SQLITE_OK && pContext ){
  111026. sqlite3_result_error_code(pContext, rc);
  111027. }
  111028. return rc;
  111029. }
  111030. /*
  111031. ** This function is used to process a single interior node when searching
  111032. ** a b-tree for a term or term prefix. The node data is passed to this
  111033. ** function via the zNode/nNode parameters. The term to search for is
  111034. ** passed in zTerm/nTerm.
  111035. **
  111036. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  111037. ** of the child node that heads the sub-tree that may contain the term.
  111038. **
  111039. ** If piLast is not NULL, then *piLast is set to the right-most child node
  111040. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  111041. ** a prefix.
  111042. **
  111043. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  111044. */
  111045. static int fts3ScanInteriorNode(
  111046. const char *zTerm, /* Term to select leaves for */
  111047. int nTerm, /* Size of term zTerm in bytes */
  111048. const char *zNode, /* Buffer containing segment interior node */
  111049. int nNode, /* Size of buffer at zNode */
  111050. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  111051. sqlite3_int64 *piLast /* OUT: Selected child node */
  111052. ){
  111053. int rc = SQLITE_OK; /* Return code */
  111054. const char *zCsr = zNode; /* Cursor to iterate through node */
  111055. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  111056. char *zBuffer = 0; /* Buffer to load terms into */
  111057. int nAlloc = 0; /* Size of allocated buffer */
  111058. int isFirstTerm = 1; /* True when processing first term on page */
  111059. sqlite3_int64 iChild; /* Block id of child node to descend to */
  111060. /* Skip over the 'height' varint that occurs at the start of every
  111061. ** interior node. Then load the blockid of the left-child of the b-tree
  111062. ** node into variable iChild.
  111063. **
  111064. ** Even if the data structure on disk is corrupted, this (reading two
  111065. ** varints from the buffer) does not risk an overread. If zNode is a
  111066. ** root node, then the buffer comes from a SELECT statement. SQLite does
  111067. ** not make this guarantee explicitly, but in practice there are always
  111068. ** either more than 20 bytes of allocated space following the nNode bytes of
  111069. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  111070. ** table, then there are always 20 bytes of zeroed padding following the
  111071. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  111072. */
  111073. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  111074. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  111075. if( zCsr>zEnd ){
  111076. return FTS_CORRUPT_VTAB;
  111077. }
  111078. while( zCsr<zEnd && (piFirst || piLast) ){
  111079. int cmp; /* memcmp() result */
  111080. int nSuffix; /* Size of term suffix */
  111081. int nPrefix = 0; /* Size of term prefix */
  111082. int nBuffer; /* Total term size */
  111083. /* Load the next term on the node into zBuffer. Use realloc() to expand
  111084. ** the size of zBuffer if required. */
  111085. if( !isFirstTerm ){
  111086. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  111087. }
  111088. isFirstTerm = 0;
  111089. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  111090. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  111091. rc = FTS_CORRUPT_VTAB;
  111092. goto finish_scan;
  111093. }
  111094. if( nPrefix+nSuffix>nAlloc ){
  111095. char *zNew;
  111096. nAlloc = (nPrefix+nSuffix) * 2;
  111097. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  111098. if( !zNew ){
  111099. rc = SQLITE_NOMEM;
  111100. goto finish_scan;
  111101. }
  111102. zBuffer = zNew;
  111103. }
  111104. assert( zBuffer );
  111105. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  111106. nBuffer = nPrefix + nSuffix;
  111107. zCsr += nSuffix;
  111108. /* Compare the term we are searching for with the term just loaded from
  111109. ** the interior node. If the specified term is greater than or equal
  111110. ** to the term from the interior node, then all terms on the sub-tree
  111111. ** headed by node iChild are smaller than zTerm. No need to search
  111112. ** iChild.
  111113. **
  111114. ** If the interior node term is larger than the specified term, then
  111115. ** the tree headed by iChild may contain the specified term.
  111116. */
  111117. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  111118. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  111119. *piFirst = iChild;
  111120. piFirst = 0;
  111121. }
  111122. if( piLast && cmp<0 ){
  111123. *piLast = iChild;
  111124. piLast = 0;
  111125. }
  111126. iChild++;
  111127. };
  111128. if( piFirst ) *piFirst = iChild;
  111129. if( piLast ) *piLast = iChild;
  111130. finish_scan:
  111131. sqlite3_free(zBuffer);
  111132. return rc;
  111133. }
  111134. /*
  111135. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  111136. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  111137. ** contains a term. This function searches the sub-tree headed by the zNode
  111138. ** node for the range of leaf nodes that may contain the specified term
  111139. ** or terms for which the specified term is a prefix.
  111140. **
  111141. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  111142. ** left-most leaf node in the tree that may contain the specified term.
  111143. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  111144. ** right-most leaf node that may contain a term for which the specified
  111145. ** term is a prefix.
  111146. **
  111147. ** It is possible that the range of returned leaf nodes does not contain
  111148. ** the specified term or any terms for which it is a prefix. However, if the
  111149. ** segment does contain any such terms, they are stored within the identified
  111150. ** range. Because this function only inspects interior segment nodes (and
  111151. ** never loads leaf nodes into memory), it is not possible to be sure.
  111152. **
  111153. ** If an error occurs, an error code other than SQLITE_OK is returned.
  111154. */
  111155. static int fts3SelectLeaf(
  111156. Fts3Table *p, /* Virtual table handle */
  111157. const char *zTerm, /* Term to select leaves for */
  111158. int nTerm, /* Size of term zTerm in bytes */
  111159. const char *zNode, /* Buffer containing segment interior node */
  111160. int nNode, /* Size of buffer at zNode */
  111161. sqlite3_int64 *piLeaf, /* Selected leaf node */
  111162. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  111163. ){
  111164. int rc; /* Return code */
  111165. int iHeight; /* Height of this node in tree */
  111166. assert( piLeaf || piLeaf2 );
  111167. sqlite3Fts3GetVarint32(zNode, &iHeight);
  111168. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  111169. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  111170. if( rc==SQLITE_OK && iHeight>1 ){
  111171. char *zBlob = 0; /* Blob read from %_segments table */
  111172. int nBlob; /* Size of zBlob in bytes */
  111173. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  111174. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  111175. if( rc==SQLITE_OK ){
  111176. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  111177. }
  111178. sqlite3_free(zBlob);
  111179. piLeaf = 0;
  111180. zBlob = 0;
  111181. }
  111182. if( rc==SQLITE_OK ){
  111183. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  111184. }
  111185. if( rc==SQLITE_OK ){
  111186. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  111187. }
  111188. sqlite3_free(zBlob);
  111189. }
  111190. return rc;
  111191. }
  111192. /*
  111193. ** This function is used to create delta-encoded serialized lists of FTS3
  111194. ** varints. Each call to this function appends a single varint to a list.
  111195. */
  111196. static void fts3PutDeltaVarint(
  111197. char **pp, /* IN/OUT: Output pointer */
  111198. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  111199. sqlite3_int64 iVal /* Write this value to the list */
  111200. ){
  111201. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  111202. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  111203. *piPrev = iVal;
  111204. }
  111205. /*
  111206. ** When this function is called, *ppPoslist is assumed to point to the
  111207. ** start of a position-list. After it returns, *ppPoslist points to the
  111208. ** first byte after the position-list.
  111209. **
  111210. ** A position list is list of positions (delta encoded) and columns for
  111211. ** a single document record of a doclist. So, in other words, this
  111212. ** routine advances *ppPoslist so that it points to the next docid in
  111213. ** the doclist, or to the first byte past the end of the doclist.
  111214. **
  111215. ** If pp is not NULL, then the contents of the position list are copied
  111216. ** to *pp. *pp is set to point to the first byte past the last byte copied
  111217. ** before this function returns.
  111218. */
  111219. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  111220. char *pEnd = *ppPoslist;
  111221. char c = 0;
  111222. /* The end of a position list is marked by a zero encoded as an FTS3
  111223. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  111224. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  111225. ** of some other, multi-byte, value.
  111226. **
  111227. ** The following while-loop moves pEnd to point to the first byte that is not
  111228. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  111229. ** pEnd once more so that it points to the byte immediately following the
  111230. ** last byte in the position-list.
  111231. */
  111232. while( *pEnd | c ){
  111233. c = *pEnd++ & 0x80;
  111234. testcase( c!=0 && (*pEnd)==0 );
  111235. }
  111236. pEnd++; /* Advance past the POS_END terminator byte */
  111237. if( pp ){
  111238. int n = (int)(pEnd - *ppPoslist);
  111239. char *p = *pp;
  111240. memcpy(p, *ppPoslist, n);
  111241. p += n;
  111242. *pp = p;
  111243. }
  111244. *ppPoslist = pEnd;
  111245. }
  111246. /*
  111247. ** When this function is called, *ppPoslist is assumed to point to the
  111248. ** start of a column-list. After it returns, *ppPoslist points to the
  111249. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  111250. **
  111251. ** A column-list is list of delta-encoded positions for a single column
  111252. ** within a single document within a doclist.
  111253. **
  111254. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  111255. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  111256. ** the POS_COLUMN or POS_END that terminates the column-list.
  111257. **
  111258. ** If pp is not NULL, then the contents of the column-list are copied
  111259. ** to *pp. *pp is set to point to the first byte past the last byte copied
  111260. ** before this function returns. The POS_COLUMN or POS_END terminator
  111261. ** is not copied into *pp.
  111262. */
  111263. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  111264. char *pEnd = *ppPoslist;
  111265. char c = 0;
  111266. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  111267. ** not part of a multi-byte varint.
  111268. */
  111269. while( 0xFE & (*pEnd | c) ){
  111270. c = *pEnd++ & 0x80;
  111271. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  111272. }
  111273. if( pp ){
  111274. int n = (int)(pEnd - *ppPoslist);
  111275. char *p = *pp;
  111276. memcpy(p, *ppPoslist, n);
  111277. p += n;
  111278. *pp = p;
  111279. }
  111280. *ppPoslist = pEnd;
  111281. }
  111282. /*
  111283. ** Value used to signify the end of an position-list. This is safe because
  111284. ** it is not possible to have a document with 2^31 terms.
  111285. */
  111286. #define POSITION_LIST_END 0x7fffffff
  111287. /*
  111288. ** This function is used to help parse position-lists. When this function is
  111289. ** called, *pp may point to the start of the next varint in the position-list
  111290. ** being parsed, or it may point to 1 byte past the end of the position-list
  111291. ** (in which case **pp will be a terminator bytes POS_END (0) or
  111292. ** (1)).
  111293. **
  111294. ** If *pp points past the end of the current position-list, set *pi to
  111295. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  111296. ** increment the current value of *pi by the value read, and set *pp to
  111297. ** point to the next value before returning.
  111298. **
  111299. ** Before calling this routine *pi must be initialized to the value of
  111300. ** the previous position, or zero if we are reading the first position
  111301. ** in the position-list. Because positions are delta-encoded, the value
  111302. ** of the previous position is needed in order to compute the value of
  111303. ** the next position.
  111304. */
  111305. static void fts3ReadNextPos(
  111306. char **pp, /* IN/OUT: Pointer into position-list buffer */
  111307. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  111308. ){
  111309. if( (**pp)&0xFE ){
  111310. fts3GetDeltaVarint(pp, pi);
  111311. *pi -= 2;
  111312. }else{
  111313. *pi = POSITION_LIST_END;
  111314. }
  111315. }
  111316. /*
  111317. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  111318. ** the value of iCol encoded as a varint to *pp. This will start a new
  111319. ** column list.
  111320. **
  111321. ** Set *pp to point to the byte just after the last byte written before
  111322. ** returning (do not modify it if iCol==0). Return the total number of bytes
  111323. ** written (0 if iCol==0).
  111324. */
  111325. static int fts3PutColNumber(char **pp, int iCol){
  111326. int n = 0; /* Number of bytes written */
  111327. if( iCol ){
  111328. char *p = *pp; /* Output pointer */
  111329. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  111330. *p = 0x01;
  111331. *pp = &p[n];
  111332. }
  111333. return n;
  111334. }
  111335. /*
  111336. ** Compute the union of two position lists. The output written
  111337. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  111338. ** order and with any duplicates removed. All pointers are
  111339. ** updated appropriately. The caller is responsible for insuring
  111340. ** that there is enough space in *pp to hold the complete output.
  111341. */
  111342. static void fts3PoslistMerge(
  111343. char **pp, /* Output buffer */
  111344. char **pp1, /* Left input list */
  111345. char **pp2 /* Right input list */
  111346. ){
  111347. char *p = *pp;
  111348. char *p1 = *pp1;
  111349. char *p2 = *pp2;
  111350. while( *p1 || *p2 ){
  111351. int iCol1; /* The current column index in pp1 */
  111352. int iCol2; /* The current column index in pp2 */
  111353. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  111354. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  111355. else iCol1 = 0;
  111356. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  111357. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  111358. else iCol2 = 0;
  111359. if( iCol1==iCol2 ){
  111360. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  111361. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  111362. sqlite3_int64 iPrev = 0;
  111363. int n = fts3PutColNumber(&p, iCol1);
  111364. p1 += n;
  111365. p2 += n;
  111366. /* At this point, both p1 and p2 point to the start of column-lists
  111367. ** for the same column (the column with index iCol1 and iCol2).
  111368. ** A column-list is a list of non-negative delta-encoded varints, each
  111369. ** incremented by 2 before being stored. Each list is terminated by a
  111370. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  111371. ** and writes the results to buffer p. p is left pointing to the byte
  111372. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  111373. ** written to the output.
  111374. */
  111375. fts3GetDeltaVarint(&p1, &i1);
  111376. fts3GetDeltaVarint(&p2, &i2);
  111377. do {
  111378. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  111379. iPrev -= 2;
  111380. if( i1==i2 ){
  111381. fts3ReadNextPos(&p1, &i1);
  111382. fts3ReadNextPos(&p2, &i2);
  111383. }else if( i1<i2 ){
  111384. fts3ReadNextPos(&p1, &i1);
  111385. }else{
  111386. fts3ReadNextPos(&p2, &i2);
  111387. }
  111388. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  111389. }else if( iCol1<iCol2 ){
  111390. p1 += fts3PutColNumber(&p, iCol1);
  111391. fts3ColumnlistCopy(&p, &p1);
  111392. }else{
  111393. p2 += fts3PutColNumber(&p, iCol2);
  111394. fts3ColumnlistCopy(&p, &p2);
  111395. }
  111396. }
  111397. *p++ = POS_END;
  111398. *pp = p;
  111399. *pp1 = p1 + 1;
  111400. *pp2 = p2 + 1;
  111401. }
  111402. /*
  111403. ** This function is used to merge two position lists into one. When it is
  111404. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  111405. ** the part of a doclist that follows each document id. For example, if a row
  111406. ** contains:
  111407. **
  111408. ** 'a b c'|'x y z'|'a b b a'
  111409. **
  111410. ** Then the position list for this row for token 'b' would consist of:
  111411. **
  111412. ** 0x02 0x01 0x02 0x03 0x03 0x00
  111413. **
  111414. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  111415. ** byte following the 0x00 terminator of their respective position lists.
  111416. **
  111417. ** If isSaveLeft is 0, an entry is added to the output position list for
  111418. ** each position in *pp2 for which there exists one or more positions in
  111419. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  111420. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  111421. ** slots before it.
  111422. **
  111423. ** e.g. nToken==1 searches for adjacent positions.
  111424. */
  111425. static int fts3PoslistPhraseMerge(
  111426. char **pp, /* IN/OUT: Preallocated output buffer */
  111427. int nToken, /* Maximum difference in token positions */
  111428. int isSaveLeft, /* Save the left position */
  111429. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  111430. char **pp1, /* IN/OUT: Left input list */
  111431. char **pp2 /* IN/OUT: Right input list */
  111432. ){
  111433. char *p = *pp;
  111434. char *p1 = *pp1;
  111435. char *p2 = *pp2;
  111436. int iCol1 = 0;
  111437. int iCol2 = 0;
  111438. /* Never set both isSaveLeft and isExact for the same invocation. */
  111439. assert( isSaveLeft==0 || isExact==0 );
  111440. assert( p!=0 && *p1!=0 && *p2!=0 );
  111441. if( *p1==POS_COLUMN ){
  111442. p1++;
  111443. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  111444. }
  111445. if( *p2==POS_COLUMN ){
  111446. p2++;
  111447. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  111448. }
  111449. while( 1 ){
  111450. if( iCol1==iCol2 ){
  111451. char *pSave = p;
  111452. sqlite3_int64 iPrev = 0;
  111453. sqlite3_int64 iPos1 = 0;
  111454. sqlite3_int64 iPos2 = 0;
  111455. if( iCol1 ){
  111456. *p++ = POS_COLUMN;
  111457. p += sqlite3Fts3PutVarint(p, iCol1);
  111458. }
  111459. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  111460. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  111461. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  111462. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  111463. while( 1 ){
  111464. if( iPos2==iPos1+nToken
  111465. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  111466. ){
  111467. sqlite3_int64 iSave;
  111468. iSave = isSaveLeft ? iPos1 : iPos2;
  111469. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  111470. pSave = 0;
  111471. assert( p );
  111472. }
  111473. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  111474. if( (*p2&0xFE)==0 ) break;
  111475. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  111476. }else{
  111477. if( (*p1&0xFE)==0 ) break;
  111478. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  111479. }
  111480. }
  111481. if( pSave ){
  111482. assert( pp && p );
  111483. p = pSave;
  111484. }
  111485. fts3ColumnlistCopy(0, &p1);
  111486. fts3ColumnlistCopy(0, &p2);
  111487. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  111488. if( 0==*p1 || 0==*p2 ) break;
  111489. p1++;
  111490. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  111491. p2++;
  111492. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  111493. }
  111494. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  111495. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  111496. ** end of the position list, or the 0x01 that precedes the next
  111497. ** column-number in the position list.
  111498. */
  111499. else if( iCol1<iCol2 ){
  111500. fts3ColumnlistCopy(0, &p1);
  111501. if( 0==*p1 ) break;
  111502. p1++;
  111503. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  111504. }else{
  111505. fts3ColumnlistCopy(0, &p2);
  111506. if( 0==*p2 ) break;
  111507. p2++;
  111508. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  111509. }
  111510. }
  111511. fts3PoslistCopy(0, &p2);
  111512. fts3PoslistCopy(0, &p1);
  111513. *pp1 = p1;
  111514. *pp2 = p2;
  111515. if( *pp==p ){
  111516. return 0;
  111517. }
  111518. *p++ = 0x00;
  111519. *pp = p;
  111520. return 1;
  111521. }
  111522. /*
  111523. ** Merge two position-lists as required by the NEAR operator. The argument
  111524. ** position lists correspond to the left and right phrases of an expression
  111525. ** like:
  111526. **
  111527. ** "phrase 1" NEAR "phrase number 2"
  111528. **
  111529. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  111530. ** expression and *pp2 to the right. As usual, the indexes in the position
  111531. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  111532. ** in the example above).
  111533. **
  111534. ** The output position list - written to *pp - is a copy of *pp2 with those
  111535. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  111536. */
  111537. static int fts3PoslistNearMerge(
  111538. char **pp, /* Output buffer */
  111539. char *aTmp, /* Temporary buffer space */
  111540. int nRight, /* Maximum difference in token positions */
  111541. int nLeft, /* Maximum difference in token positions */
  111542. char **pp1, /* IN/OUT: Left input list */
  111543. char **pp2 /* IN/OUT: Right input list */
  111544. ){
  111545. char *p1 = *pp1;
  111546. char *p2 = *pp2;
  111547. char *pTmp1 = aTmp;
  111548. char *pTmp2;
  111549. char *aTmp2;
  111550. int res = 1;
  111551. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  111552. aTmp2 = pTmp2 = pTmp1;
  111553. *pp1 = p1;
  111554. *pp2 = p2;
  111555. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  111556. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  111557. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  111558. }else if( pTmp1!=aTmp ){
  111559. fts3PoslistCopy(pp, &aTmp);
  111560. }else if( pTmp2!=aTmp2 ){
  111561. fts3PoslistCopy(pp, &aTmp2);
  111562. }else{
  111563. res = 0;
  111564. }
  111565. return res;
  111566. }
  111567. /*
  111568. ** An instance of this function is used to merge together the (potentially
  111569. ** large number of) doclists for each term that matches a prefix query.
  111570. ** See function fts3TermSelectMerge() for details.
  111571. */
  111572. typedef struct TermSelect TermSelect;
  111573. struct TermSelect {
  111574. char *aaOutput[16]; /* Malloc'd output buffers */
  111575. int anOutput[16]; /* Size each output buffer in bytes */
  111576. };
  111577. /*
  111578. ** This function is used to read a single varint from a buffer. Parameter
  111579. ** pEnd points 1 byte past the end of the buffer. When this function is
  111580. ** called, if *pp points to pEnd or greater, then the end of the buffer
  111581. ** has been reached. In this case *pp is set to 0 and the function returns.
  111582. **
  111583. ** If *pp does not point to or past pEnd, then a single varint is read
  111584. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  111585. **
  111586. ** If bDescIdx is false, the value read is added to *pVal before returning.
  111587. ** If it is true, the value read is subtracted from *pVal before this
  111588. ** function returns.
  111589. */
  111590. static void fts3GetDeltaVarint3(
  111591. char **pp, /* IN/OUT: Point to read varint from */
  111592. char *pEnd, /* End of buffer */
  111593. int bDescIdx, /* True if docids are descending */
  111594. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  111595. ){
  111596. if( *pp>=pEnd ){
  111597. *pp = 0;
  111598. }else{
  111599. sqlite3_int64 iVal;
  111600. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  111601. if( bDescIdx ){
  111602. *pVal -= iVal;
  111603. }else{
  111604. *pVal += iVal;
  111605. }
  111606. }
  111607. }
  111608. /*
  111609. ** This function is used to write a single varint to a buffer. The varint
  111610. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  111611. ** end of the value written.
  111612. **
  111613. ** If *pbFirst is zero when this function is called, the value written to
  111614. ** the buffer is that of parameter iVal.
  111615. **
  111616. ** If *pbFirst is non-zero when this function is called, then the value
  111617. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  111618. ** (if bDescIdx is non-zero).
  111619. **
  111620. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  111621. ** to the value of parameter iVal.
  111622. */
  111623. static void fts3PutDeltaVarint3(
  111624. char **pp, /* IN/OUT: Output pointer */
  111625. int bDescIdx, /* True for descending docids */
  111626. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  111627. int *pbFirst, /* IN/OUT: True after first int written */
  111628. sqlite3_int64 iVal /* Write this value to the list */
  111629. ){
  111630. sqlite3_int64 iWrite;
  111631. if( bDescIdx==0 || *pbFirst==0 ){
  111632. iWrite = iVal - *piPrev;
  111633. }else{
  111634. iWrite = *piPrev - iVal;
  111635. }
  111636. assert( *pbFirst || *piPrev==0 );
  111637. assert( *pbFirst==0 || iWrite>0 );
  111638. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  111639. *piPrev = iVal;
  111640. *pbFirst = 1;
  111641. }
  111642. /*
  111643. ** This macro is used by various functions that merge doclists. The two
  111644. ** arguments are 64-bit docid values. If the value of the stack variable
  111645. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  111646. ** Otherwise, (i2-i1).
  111647. **
  111648. ** Using this makes it easier to write code that can merge doclists that are
  111649. ** sorted in either ascending or descending order.
  111650. */
  111651. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  111652. /*
  111653. ** This function does an "OR" merge of two doclists (output contains all
  111654. ** positions contained in either argument doclist). If the docids in the
  111655. ** input doclists are sorted in ascending order, parameter bDescDoclist
  111656. ** should be false. If they are sorted in ascending order, it should be
  111657. ** passed a non-zero value.
  111658. **
  111659. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  111660. ** containing the output doclist and SQLITE_OK is returned. In this case
  111661. ** *pnOut is set to the number of bytes in the output doclist.
  111662. **
  111663. ** If an error occurs, an SQLite error code is returned. The output values
  111664. ** are undefined in this case.
  111665. */
  111666. static int fts3DoclistOrMerge(
  111667. int bDescDoclist, /* True if arguments are desc */
  111668. char *a1, int n1, /* First doclist */
  111669. char *a2, int n2, /* Second doclist */
  111670. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  111671. ){
  111672. sqlite3_int64 i1 = 0;
  111673. sqlite3_int64 i2 = 0;
  111674. sqlite3_int64 iPrev = 0;
  111675. char *pEnd1 = &a1[n1];
  111676. char *pEnd2 = &a2[n2];
  111677. char *p1 = a1;
  111678. char *p2 = a2;
  111679. char *p;
  111680. char *aOut;
  111681. int bFirstOut = 0;
  111682. *paOut = 0;
  111683. *pnOut = 0;
  111684. /* Allocate space for the output. Both the input and output doclists
  111685. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  111686. ** then the first docid in each list is simply encoded as a varint. For
  111687. ** each subsequent docid, the varint stored is the difference between the
  111688. ** current and previous docid (a positive number - since the list is in
  111689. ** ascending order).
  111690. **
  111691. ** The first docid written to the output is therefore encoded using the
  111692. ** same number of bytes as it is in whichever of the input lists it is
  111693. ** read from. And each subsequent docid read from the same input list
  111694. ** consumes either the same or less bytes as it did in the input (since
  111695. ** the difference between it and the previous value in the output must
  111696. ** be a positive value less than or equal to the delta value read from
  111697. ** the input list). The same argument applies to all but the first docid
  111698. ** read from the 'other' list. And to the contents of all position lists
  111699. ** that will be copied and merged from the input to the output.
  111700. **
  111701. ** However, if the first docid copied to the output is a negative number,
  111702. ** then the encoding of the first docid from the 'other' input list may
  111703. ** be larger in the output than it was in the input (since the delta value
  111704. ** may be a larger positive integer than the actual docid).
  111705. **
  111706. ** The space required to store the output is therefore the sum of the
  111707. ** sizes of the two inputs, plus enough space for exactly one of the input
  111708. ** docids to grow.
  111709. **
  111710. ** A symetric argument may be made if the doclists are in descending
  111711. ** order.
  111712. */
  111713. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  111714. if( !aOut ) return SQLITE_NOMEM;
  111715. p = aOut;
  111716. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  111717. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  111718. while( p1 || p2 ){
  111719. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  111720. if( p2 && p1 && iDiff==0 ){
  111721. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  111722. fts3PoslistMerge(&p, &p1, &p2);
  111723. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  111724. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  111725. }else if( !p2 || (p1 && iDiff<0) ){
  111726. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  111727. fts3PoslistCopy(&p, &p1);
  111728. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  111729. }else{
  111730. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  111731. fts3PoslistCopy(&p, &p2);
  111732. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  111733. }
  111734. }
  111735. *paOut = aOut;
  111736. *pnOut = (int)(p-aOut);
  111737. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  111738. return SQLITE_OK;
  111739. }
  111740. /*
  111741. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  111742. ** the output contains a copy of each position from the right-hand input
  111743. ** doclist for which there is a position in the left-hand input doclist
  111744. ** exactly nDist tokens before it.
  111745. **
  111746. ** If the docids in the input doclists are sorted in ascending order,
  111747. ** parameter bDescDoclist should be false. If they are sorted in ascending
  111748. ** order, it should be passed a non-zero value.
  111749. **
  111750. ** The right-hand input doclist is overwritten by this function.
  111751. */
  111752. static void fts3DoclistPhraseMerge(
  111753. int bDescDoclist, /* True if arguments are desc */
  111754. int nDist, /* Distance from left to right (1=adjacent) */
  111755. char *aLeft, int nLeft, /* Left doclist */
  111756. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  111757. ){
  111758. sqlite3_int64 i1 = 0;
  111759. sqlite3_int64 i2 = 0;
  111760. sqlite3_int64 iPrev = 0;
  111761. char *pEnd1 = &aLeft[nLeft];
  111762. char *pEnd2 = &aRight[*pnRight];
  111763. char *p1 = aLeft;
  111764. char *p2 = aRight;
  111765. char *p;
  111766. int bFirstOut = 0;
  111767. char *aOut = aRight;
  111768. assert( nDist>0 );
  111769. p = aOut;
  111770. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  111771. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  111772. while( p1 && p2 ){
  111773. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  111774. if( iDiff==0 ){
  111775. char *pSave = p;
  111776. sqlite3_int64 iPrevSave = iPrev;
  111777. int bFirstOutSave = bFirstOut;
  111778. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  111779. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  111780. p = pSave;
  111781. iPrev = iPrevSave;
  111782. bFirstOut = bFirstOutSave;
  111783. }
  111784. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  111785. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  111786. }else if( iDiff<0 ){
  111787. fts3PoslistCopy(0, &p1);
  111788. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  111789. }else{
  111790. fts3PoslistCopy(0, &p2);
  111791. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  111792. }
  111793. }
  111794. *pnRight = (int)(p - aOut);
  111795. }
  111796. /*
  111797. ** Argument pList points to a position list nList bytes in size. This
  111798. ** function checks to see if the position list contains any entries for
  111799. ** a token in position 0 (of any column). If so, it writes argument iDelta
  111800. ** to the output buffer pOut, followed by a position list consisting only
  111801. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  111802. ** The value returned is the number of bytes written to pOut (if any).
  111803. */
  111804. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  111805. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  111806. char *pList, /* Position list (no 0x00 term) */
  111807. int nList, /* Size of pList in bytes */
  111808. char *pOut /* Write output here */
  111809. ){
  111810. int nOut = 0;
  111811. int bWritten = 0; /* True once iDelta has been written */
  111812. char *p = pList;
  111813. char *pEnd = &pList[nList];
  111814. if( *p!=0x01 ){
  111815. if( *p==0x02 ){
  111816. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  111817. pOut[nOut++] = 0x02;
  111818. bWritten = 1;
  111819. }
  111820. fts3ColumnlistCopy(0, &p);
  111821. }
  111822. while( p<pEnd && *p==0x01 ){
  111823. sqlite3_int64 iCol;
  111824. p++;
  111825. p += sqlite3Fts3GetVarint(p, &iCol);
  111826. if( *p==0x02 ){
  111827. if( bWritten==0 ){
  111828. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  111829. bWritten = 1;
  111830. }
  111831. pOut[nOut++] = 0x01;
  111832. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  111833. pOut[nOut++] = 0x02;
  111834. }
  111835. fts3ColumnlistCopy(0, &p);
  111836. }
  111837. if( bWritten ){
  111838. pOut[nOut++] = 0x00;
  111839. }
  111840. return nOut;
  111841. }
  111842. /*
  111843. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  111844. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  111845. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  111846. **
  111847. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  111848. ** the responsibility of the caller to free any doclists left in the
  111849. ** TermSelect.aaOutput[] array.
  111850. */
  111851. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  111852. char *aOut = 0;
  111853. int nOut = 0;
  111854. int i;
  111855. /* Loop through the doclists in the aaOutput[] array. Merge them all
  111856. ** into a single doclist.
  111857. */
  111858. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  111859. if( pTS->aaOutput[i] ){
  111860. if( !aOut ){
  111861. aOut = pTS->aaOutput[i];
  111862. nOut = pTS->anOutput[i];
  111863. pTS->aaOutput[i] = 0;
  111864. }else{
  111865. int nNew;
  111866. char *aNew;
  111867. int rc = fts3DoclistOrMerge(p->bDescIdx,
  111868. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  111869. );
  111870. if( rc!=SQLITE_OK ){
  111871. sqlite3_free(aOut);
  111872. return rc;
  111873. }
  111874. sqlite3_free(pTS->aaOutput[i]);
  111875. sqlite3_free(aOut);
  111876. pTS->aaOutput[i] = 0;
  111877. aOut = aNew;
  111878. nOut = nNew;
  111879. }
  111880. }
  111881. }
  111882. pTS->aaOutput[0] = aOut;
  111883. pTS->anOutput[0] = nOut;
  111884. return SQLITE_OK;
  111885. }
  111886. /*
  111887. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  111888. ** as the first argument. The merge is an "OR" merge (see function
  111889. ** fts3DoclistOrMerge() for details).
  111890. **
  111891. ** This function is called with the doclist for each term that matches
  111892. ** a queried prefix. It merges all these doclists into one, the doclist
  111893. ** for the specified prefix. Since there can be a very large number of
  111894. ** doclists to merge, the merging is done pair-wise using the TermSelect
  111895. ** object.
  111896. **
  111897. ** This function returns SQLITE_OK if the merge is successful, or an
  111898. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  111899. */
  111900. static int fts3TermSelectMerge(
  111901. Fts3Table *p, /* FTS table handle */
  111902. TermSelect *pTS, /* TermSelect object to merge into */
  111903. char *aDoclist, /* Pointer to doclist */
  111904. int nDoclist /* Size of aDoclist in bytes */
  111905. ){
  111906. if( pTS->aaOutput[0]==0 ){
  111907. /* If this is the first term selected, copy the doclist to the output
  111908. ** buffer using memcpy(). */
  111909. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  111910. pTS->anOutput[0] = nDoclist;
  111911. if( pTS->aaOutput[0] ){
  111912. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  111913. }else{
  111914. return SQLITE_NOMEM;
  111915. }
  111916. }else{
  111917. char *aMerge = aDoclist;
  111918. int nMerge = nDoclist;
  111919. int iOut;
  111920. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  111921. if( pTS->aaOutput[iOut]==0 ){
  111922. assert( iOut>0 );
  111923. pTS->aaOutput[iOut] = aMerge;
  111924. pTS->anOutput[iOut] = nMerge;
  111925. break;
  111926. }else{
  111927. char *aNew;
  111928. int nNew;
  111929. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  111930. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  111931. );
  111932. if( rc!=SQLITE_OK ){
  111933. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  111934. return rc;
  111935. }
  111936. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  111937. sqlite3_free(pTS->aaOutput[iOut]);
  111938. pTS->aaOutput[iOut] = 0;
  111939. aMerge = aNew;
  111940. nMerge = nNew;
  111941. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  111942. pTS->aaOutput[iOut] = aMerge;
  111943. pTS->anOutput[iOut] = nMerge;
  111944. }
  111945. }
  111946. }
  111947. }
  111948. return SQLITE_OK;
  111949. }
  111950. /*
  111951. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  111952. */
  111953. static int fts3SegReaderCursorAppend(
  111954. Fts3MultiSegReader *pCsr,
  111955. Fts3SegReader *pNew
  111956. ){
  111957. if( (pCsr->nSegment%16)==0 ){
  111958. Fts3SegReader **apNew;
  111959. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  111960. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  111961. if( !apNew ){
  111962. sqlite3Fts3SegReaderFree(pNew);
  111963. return SQLITE_NOMEM;
  111964. }
  111965. pCsr->apSegment = apNew;
  111966. }
  111967. pCsr->apSegment[pCsr->nSegment++] = pNew;
  111968. return SQLITE_OK;
  111969. }
  111970. /*
  111971. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  111972. ** 8th argument.
  111973. **
  111974. ** This function returns SQLITE_OK if successful, or an SQLite error code
  111975. ** otherwise.
  111976. */
  111977. static int fts3SegReaderCursor(
  111978. Fts3Table *p, /* FTS3 table handle */
  111979. int iLangid, /* Language id */
  111980. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  111981. int iLevel, /* Level of segments to scan */
  111982. const char *zTerm, /* Term to query for */
  111983. int nTerm, /* Size of zTerm in bytes */
  111984. int isPrefix, /* True for a prefix search */
  111985. int isScan, /* True to scan from zTerm to EOF */
  111986. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  111987. ){
  111988. int rc = SQLITE_OK; /* Error code */
  111989. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  111990. int rc2; /* Result of sqlite3_reset() */
  111991. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  111992. ** for the pending-terms. If this is a scan, then this call must be being
  111993. ** made by an fts4aux module, not an FTS table. In this case calling
  111994. ** Fts3SegReaderPending might segfault, as the data structures used by
  111995. ** fts4aux are not completely populated. So it's easiest to filter these
  111996. ** calls out here. */
  111997. if( iLevel<0 && p->aIndex ){
  111998. Fts3SegReader *pSeg = 0;
  111999. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  112000. if( rc==SQLITE_OK && pSeg ){
  112001. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  112002. }
  112003. }
  112004. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  112005. if( rc==SQLITE_OK ){
  112006. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  112007. }
  112008. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  112009. Fts3SegReader *pSeg = 0;
  112010. /* Read the values returned by the SELECT into local variables. */
  112011. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  112012. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  112013. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  112014. int nRoot = sqlite3_column_bytes(pStmt, 4);
  112015. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  112016. /* If zTerm is not NULL, and this segment is not stored entirely on its
  112017. ** root node, the range of leaves scanned can be reduced. Do this. */
  112018. if( iStartBlock && zTerm ){
  112019. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  112020. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  112021. if( rc!=SQLITE_OK ) goto finished;
  112022. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  112023. }
  112024. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  112025. (isPrefix==0 && isScan==0),
  112026. iStartBlock, iLeavesEndBlock,
  112027. iEndBlock, zRoot, nRoot, &pSeg
  112028. );
  112029. if( rc!=SQLITE_OK ) goto finished;
  112030. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  112031. }
  112032. }
  112033. finished:
  112034. rc2 = sqlite3_reset(pStmt);
  112035. if( rc==SQLITE_DONE ) rc = rc2;
  112036. return rc;
  112037. }
  112038. /*
  112039. ** Set up a cursor object for iterating through a full-text index or a
  112040. ** single level therein.
  112041. */
  112042. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  112043. Fts3Table *p, /* FTS3 table handle */
  112044. int iLangid, /* Language-id to search */
  112045. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  112046. int iLevel, /* Level of segments to scan */
  112047. const char *zTerm, /* Term to query for */
  112048. int nTerm, /* Size of zTerm in bytes */
  112049. int isPrefix, /* True for a prefix search */
  112050. int isScan, /* True to scan from zTerm to EOF */
  112051. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  112052. ){
  112053. assert( iIndex>=0 && iIndex<p->nIndex );
  112054. assert( iLevel==FTS3_SEGCURSOR_ALL
  112055. || iLevel==FTS3_SEGCURSOR_PENDING
  112056. || iLevel>=0
  112057. );
  112058. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  112059. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  112060. assert( isPrefix==0 || isScan==0 );
  112061. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  112062. return fts3SegReaderCursor(
  112063. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  112064. );
  112065. }
  112066. /*
  112067. ** In addition to its current configuration, have the Fts3MultiSegReader
  112068. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  112069. **
  112070. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  112071. */
  112072. static int fts3SegReaderCursorAddZero(
  112073. Fts3Table *p, /* FTS virtual table handle */
  112074. int iLangid,
  112075. const char *zTerm, /* Term to scan doclist of */
  112076. int nTerm, /* Number of bytes in zTerm */
  112077. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  112078. ){
  112079. return fts3SegReaderCursor(p,
  112080. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  112081. );
  112082. }
  112083. /*
  112084. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  112085. ** if isPrefix is true, to scan the doclist for all terms for which
  112086. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  112087. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  112088. ** an SQLite error code.
  112089. **
  112090. ** It is the responsibility of the caller to free this object by eventually
  112091. ** passing it to fts3SegReaderCursorFree()
  112092. **
  112093. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  112094. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  112095. */
  112096. static int fts3TermSegReaderCursor(
  112097. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  112098. const char *zTerm, /* Term to query for */
  112099. int nTerm, /* Size of zTerm in bytes */
  112100. int isPrefix, /* True for a prefix search */
  112101. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  112102. ){
  112103. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  112104. int rc = SQLITE_NOMEM; /* Return code */
  112105. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  112106. if( pSegcsr ){
  112107. int i;
  112108. int bFound = 0; /* True once an index has been found */
  112109. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  112110. if( isPrefix ){
  112111. for(i=1; bFound==0 && i<p->nIndex; i++){
  112112. if( p->aIndex[i].nPrefix==nTerm ){
  112113. bFound = 1;
  112114. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  112115. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  112116. );
  112117. pSegcsr->bLookup = 1;
  112118. }
  112119. }
  112120. for(i=1; bFound==0 && i<p->nIndex; i++){
  112121. if( p->aIndex[i].nPrefix==nTerm+1 ){
  112122. bFound = 1;
  112123. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  112124. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  112125. );
  112126. if( rc==SQLITE_OK ){
  112127. rc = fts3SegReaderCursorAddZero(
  112128. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  112129. );
  112130. }
  112131. }
  112132. }
  112133. }
  112134. if( bFound==0 ){
  112135. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  112136. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  112137. );
  112138. pSegcsr->bLookup = !isPrefix;
  112139. }
  112140. }
  112141. *ppSegcsr = pSegcsr;
  112142. return rc;
  112143. }
  112144. /*
  112145. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  112146. */
  112147. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  112148. sqlite3Fts3SegReaderFinish(pSegcsr);
  112149. sqlite3_free(pSegcsr);
  112150. }
  112151. /*
  112152. ** This function retreives the doclist for the specified term (or term
  112153. ** prefix) from the database.
  112154. */
  112155. static int fts3TermSelect(
  112156. Fts3Table *p, /* Virtual table handle */
  112157. Fts3PhraseToken *pTok, /* Token to query for */
  112158. int iColumn, /* Column to query (or -ve for all columns) */
  112159. int *pnOut, /* OUT: Size of buffer at *ppOut */
  112160. char **ppOut /* OUT: Malloced result buffer */
  112161. ){
  112162. int rc; /* Return code */
  112163. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  112164. TermSelect tsc; /* Object for pair-wise doclist merging */
  112165. Fts3SegFilter filter; /* Segment term filter configuration */
  112166. pSegcsr = pTok->pSegcsr;
  112167. memset(&tsc, 0, sizeof(TermSelect));
  112168. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  112169. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  112170. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  112171. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  112172. filter.iCol = iColumn;
  112173. filter.zTerm = pTok->z;
  112174. filter.nTerm = pTok->n;
  112175. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  112176. while( SQLITE_OK==rc
  112177. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  112178. ){
  112179. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  112180. }
  112181. if( rc==SQLITE_OK ){
  112182. rc = fts3TermSelectFinishMerge(p, &tsc);
  112183. }
  112184. if( rc==SQLITE_OK ){
  112185. *ppOut = tsc.aaOutput[0];
  112186. *pnOut = tsc.anOutput[0];
  112187. }else{
  112188. int i;
  112189. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  112190. sqlite3_free(tsc.aaOutput[i]);
  112191. }
  112192. }
  112193. fts3SegReaderCursorFree(pSegcsr);
  112194. pTok->pSegcsr = 0;
  112195. return rc;
  112196. }
  112197. /*
  112198. ** This function counts the total number of docids in the doclist stored
  112199. ** in buffer aList[], size nList bytes.
  112200. **
  112201. ** If the isPoslist argument is true, then it is assumed that the doclist
  112202. ** contains a position-list following each docid. Otherwise, it is assumed
  112203. ** that the doclist is simply a list of docids stored as delta encoded
  112204. ** varints.
  112205. */
  112206. static int fts3DoclistCountDocids(char *aList, int nList){
  112207. int nDoc = 0; /* Return value */
  112208. if( aList ){
  112209. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  112210. char *p = aList; /* Cursor */
  112211. while( p<aEnd ){
  112212. nDoc++;
  112213. while( (*p++)&0x80 ); /* Skip docid varint */
  112214. fts3PoslistCopy(0, &p); /* Skip over position list */
  112215. }
  112216. }
  112217. return nDoc;
  112218. }
  112219. /*
  112220. ** Advance the cursor to the next row in the %_content table that
  112221. ** matches the search criteria. For a MATCH search, this will be
  112222. ** the next row that matches. For a full-table scan, this will be
  112223. ** simply the next row in the %_content table. For a docid lookup,
  112224. ** this routine simply sets the EOF flag.
  112225. **
  112226. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  112227. ** even if we reach end-of-file. The fts3EofMethod() will be called
  112228. ** subsequently to determine whether or not an EOF was hit.
  112229. */
  112230. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  112231. int rc;
  112232. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  112233. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  112234. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  112235. pCsr->isEof = 1;
  112236. rc = sqlite3_reset(pCsr->pStmt);
  112237. }else{
  112238. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  112239. rc = SQLITE_OK;
  112240. }
  112241. }else{
  112242. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  112243. }
  112244. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  112245. return rc;
  112246. }
  112247. /*
  112248. ** This is the xFilter interface for the virtual table. See
  112249. ** the virtual table xFilter method documentation for additional
  112250. ** information.
  112251. **
  112252. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  112253. ** the %_content table.
  112254. **
  112255. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  112256. ** in the %_content table.
  112257. **
  112258. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  112259. ** column on the left-hand side of the MATCH operator is column
  112260. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  112261. ** side of the MATCH operator.
  112262. */
  112263. static int fts3FilterMethod(
  112264. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  112265. int idxNum, /* Strategy index */
  112266. const char *idxStr, /* Unused */
  112267. int nVal, /* Number of elements in apVal */
  112268. sqlite3_value **apVal /* Arguments for the indexing scheme */
  112269. ){
  112270. int rc;
  112271. char *zSql; /* SQL statement used to access %_content */
  112272. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  112273. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  112274. UNUSED_PARAMETER(idxStr);
  112275. UNUSED_PARAMETER(nVal);
  112276. assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  112277. assert( nVal==0 || nVal==1 || nVal==2 );
  112278. assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
  112279. assert( p->pSegments==0 );
  112280. /* In case the cursor has been used before, clear it now. */
  112281. sqlite3_finalize(pCsr->pStmt);
  112282. sqlite3_free(pCsr->aDoclist);
  112283. sqlite3Fts3ExprFree(pCsr->pExpr);
  112284. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  112285. if( idxStr ){
  112286. pCsr->bDesc = (idxStr[0]=='D');
  112287. }else{
  112288. pCsr->bDesc = p->bDescIdx;
  112289. }
  112290. pCsr->eSearch = (i16)idxNum;
  112291. if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
  112292. int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
  112293. const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
  112294. if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  112295. return SQLITE_NOMEM;
  112296. }
  112297. pCsr->iLangid = 0;
  112298. if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
  112299. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  112300. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
  112301. );
  112302. if( rc!=SQLITE_OK ){
  112303. if( rc==SQLITE_ERROR ){
  112304. static const char *zErr = "malformed MATCH expression: [%s]";
  112305. p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
  112306. }
  112307. return rc;
  112308. }
  112309. rc = sqlite3Fts3ReadLock(p);
  112310. if( rc!=SQLITE_OK ) return rc;
  112311. rc = fts3EvalStart(pCsr);
  112312. sqlite3Fts3SegmentsClose(p);
  112313. if( rc!=SQLITE_OK ) return rc;
  112314. pCsr->pNextId = pCsr->aDoclist;
  112315. pCsr->iPrevId = 0;
  112316. }
  112317. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  112318. ** statement loops through all rows of the %_content table. For a
  112319. ** full-text query or docid lookup, the statement retrieves a single
  112320. ** row by docid.
  112321. */
  112322. if( idxNum==FTS3_FULLSCAN_SEARCH ){
  112323. zSql = sqlite3_mprintf(
  112324. "SELECT %s ORDER BY rowid %s",
  112325. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  112326. );
  112327. if( zSql ){
  112328. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  112329. sqlite3_free(zSql);
  112330. }else{
  112331. rc = SQLITE_NOMEM;
  112332. }
  112333. }else if( idxNum==FTS3_DOCID_SEARCH ){
  112334. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  112335. if( rc==SQLITE_OK ){
  112336. rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  112337. }
  112338. }
  112339. if( rc!=SQLITE_OK ) return rc;
  112340. return fts3NextMethod(pCursor);
  112341. }
  112342. /*
  112343. ** This is the xEof method of the virtual table. SQLite calls this
  112344. ** routine to find out if it has reached the end of a result set.
  112345. */
  112346. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  112347. return ((Fts3Cursor *)pCursor)->isEof;
  112348. }
  112349. /*
  112350. ** This is the xRowid method. The SQLite core calls this routine to
  112351. ** retrieve the rowid for the current row of the result set. fts3
  112352. ** exposes %_content.docid as the rowid for the virtual table. The
  112353. ** rowid should be written to *pRowid.
  112354. */
  112355. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  112356. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  112357. *pRowid = pCsr->iPrevId;
  112358. return SQLITE_OK;
  112359. }
  112360. /*
  112361. ** This is the xColumn method, called by SQLite to request a value from
  112362. ** the row that the supplied cursor currently points to.
  112363. **
  112364. ** If:
  112365. **
  112366. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  112367. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  112368. ** (iCol == p->nColumn+1) -> Docid column
  112369. ** (iCol == p->nColumn+2) -> Langid column
  112370. */
  112371. static int fts3ColumnMethod(
  112372. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  112373. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  112374. int iCol /* Index of column to read value from */
  112375. ){
  112376. int rc = SQLITE_OK; /* Return Code */
  112377. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  112378. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  112379. /* The column value supplied by SQLite must be in range. */
  112380. assert( iCol>=0 && iCol<=p->nColumn+2 );
  112381. if( iCol==p->nColumn+1 ){
  112382. /* This call is a request for the "docid" column. Since "docid" is an
  112383. ** alias for "rowid", use the xRowid() method to obtain the value.
  112384. */
  112385. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  112386. }else if( iCol==p->nColumn ){
  112387. /* The extra column whose name is the same as the table.
  112388. ** Return a blob which is a pointer to the cursor. */
  112389. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  112390. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  112391. sqlite3_result_int64(pCtx, pCsr->iLangid);
  112392. }else{
  112393. /* The requested column is either a user column (one that contains
  112394. ** indexed data), or the language-id column. */
  112395. rc = fts3CursorSeek(0, pCsr);
  112396. if( rc==SQLITE_OK ){
  112397. if( iCol==p->nColumn+2 ){
  112398. int iLangid = 0;
  112399. if( p->zLanguageid ){
  112400. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  112401. }
  112402. sqlite3_result_int(pCtx, iLangid);
  112403. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  112404. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  112405. }
  112406. }
  112407. }
  112408. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  112409. return rc;
  112410. }
  112411. /*
  112412. ** This function is the implementation of the xUpdate callback used by
  112413. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  112414. ** inserted, updated or deleted.
  112415. */
  112416. static int fts3UpdateMethod(
  112417. sqlite3_vtab *pVtab, /* Virtual table handle */
  112418. int nArg, /* Size of argument array */
  112419. sqlite3_value **apVal, /* Array of arguments */
  112420. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  112421. ){
  112422. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  112423. }
  112424. /*
  112425. ** Implementation of xSync() method. Flush the contents of the pending-terms
  112426. ** hash-table to the database.
  112427. */
  112428. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  112429. /* Following an incremental-merge operation, assuming that the input
  112430. ** segments are not completely consumed (the usual case), they are updated
  112431. ** in place to remove the entries that have already been merged. This
  112432. ** involves updating the leaf block that contains the smallest unmerged
  112433. ** entry and each block (if any) between the leaf and the root node. So
  112434. ** if the height of the input segment b-trees is N, and input segments
  112435. ** are merged eight at a time, updating the input segments at the end
  112436. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  112437. ** small - often between 0 and 2. So the overhead of the incremental
  112438. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  112439. ** dwarfing the actual productive work accomplished, the incremental merge
  112440. ** is only attempted if it will write at least 64 leaf blocks. Hence
  112441. ** nMinMerge.
  112442. **
  112443. ** Of course, updating the input segments also involves deleting a bunch
  112444. ** of blocks from the segments table. But this is not considered overhead
  112445. ** as it would also be required by a crisis-merge that used the same input
  112446. ** segments.
  112447. */
  112448. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  112449. Fts3Table *p = (Fts3Table*)pVtab;
  112450. int rc = sqlite3Fts3PendingTermsFlush(p);
  112451. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  112452. int mxLevel = 0; /* Maximum relative level value in db */
  112453. int A; /* Incr-merge parameter A */
  112454. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  112455. assert( rc==SQLITE_OK || mxLevel==0 );
  112456. A = p->nLeafAdd * mxLevel;
  112457. A += (A/2);
  112458. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  112459. }
  112460. sqlite3Fts3SegmentsClose(p);
  112461. return rc;
  112462. }
  112463. /*
  112464. ** Implementation of xBegin() method. This is a no-op.
  112465. */
  112466. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  112467. Fts3Table *p = (Fts3Table*)pVtab;
  112468. UNUSED_PARAMETER(pVtab);
  112469. assert( p->pSegments==0 );
  112470. assert( p->nPendingData==0 );
  112471. assert( p->inTransaction!=1 );
  112472. TESTONLY( p->inTransaction = 1 );
  112473. TESTONLY( p->mxSavepoint = -1; );
  112474. p->nLeafAdd = 0;
  112475. return SQLITE_OK;
  112476. }
  112477. /*
  112478. ** Implementation of xCommit() method. This is a no-op. The contents of
  112479. ** the pending-terms hash-table have already been flushed into the database
  112480. ** by fts3SyncMethod().
  112481. */
  112482. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  112483. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  112484. UNUSED_PARAMETER(pVtab);
  112485. assert( p->nPendingData==0 );
  112486. assert( p->inTransaction!=0 );
  112487. assert( p->pSegments==0 );
  112488. TESTONLY( p->inTransaction = 0 );
  112489. TESTONLY( p->mxSavepoint = -1; );
  112490. return SQLITE_OK;
  112491. }
  112492. /*
  112493. ** Implementation of xRollback(). Discard the contents of the pending-terms
  112494. ** hash-table. Any changes made to the database are reverted by SQLite.
  112495. */
  112496. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  112497. Fts3Table *p = (Fts3Table*)pVtab;
  112498. sqlite3Fts3PendingTermsClear(p);
  112499. assert( p->inTransaction!=0 );
  112500. TESTONLY( p->inTransaction = 0 );
  112501. TESTONLY( p->mxSavepoint = -1; );
  112502. return SQLITE_OK;
  112503. }
  112504. /*
  112505. ** When called, *ppPoslist must point to the byte immediately following the
  112506. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  112507. ** moves *ppPoslist so that it instead points to the first byte of the
  112508. ** same position list.
  112509. */
  112510. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  112511. char *p = &(*ppPoslist)[-2];
  112512. char c = 0;
  112513. while( p>pStart && (c=*p--)==0 );
  112514. while( p>pStart && (*p & 0x80) | c ){
  112515. c = *p--;
  112516. }
  112517. if( p>pStart ){ p = &p[2]; }
  112518. while( *p++&0x80 );
  112519. *ppPoslist = p;
  112520. }
  112521. /*
  112522. ** Helper function used by the implementation of the overloaded snippet(),
  112523. ** offsets() and optimize() SQL functions.
  112524. **
  112525. ** If the value passed as the third argument is a blob of size
  112526. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  112527. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  112528. ** message is written to context pContext and SQLITE_ERROR returned. The
  112529. ** string passed via zFunc is used as part of the error message.
  112530. */
  112531. static int fts3FunctionArg(
  112532. sqlite3_context *pContext, /* SQL function call context */
  112533. const char *zFunc, /* Function name */
  112534. sqlite3_value *pVal, /* argv[0] passed to function */
  112535. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  112536. ){
  112537. Fts3Cursor *pRet;
  112538. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  112539. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  112540. ){
  112541. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  112542. sqlite3_result_error(pContext, zErr, -1);
  112543. sqlite3_free(zErr);
  112544. return SQLITE_ERROR;
  112545. }
  112546. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  112547. *ppCsr = pRet;
  112548. return SQLITE_OK;
  112549. }
  112550. /*
  112551. ** Implementation of the snippet() function for FTS3
  112552. */
  112553. static void fts3SnippetFunc(
  112554. sqlite3_context *pContext, /* SQLite function call context */
  112555. int nVal, /* Size of apVal[] array */
  112556. sqlite3_value **apVal /* Array of arguments */
  112557. ){
  112558. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  112559. const char *zStart = "<b>";
  112560. const char *zEnd = "</b>";
  112561. const char *zEllipsis = "<b>...</b>";
  112562. int iCol = -1;
  112563. int nToken = 15; /* Default number of tokens in snippet */
  112564. /* There must be at least one argument passed to this function (otherwise
  112565. ** the non-overloaded version would have been called instead of this one).
  112566. */
  112567. assert( nVal>=1 );
  112568. if( nVal>6 ){
  112569. sqlite3_result_error(pContext,
  112570. "wrong number of arguments to function snippet()", -1);
  112571. return;
  112572. }
  112573. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  112574. switch( nVal ){
  112575. case 6: nToken = sqlite3_value_int(apVal[5]);
  112576. case 5: iCol = sqlite3_value_int(apVal[4]);
  112577. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  112578. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  112579. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  112580. }
  112581. if( !zEllipsis || !zEnd || !zStart ){
  112582. sqlite3_result_error_nomem(pContext);
  112583. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  112584. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  112585. }
  112586. }
  112587. /*
  112588. ** Implementation of the offsets() function for FTS3
  112589. */
  112590. static void fts3OffsetsFunc(
  112591. sqlite3_context *pContext, /* SQLite function call context */
  112592. int nVal, /* Size of argument array */
  112593. sqlite3_value **apVal /* Array of arguments */
  112594. ){
  112595. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  112596. UNUSED_PARAMETER(nVal);
  112597. assert( nVal==1 );
  112598. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  112599. assert( pCsr );
  112600. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  112601. sqlite3Fts3Offsets(pContext, pCsr);
  112602. }
  112603. }
  112604. /*
  112605. ** Implementation of the special optimize() function for FTS3. This
  112606. ** function merges all segments in the database to a single segment.
  112607. ** Example usage is:
  112608. **
  112609. ** SELECT optimize(t) FROM t LIMIT 1;
  112610. **
  112611. ** where 't' is the name of an FTS3 table.
  112612. */
  112613. static void fts3OptimizeFunc(
  112614. sqlite3_context *pContext, /* SQLite function call context */
  112615. int nVal, /* Size of argument array */
  112616. sqlite3_value **apVal /* Array of arguments */
  112617. ){
  112618. int rc; /* Return code */
  112619. Fts3Table *p; /* Virtual table handle */
  112620. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  112621. UNUSED_PARAMETER(nVal);
  112622. assert( nVal==1 );
  112623. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  112624. p = (Fts3Table *)pCursor->base.pVtab;
  112625. assert( p );
  112626. rc = sqlite3Fts3Optimize(p);
  112627. switch( rc ){
  112628. case SQLITE_OK:
  112629. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  112630. break;
  112631. case SQLITE_DONE:
  112632. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  112633. break;
  112634. default:
  112635. sqlite3_result_error_code(pContext, rc);
  112636. break;
  112637. }
  112638. }
  112639. /*
  112640. ** Implementation of the matchinfo() function for FTS3
  112641. */
  112642. static void fts3MatchinfoFunc(
  112643. sqlite3_context *pContext, /* SQLite function call context */
  112644. int nVal, /* Size of argument array */
  112645. sqlite3_value **apVal /* Array of arguments */
  112646. ){
  112647. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  112648. assert( nVal==1 || nVal==2 );
  112649. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  112650. const char *zArg = 0;
  112651. if( nVal>1 ){
  112652. zArg = (const char *)sqlite3_value_text(apVal[1]);
  112653. }
  112654. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  112655. }
  112656. }
  112657. /*
  112658. ** This routine implements the xFindFunction method for the FTS3
  112659. ** virtual table.
  112660. */
  112661. static int fts3FindFunctionMethod(
  112662. sqlite3_vtab *pVtab, /* Virtual table handle */
  112663. int nArg, /* Number of SQL function arguments */
  112664. const char *zName, /* Name of SQL function */
  112665. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  112666. void **ppArg /* Unused */
  112667. ){
  112668. struct Overloaded {
  112669. const char *zName;
  112670. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  112671. } aOverload[] = {
  112672. { "snippet", fts3SnippetFunc },
  112673. { "offsets", fts3OffsetsFunc },
  112674. { "optimize", fts3OptimizeFunc },
  112675. { "matchinfo", fts3MatchinfoFunc },
  112676. };
  112677. int i; /* Iterator variable */
  112678. UNUSED_PARAMETER(pVtab);
  112679. UNUSED_PARAMETER(nArg);
  112680. UNUSED_PARAMETER(ppArg);
  112681. for(i=0; i<SizeofArray(aOverload); i++){
  112682. if( strcmp(zName, aOverload[i].zName)==0 ){
  112683. *pxFunc = aOverload[i].xFunc;
  112684. return 1;
  112685. }
  112686. }
  112687. /* No function of the specified name was found. Return 0. */
  112688. return 0;
  112689. }
  112690. /*
  112691. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  112692. */
  112693. static int fts3RenameMethod(
  112694. sqlite3_vtab *pVtab, /* Virtual table handle */
  112695. const char *zName /* New name of table */
  112696. ){
  112697. Fts3Table *p = (Fts3Table *)pVtab;
  112698. sqlite3 *db = p->db; /* Database connection */
  112699. int rc; /* Return Code */
  112700. /* As it happens, the pending terms table is always empty here. This is
  112701. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  112702. ** always opens a savepoint transaction. And the xSavepoint() method
  112703. ** flushes the pending terms table. But leave the (no-op) call to
  112704. ** PendingTermsFlush() in in case that changes.
  112705. */
  112706. assert( p->nPendingData==0 );
  112707. rc = sqlite3Fts3PendingTermsFlush(p);
  112708. if( p->zContentTbl==0 ){
  112709. fts3DbExec(&rc, db,
  112710. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  112711. p->zDb, p->zName, zName
  112712. );
  112713. }
  112714. if( p->bHasDocsize ){
  112715. fts3DbExec(&rc, db,
  112716. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  112717. p->zDb, p->zName, zName
  112718. );
  112719. }
  112720. if( p->bHasStat ){
  112721. fts3DbExec(&rc, db,
  112722. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  112723. p->zDb, p->zName, zName
  112724. );
  112725. }
  112726. fts3DbExec(&rc, db,
  112727. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  112728. p->zDb, p->zName, zName
  112729. );
  112730. fts3DbExec(&rc, db,
  112731. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  112732. p->zDb, p->zName, zName
  112733. );
  112734. return rc;
  112735. }
  112736. /*
  112737. ** The xSavepoint() method.
  112738. **
  112739. ** Flush the contents of the pending-terms table to disk.
  112740. */
  112741. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  112742. int rc = SQLITE_OK;
  112743. UNUSED_PARAMETER(iSavepoint);
  112744. assert( ((Fts3Table *)pVtab)->inTransaction );
  112745. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  112746. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  112747. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  112748. rc = fts3SyncMethod(pVtab);
  112749. }
  112750. return rc;
  112751. }
  112752. /*
  112753. ** The xRelease() method.
  112754. **
  112755. ** This is a no-op.
  112756. */
  112757. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  112758. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  112759. UNUSED_PARAMETER(iSavepoint);
  112760. UNUSED_PARAMETER(pVtab);
  112761. assert( p->inTransaction );
  112762. assert( p->mxSavepoint >= iSavepoint );
  112763. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  112764. return SQLITE_OK;
  112765. }
  112766. /*
  112767. ** The xRollbackTo() method.
  112768. **
  112769. ** Discard the contents of the pending terms table.
  112770. */
  112771. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  112772. Fts3Table *p = (Fts3Table*)pVtab;
  112773. UNUSED_PARAMETER(iSavepoint);
  112774. assert( p->inTransaction );
  112775. assert( p->mxSavepoint >= iSavepoint );
  112776. TESTONLY( p->mxSavepoint = iSavepoint );
  112777. sqlite3Fts3PendingTermsClear(p);
  112778. return SQLITE_OK;
  112779. }
  112780. static const sqlite3_module fts3Module = {
  112781. /* iVersion */ 2,
  112782. /* xCreate */ fts3CreateMethod,
  112783. /* xConnect */ fts3ConnectMethod,
  112784. /* xBestIndex */ fts3BestIndexMethod,
  112785. /* xDisconnect */ fts3DisconnectMethod,
  112786. /* xDestroy */ fts3DestroyMethod,
  112787. /* xOpen */ fts3OpenMethod,
  112788. /* xClose */ fts3CloseMethod,
  112789. /* xFilter */ fts3FilterMethod,
  112790. /* xNext */ fts3NextMethod,
  112791. /* xEof */ fts3EofMethod,
  112792. /* xColumn */ fts3ColumnMethod,
  112793. /* xRowid */ fts3RowidMethod,
  112794. /* xUpdate */ fts3UpdateMethod,
  112795. /* xBegin */ fts3BeginMethod,
  112796. /* xSync */ fts3SyncMethod,
  112797. /* xCommit */ fts3CommitMethod,
  112798. /* xRollback */ fts3RollbackMethod,
  112799. /* xFindFunction */ fts3FindFunctionMethod,
  112800. /* xRename */ fts3RenameMethod,
  112801. /* xSavepoint */ fts3SavepointMethod,
  112802. /* xRelease */ fts3ReleaseMethod,
  112803. /* xRollbackTo */ fts3RollbackToMethod,
  112804. };
  112805. /*
  112806. ** This function is registered as the module destructor (called when an
  112807. ** FTS3 enabled database connection is closed). It frees the memory
  112808. ** allocated for the tokenizer hash table.
  112809. */
  112810. static void hashDestroy(void *p){
  112811. Fts3Hash *pHash = (Fts3Hash *)p;
  112812. sqlite3Fts3HashClear(pHash);
  112813. sqlite3_free(pHash);
  112814. }
  112815. /*
  112816. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  112817. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  112818. ** respectively. The following three forward declarations are for functions
  112819. ** declared in these files used to retrieve the respective implementations.
  112820. **
  112821. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  112822. ** to by the argument to point to the "simple" tokenizer implementation.
  112823. ** And so on.
  112824. */
  112825. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  112826. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  112827. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  112828. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  112829. #endif
  112830. #ifdef SQLITE_ENABLE_ICU
  112831. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  112832. #endif
  112833. /*
  112834. ** Initialise the fts3 extension. If this extension is built as part
  112835. ** of the sqlite library, then this function is called directly by
  112836. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  112837. ** function is called by the sqlite3_extension_init() entry point.
  112838. */
  112839. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  112840. int rc = SQLITE_OK;
  112841. Fts3Hash *pHash = 0;
  112842. const sqlite3_tokenizer_module *pSimple = 0;
  112843. const sqlite3_tokenizer_module *pPorter = 0;
  112844. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  112845. const sqlite3_tokenizer_module *pUnicode = 0;
  112846. #endif
  112847. #ifdef SQLITE_ENABLE_ICU
  112848. const sqlite3_tokenizer_module *pIcu = 0;
  112849. sqlite3Fts3IcuTokenizerModule(&pIcu);
  112850. #endif
  112851. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  112852. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  112853. #endif
  112854. #ifdef SQLITE_TEST
  112855. rc = sqlite3Fts3InitTerm(db);
  112856. if( rc!=SQLITE_OK ) return rc;
  112857. #endif
  112858. rc = sqlite3Fts3InitAux(db);
  112859. if( rc!=SQLITE_OK ) return rc;
  112860. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  112861. sqlite3Fts3PorterTokenizerModule(&pPorter);
  112862. /* Allocate and initialise the hash-table used to store tokenizers. */
  112863. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  112864. if( !pHash ){
  112865. rc = SQLITE_NOMEM;
  112866. }else{
  112867. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  112868. }
  112869. /* Load the built-in tokenizers into the hash table */
  112870. if( rc==SQLITE_OK ){
  112871. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  112872. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  112873. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  112874. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  112875. #endif
  112876. #ifdef SQLITE_ENABLE_ICU
  112877. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  112878. #endif
  112879. ){
  112880. rc = SQLITE_NOMEM;
  112881. }
  112882. }
  112883. #ifdef SQLITE_TEST
  112884. if( rc==SQLITE_OK ){
  112885. rc = sqlite3Fts3ExprInitTestInterface(db);
  112886. }
  112887. #endif
  112888. /* Create the virtual table wrapper around the hash-table and overload
  112889. ** the two scalar functions. If this is successful, register the
  112890. ** module with sqlite.
  112891. */
  112892. if( SQLITE_OK==rc
  112893. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  112894. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  112895. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  112896. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  112897. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  112898. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  112899. ){
  112900. rc = sqlite3_create_module_v2(
  112901. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  112902. );
  112903. if( rc==SQLITE_OK ){
  112904. rc = sqlite3_create_module_v2(
  112905. db, "fts4", &fts3Module, (void *)pHash, 0
  112906. );
  112907. }
  112908. return rc;
  112909. }
  112910. /* An error has occurred. Delete the hash table and return the error code. */
  112911. assert( rc!=SQLITE_OK );
  112912. if( pHash ){
  112913. sqlite3Fts3HashClear(pHash);
  112914. sqlite3_free(pHash);
  112915. }
  112916. return rc;
  112917. }
  112918. /*
  112919. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  112920. ** by pExpr.
  112921. **
  112922. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  112923. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  112924. ** Fts3SegReader objects internally to provide an interface to seek or scan
  112925. ** within the union of all segments of a b-tree. Hence the name.
  112926. **
  112927. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  112928. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  112929. ** there exists prefix b-tree of the right length) then it may be traversed
  112930. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  112931. ** doclist and then traversed.
  112932. */
  112933. static void fts3EvalAllocateReaders(
  112934. Fts3Cursor *pCsr, /* FTS cursor handle */
  112935. Fts3Expr *pExpr, /* Allocate readers for this expression */
  112936. int *pnToken, /* OUT: Total number of tokens in phrase. */
  112937. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  112938. int *pRc /* IN/OUT: Error code */
  112939. ){
  112940. if( pExpr && SQLITE_OK==*pRc ){
  112941. if( pExpr->eType==FTSQUERY_PHRASE ){
  112942. int i;
  112943. int nToken = pExpr->pPhrase->nToken;
  112944. *pnToken += nToken;
  112945. for(i=0; i<nToken; i++){
  112946. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  112947. int rc = fts3TermSegReaderCursor(pCsr,
  112948. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  112949. );
  112950. if( rc!=SQLITE_OK ){
  112951. *pRc = rc;
  112952. return;
  112953. }
  112954. }
  112955. assert( pExpr->pPhrase->iDoclistToken==0 );
  112956. pExpr->pPhrase->iDoclistToken = -1;
  112957. }else{
  112958. *pnOr += (pExpr->eType==FTSQUERY_OR);
  112959. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  112960. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  112961. }
  112962. }
  112963. }
  112964. /*
  112965. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  112966. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  112967. **
  112968. ** This function assumes that pList points to a buffer allocated using
  112969. ** sqlite3_malloc(). This function takes responsibility for eventually
  112970. ** freeing the buffer.
  112971. */
  112972. static void fts3EvalPhraseMergeToken(
  112973. Fts3Table *pTab, /* FTS Table pointer */
  112974. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  112975. int iToken, /* Token pList/nList corresponds to */
  112976. char *pList, /* Pointer to doclist */
  112977. int nList /* Number of bytes in pList */
  112978. ){
  112979. assert( iToken!=p->iDoclistToken );
  112980. if( pList==0 ){
  112981. sqlite3_free(p->doclist.aAll);
  112982. p->doclist.aAll = 0;
  112983. p->doclist.nAll = 0;
  112984. }
  112985. else if( p->iDoclistToken<0 ){
  112986. p->doclist.aAll = pList;
  112987. p->doclist.nAll = nList;
  112988. }
  112989. else if( p->doclist.aAll==0 ){
  112990. sqlite3_free(pList);
  112991. }
  112992. else {
  112993. char *pLeft;
  112994. char *pRight;
  112995. int nLeft;
  112996. int nRight;
  112997. int nDiff;
  112998. if( p->iDoclistToken<iToken ){
  112999. pLeft = p->doclist.aAll;
  113000. nLeft = p->doclist.nAll;
  113001. pRight = pList;
  113002. nRight = nList;
  113003. nDiff = iToken - p->iDoclistToken;
  113004. }else{
  113005. pRight = p->doclist.aAll;
  113006. nRight = p->doclist.nAll;
  113007. pLeft = pList;
  113008. nLeft = nList;
  113009. nDiff = p->iDoclistToken - iToken;
  113010. }
  113011. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  113012. sqlite3_free(pLeft);
  113013. p->doclist.aAll = pRight;
  113014. p->doclist.nAll = nRight;
  113015. }
  113016. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  113017. }
  113018. /*
  113019. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  113020. ** does not take deferred tokens into account.
  113021. **
  113022. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  113023. */
  113024. static int fts3EvalPhraseLoad(
  113025. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113026. Fts3Phrase *p /* Phrase object */
  113027. ){
  113028. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113029. int iToken;
  113030. int rc = SQLITE_OK;
  113031. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  113032. Fts3PhraseToken *pToken = &p->aToken[iToken];
  113033. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  113034. if( pToken->pSegcsr ){
  113035. int nThis = 0;
  113036. char *pThis = 0;
  113037. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  113038. if( rc==SQLITE_OK ){
  113039. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  113040. }
  113041. }
  113042. assert( pToken->pSegcsr==0 );
  113043. }
  113044. return rc;
  113045. }
  113046. /*
  113047. ** This function is called on each phrase after the position lists for
  113048. ** any deferred tokens have been loaded into memory. It updates the phrases
  113049. ** current position list to include only those positions that are really
  113050. ** instances of the phrase (after considering deferred tokens). If this
  113051. ** means that the phrase does not appear in the current row, doclist.pList
  113052. ** and doclist.nList are both zeroed.
  113053. **
  113054. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  113055. */
  113056. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  113057. int iToken; /* Used to iterate through phrase tokens */
  113058. char *aPoslist = 0; /* Position list for deferred tokens */
  113059. int nPoslist = 0; /* Number of bytes in aPoslist */
  113060. int iPrev = -1; /* Token number of previous deferred token */
  113061. assert( pPhrase->doclist.bFreeList==0 );
  113062. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  113063. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  113064. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  113065. if( pDeferred ){
  113066. char *pList;
  113067. int nList;
  113068. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  113069. if( rc!=SQLITE_OK ) return rc;
  113070. if( pList==0 ){
  113071. sqlite3_free(aPoslist);
  113072. pPhrase->doclist.pList = 0;
  113073. pPhrase->doclist.nList = 0;
  113074. return SQLITE_OK;
  113075. }else if( aPoslist==0 ){
  113076. aPoslist = pList;
  113077. nPoslist = nList;
  113078. }else{
  113079. char *aOut = pList;
  113080. char *p1 = aPoslist;
  113081. char *p2 = aOut;
  113082. assert( iPrev>=0 );
  113083. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  113084. sqlite3_free(aPoslist);
  113085. aPoslist = pList;
  113086. nPoslist = (int)(aOut - aPoslist);
  113087. if( nPoslist==0 ){
  113088. sqlite3_free(aPoslist);
  113089. pPhrase->doclist.pList = 0;
  113090. pPhrase->doclist.nList = 0;
  113091. return SQLITE_OK;
  113092. }
  113093. }
  113094. iPrev = iToken;
  113095. }
  113096. }
  113097. if( iPrev>=0 ){
  113098. int nMaxUndeferred = pPhrase->iDoclistToken;
  113099. if( nMaxUndeferred<0 ){
  113100. pPhrase->doclist.pList = aPoslist;
  113101. pPhrase->doclist.nList = nPoslist;
  113102. pPhrase->doclist.iDocid = pCsr->iPrevId;
  113103. pPhrase->doclist.bFreeList = 1;
  113104. }else{
  113105. int nDistance;
  113106. char *p1;
  113107. char *p2;
  113108. char *aOut;
  113109. if( nMaxUndeferred>iPrev ){
  113110. p1 = aPoslist;
  113111. p2 = pPhrase->doclist.pList;
  113112. nDistance = nMaxUndeferred - iPrev;
  113113. }else{
  113114. p1 = pPhrase->doclist.pList;
  113115. p2 = aPoslist;
  113116. nDistance = iPrev - nMaxUndeferred;
  113117. }
  113118. aOut = (char *)sqlite3_malloc(nPoslist+8);
  113119. if( !aOut ){
  113120. sqlite3_free(aPoslist);
  113121. return SQLITE_NOMEM;
  113122. }
  113123. pPhrase->doclist.pList = aOut;
  113124. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  113125. pPhrase->doclist.bFreeList = 1;
  113126. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  113127. }else{
  113128. sqlite3_free(aOut);
  113129. pPhrase->doclist.pList = 0;
  113130. pPhrase->doclist.nList = 0;
  113131. }
  113132. sqlite3_free(aPoslist);
  113133. }
  113134. }
  113135. return SQLITE_OK;
  113136. }
  113137. /*
  113138. ** This function is called for each Fts3Phrase in a full-text query
  113139. ** expression to initialize the mechanism for returning rows. Once this
  113140. ** function has been called successfully on an Fts3Phrase, it may be
  113141. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  113142. **
  113143. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  113144. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  113145. ** memory within this call.
  113146. **
  113147. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  113148. */
  113149. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  113150. int rc; /* Error code */
  113151. Fts3PhraseToken *pFirst = &p->aToken[0];
  113152. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113153. if( pCsr->bDesc==pTab->bDescIdx
  113154. && bOptOk==1
  113155. && p->nToken==1
  113156. && pFirst->pSegcsr
  113157. && pFirst->pSegcsr->bLookup
  113158. && pFirst->bFirst==0
  113159. ){
  113160. /* Use the incremental approach. */
  113161. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  113162. rc = sqlite3Fts3MsrIncrStart(
  113163. pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
  113164. p->bIncr = 1;
  113165. }else{
  113166. /* Load the full doclist for the phrase into memory. */
  113167. rc = fts3EvalPhraseLoad(pCsr, p);
  113168. p->bIncr = 0;
  113169. }
  113170. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  113171. return rc;
  113172. }
  113173. /*
  113174. ** This function is used to iterate backwards (from the end to start)
  113175. ** through doclists. It is used by this module to iterate through phrase
  113176. ** doclists in reverse and by the fts3_write.c module to iterate through
  113177. ** pending-terms lists when writing to databases with "order=desc".
  113178. **
  113179. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  113180. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  113181. ** function iterates from the end of the doclist to the beginning.
  113182. */
  113183. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  113184. int bDescIdx, /* True if the doclist is desc */
  113185. char *aDoclist, /* Pointer to entire doclist */
  113186. int nDoclist, /* Length of aDoclist in bytes */
  113187. char **ppIter, /* IN/OUT: Iterator pointer */
  113188. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  113189. int *pnList, /* OUT: List length pointer */
  113190. u8 *pbEof /* OUT: End-of-file flag */
  113191. ){
  113192. char *p = *ppIter;
  113193. assert( nDoclist>0 );
  113194. assert( *pbEof==0 );
  113195. assert( p || *piDocid==0 );
  113196. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  113197. if( p==0 ){
  113198. sqlite3_int64 iDocid = 0;
  113199. char *pNext = 0;
  113200. char *pDocid = aDoclist;
  113201. char *pEnd = &aDoclist[nDoclist];
  113202. int iMul = 1;
  113203. while( pDocid<pEnd ){
  113204. sqlite3_int64 iDelta;
  113205. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  113206. iDocid += (iMul * iDelta);
  113207. pNext = pDocid;
  113208. fts3PoslistCopy(0, &pDocid);
  113209. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  113210. iMul = (bDescIdx ? -1 : 1);
  113211. }
  113212. *pnList = (int)(pEnd - pNext);
  113213. *ppIter = pNext;
  113214. *piDocid = iDocid;
  113215. }else{
  113216. int iMul = (bDescIdx ? -1 : 1);
  113217. sqlite3_int64 iDelta;
  113218. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  113219. *piDocid -= (iMul * iDelta);
  113220. if( p==aDoclist ){
  113221. *pbEof = 1;
  113222. }else{
  113223. char *pSave = p;
  113224. fts3ReversePoslist(aDoclist, &p);
  113225. *pnList = (int)(pSave - p);
  113226. }
  113227. *ppIter = p;
  113228. }
  113229. }
  113230. /*
  113231. ** Iterate forwards through a doclist.
  113232. */
  113233. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  113234. int bDescIdx, /* True if the doclist is desc */
  113235. char *aDoclist, /* Pointer to entire doclist */
  113236. int nDoclist, /* Length of aDoclist in bytes */
  113237. char **ppIter, /* IN/OUT: Iterator pointer */
  113238. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  113239. u8 *pbEof /* OUT: End-of-file flag */
  113240. ){
  113241. char *p = *ppIter;
  113242. assert( nDoclist>0 );
  113243. assert( *pbEof==0 );
  113244. assert( p || *piDocid==0 );
  113245. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  113246. if( p==0 ){
  113247. p = aDoclist;
  113248. p += sqlite3Fts3GetVarint(p, piDocid);
  113249. }else{
  113250. fts3PoslistCopy(0, &p);
  113251. if( p>=&aDoclist[nDoclist] ){
  113252. *pbEof = 1;
  113253. }else{
  113254. sqlite3_int64 iVar;
  113255. p += sqlite3Fts3GetVarint(p, &iVar);
  113256. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  113257. }
  113258. }
  113259. *ppIter = p;
  113260. }
  113261. /*
  113262. ** Attempt to move the phrase iterator to point to the next matching docid.
  113263. ** If an error occurs, return an SQLite error code. Otherwise, return
  113264. ** SQLITE_OK.
  113265. **
  113266. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  113267. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  113268. ** successfully advanced, *pbEof is set to 0.
  113269. */
  113270. static int fts3EvalPhraseNext(
  113271. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113272. Fts3Phrase *p, /* Phrase object to advance to next docid */
  113273. u8 *pbEof /* OUT: Set to 1 if EOF */
  113274. ){
  113275. int rc = SQLITE_OK;
  113276. Fts3Doclist *pDL = &p->doclist;
  113277. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113278. if( p->bIncr ){
  113279. assert( p->nToken==1 );
  113280. assert( pDL->pNextDocid==0 );
  113281. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  113282. &pDL->iDocid, &pDL->pList, &pDL->nList
  113283. );
  113284. if( rc==SQLITE_OK && !pDL->pList ){
  113285. *pbEof = 1;
  113286. }
  113287. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  113288. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  113289. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  113290. );
  113291. pDL->pList = pDL->pNextDocid;
  113292. }else{
  113293. char *pIter; /* Used to iterate through aAll */
  113294. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  113295. if( pDL->pNextDocid ){
  113296. pIter = pDL->pNextDocid;
  113297. }else{
  113298. pIter = pDL->aAll;
  113299. }
  113300. if( pIter>=pEnd ){
  113301. /* We have already reached the end of this doclist. EOF. */
  113302. *pbEof = 1;
  113303. }else{
  113304. sqlite3_int64 iDelta;
  113305. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  113306. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  113307. pDL->iDocid += iDelta;
  113308. }else{
  113309. pDL->iDocid -= iDelta;
  113310. }
  113311. pDL->pList = pIter;
  113312. fts3PoslistCopy(0, &pIter);
  113313. pDL->nList = (int)(pIter - pDL->pList);
  113314. /* pIter now points just past the 0x00 that terminates the position-
  113315. ** list for document pDL->iDocid. However, if this position-list was
  113316. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  113317. ** point to the start of the next docid value. The following line deals
  113318. ** with this case by advancing pIter past the zero-padding added by
  113319. ** fts3EvalNearTrim(). */
  113320. while( pIter<pEnd && *pIter==0 ) pIter++;
  113321. pDL->pNextDocid = pIter;
  113322. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  113323. *pbEof = 0;
  113324. }
  113325. }
  113326. return rc;
  113327. }
  113328. /*
  113329. **
  113330. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  113331. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  113332. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  113333. ** expressions for which all descendent tokens are deferred.
  113334. **
  113335. ** If parameter bOptOk is zero, then it is guaranteed that the
  113336. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  113337. ** each phrase in the expression (subject to deferred token processing).
  113338. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  113339. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  113340. **
  113341. ** If an error occurs within this function, *pRc is set to an SQLite error
  113342. ** code before returning.
  113343. */
  113344. static void fts3EvalStartReaders(
  113345. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113346. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  113347. int bOptOk, /* True to enable incremental loading */
  113348. int *pRc /* IN/OUT: Error code */
  113349. ){
  113350. if( pExpr && SQLITE_OK==*pRc ){
  113351. if( pExpr->eType==FTSQUERY_PHRASE ){
  113352. int i;
  113353. int nToken = pExpr->pPhrase->nToken;
  113354. for(i=0; i<nToken; i++){
  113355. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  113356. }
  113357. pExpr->bDeferred = (i==nToken);
  113358. *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
  113359. }else{
  113360. fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
  113361. fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
  113362. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  113363. }
  113364. }
  113365. }
  113366. /*
  113367. ** An array of the following structures is assembled as part of the process
  113368. ** of selecting tokens to defer before the query starts executing (as part
  113369. ** of the xFilter() method). There is one element in the array for each
  113370. ** token in the FTS expression.
  113371. **
  113372. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  113373. ** to phrases that are connected only by AND and NEAR operators (not OR or
  113374. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  113375. ** separately. The root of a tokens AND/NEAR cluster is stored in
  113376. ** Fts3TokenAndCost.pRoot.
  113377. */
  113378. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  113379. struct Fts3TokenAndCost {
  113380. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  113381. int iToken; /* Position of token in phrase */
  113382. Fts3PhraseToken *pToken; /* The token itself */
  113383. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  113384. int nOvfl; /* Number of overflow pages to load doclist */
  113385. int iCol; /* The column the token must match */
  113386. };
  113387. /*
  113388. ** This function is used to populate an allocated Fts3TokenAndCost array.
  113389. **
  113390. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  113391. ** Otherwise, if an error occurs during execution, *pRc is set to an
  113392. ** SQLite error code.
  113393. */
  113394. static void fts3EvalTokenCosts(
  113395. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113396. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  113397. Fts3Expr *pExpr, /* Expression to consider */
  113398. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  113399. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  113400. int *pRc /* IN/OUT: Error code */
  113401. ){
  113402. if( *pRc==SQLITE_OK ){
  113403. if( pExpr->eType==FTSQUERY_PHRASE ){
  113404. Fts3Phrase *pPhrase = pExpr->pPhrase;
  113405. int i;
  113406. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  113407. Fts3TokenAndCost *pTC = (*ppTC)++;
  113408. pTC->pPhrase = pPhrase;
  113409. pTC->iToken = i;
  113410. pTC->pRoot = pRoot;
  113411. pTC->pToken = &pPhrase->aToken[i];
  113412. pTC->iCol = pPhrase->iColumn;
  113413. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  113414. }
  113415. }else if( pExpr->eType!=FTSQUERY_NOT ){
  113416. assert( pExpr->eType==FTSQUERY_OR
  113417. || pExpr->eType==FTSQUERY_AND
  113418. || pExpr->eType==FTSQUERY_NEAR
  113419. );
  113420. assert( pExpr->pLeft && pExpr->pRight );
  113421. if( pExpr->eType==FTSQUERY_OR ){
  113422. pRoot = pExpr->pLeft;
  113423. **ppOr = pRoot;
  113424. (*ppOr)++;
  113425. }
  113426. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  113427. if( pExpr->eType==FTSQUERY_OR ){
  113428. pRoot = pExpr->pRight;
  113429. **ppOr = pRoot;
  113430. (*ppOr)++;
  113431. }
  113432. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  113433. }
  113434. }
  113435. }
  113436. /*
  113437. ** Determine the average document (row) size in pages. If successful,
  113438. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  113439. ** an SQLite error code.
  113440. **
  113441. ** The average document size in pages is calculated by first calculating
  113442. ** determining the average size in bytes, B. If B is less than the amount
  113443. ** of data that will fit on a single leaf page of an intkey table in
  113444. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  113445. ** the number of overflow pages consumed by a record B bytes in size.
  113446. */
  113447. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  113448. if( pCsr->nRowAvg==0 ){
  113449. /* The average document size, which is required to calculate the cost
  113450. ** of each doclist, has not yet been determined. Read the required
  113451. ** data from the %_stat table to calculate it.
  113452. **
  113453. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  113454. ** varints, where nCol is the number of columns in the FTS3 table.
  113455. ** The first varint is the number of documents currently stored in
  113456. ** the table. The following nCol varints contain the total amount of
  113457. ** data stored in all rows of each column of the table, from left
  113458. ** to right.
  113459. */
  113460. int rc;
  113461. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  113462. sqlite3_stmt *pStmt;
  113463. sqlite3_int64 nDoc = 0;
  113464. sqlite3_int64 nByte = 0;
  113465. const char *pEnd;
  113466. const char *a;
  113467. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  113468. if( rc!=SQLITE_OK ) return rc;
  113469. a = sqlite3_column_blob(pStmt, 0);
  113470. assert( a );
  113471. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  113472. a += sqlite3Fts3GetVarint(a, &nDoc);
  113473. while( a<pEnd ){
  113474. a += sqlite3Fts3GetVarint(a, &nByte);
  113475. }
  113476. if( nDoc==0 || nByte==0 ){
  113477. sqlite3_reset(pStmt);
  113478. return FTS_CORRUPT_VTAB;
  113479. }
  113480. pCsr->nDoc = nDoc;
  113481. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  113482. assert( pCsr->nRowAvg>0 );
  113483. rc = sqlite3_reset(pStmt);
  113484. if( rc!=SQLITE_OK ) return rc;
  113485. }
  113486. *pnPage = pCsr->nRowAvg;
  113487. return SQLITE_OK;
  113488. }
  113489. /*
  113490. ** This function is called to select the tokens (if any) that will be
  113491. ** deferred. The array aTC[] has already been populated when this is
  113492. ** called.
  113493. **
  113494. ** This function is called once for each AND/NEAR cluster in the
  113495. ** expression. Each invocation determines which tokens to defer within
  113496. ** the cluster with root node pRoot. See comments above the definition
  113497. ** of struct Fts3TokenAndCost for more details.
  113498. **
  113499. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  113500. ** called on each token to defer. Otherwise, an SQLite error code is
  113501. ** returned.
  113502. */
  113503. static int fts3EvalSelectDeferred(
  113504. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113505. Fts3Expr *pRoot, /* Consider tokens with this root node */
  113506. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  113507. int nTC /* Number of entries in aTC[] */
  113508. ){
  113509. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113510. int nDocSize = 0; /* Number of pages per doc loaded */
  113511. int rc = SQLITE_OK; /* Return code */
  113512. int ii; /* Iterator variable for various purposes */
  113513. int nOvfl = 0; /* Total overflow pages used by doclists */
  113514. int nToken = 0; /* Total number of tokens in cluster */
  113515. int nMinEst = 0; /* The minimum count for any phrase so far. */
  113516. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  113517. /* Tokens are never deferred for FTS tables created using the content=xxx
  113518. ** option. The reason being that it is not guaranteed that the content
  113519. ** table actually contains the same data as the index. To prevent this from
  113520. ** causing any problems, the deferred token optimization is completely
  113521. ** disabled for content=xxx tables. */
  113522. if( pTab->zContentTbl ){
  113523. return SQLITE_OK;
  113524. }
  113525. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  113526. ** associated with the tokens spill onto overflow pages, or if there is
  113527. ** only 1 token, exit early. No tokens to defer in this case. */
  113528. for(ii=0; ii<nTC; ii++){
  113529. if( aTC[ii].pRoot==pRoot ){
  113530. nOvfl += aTC[ii].nOvfl;
  113531. nToken++;
  113532. }
  113533. }
  113534. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  113535. /* Obtain the average docsize (in pages). */
  113536. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  113537. assert( rc!=SQLITE_OK || nDocSize>0 );
  113538. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  113539. ** of the number of overflow pages that will be loaded by the pager layer
  113540. ** to retrieve the entire doclist for the token from the full-text index.
  113541. ** Load the doclists for tokens that are either:
  113542. **
  113543. ** a. The cheapest token in the entire query (i.e. the one visited by the
  113544. ** first iteration of this loop), or
  113545. **
  113546. ** b. Part of a multi-token phrase.
  113547. **
  113548. ** After each token doclist is loaded, merge it with the others from the
  113549. ** same phrase and count the number of documents that the merged doclist
  113550. ** contains. Set variable "nMinEst" to the smallest number of documents in
  113551. ** any phrase doclist for which 1 or more token doclists have been loaded.
  113552. ** Let nOther be the number of other phrases for which it is certain that
  113553. ** one or more tokens will not be deferred.
  113554. **
  113555. ** Then, for each token, defer it if loading the doclist would result in
  113556. ** loading N or more overflow pages into memory, where N is computed as:
  113557. **
  113558. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  113559. */
  113560. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  113561. int iTC; /* Used to iterate through aTC[] array. */
  113562. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  113563. /* Set pTC to point to the cheapest remaining token. */
  113564. for(iTC=0; iTC<nTC; iTC++){
  113565. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  113566. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  113567. ){
  113568. pTC = &aTC[iTC];
  113569. }
  113570. }
  113571. assert( pTC );
  113572. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  113573. /* The number of overflow pages to load for this (and therefore all
  113574. ** subsequent) tokens is greater than the estimated number of pages
  113575. ** that will be loaded if all subsequent tokens are deferred.
  113576. */
  113577. Fts3PhraseToken *pToken = pTC->pToken;
  113578. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  113579. fts3SegReaderCursorFree(pToken->pSegcsr);
  113580. pToken->pSegcsr = 0;
  113581. }else{
  113582. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  113583. ** for-loop. Except, limit the value to 2^24 to prevent it from
  113584. ** overflowing the 32-bit integer it is stored in. */
  113585. if( ii<12 ) nLoad4 = nLoad4*4;
  113586. if( ii==0 || pTC->pPhrase->nToken>1 ){
  113587. /* Either this is the cheapest token in the entire query, or it is
  113588. ** part of a multi-token phrase. Either way, the entire doclist will
  113589. ** (eventually) be loaded into memory. It may as well be now. */
  113590. Fts3PhraseToken *pToken = pTC->pToken;
  113591. int nList = 0;
  113592. char *pList = 0;
  113593. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  113594. assert( rc==SQLITE_OK || pList==0 );
  113595. if( rc==SQLITE_OK ){
  113596. int nCount;
  113597. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  113598. nCount = fts3DoclistCountDocids(
  113599. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  113600. );
  113601. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  113602. }
  113603. }
  113604. }
  113605. pTC->pToken = 0;
  113606. }
  113607. return rc;
  113608. }
  113609. /*
  113610. ** This function is called from within the xFilter method. It initializes
  113611. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  113612. ** the results of a query, the caller does:
  113613. **
  113614. ** fts3EvalStart(pCsr);
  113615. ** while( 1 ){
  113616. ** fts3EvalNext(pCsr);
  113617. ** if( pCsr->bEof ) break;
  113618. ** ... return row pCsr->iPrevId to the caller ...
  113619. ** }
  113620. */
  113621. static int fts3EvalStart(Fts3Cursor *pCsr){
  113622. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113623. int rc = SQLITE_OK;
  113624. int nToken = 0;
  113625. int nOr = 0;
  113626. /* Allocate a MultiSegReader for each token in the expression. */
  113627. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  113628. /* Determine which, if any, tokens in the expression should be deferred. */
  113629. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  113630. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  113631. Fts3TokenAndCost *aTC;
  113632. Fts3Expr **apOr;
  113633. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  113634. sizeof(Fts3TokenAndCost) * nToken
  113635. + sizeof(Fts3Expr *) * nOr * 2
  113636. );
  113637. apOr = (Fts3Expr **)&aTC[nToken];
  113638. if( !aTC ){
  113639. rc = SQLITE_NOMEM;
  113640. }else{
  113641. int ii;
  113642. Fts3TokenAndCost *pTC = aTC;
  113643. Fts3Expr **ppOr = apOr;
  113644. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  113645. nToken = (int)(pTC-aTC);
  113646. nOr = (int)(ppOr-apOr);
  113647. if( rc==SQLITE_OK ){
  113648. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  113649. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  113650. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  113651. }
  113652. }
  113653. sqlite3_free(aTC);
  113654. }
  113655. }
  113656. #endif
  113657. fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
  113658. return rc;
  113659. }
  113660. /*
  113661. ** Invalidate the current position list for phrase pPhrase.
  113662. */
  113663. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  113664. if( pPhrase->doclist.bFreeList ){
  113665. sqlite3_free(pPhrase->doclist.pList);
  113666. }
  113667. pPhrase->doclist.pList = 0;
  113668. pPhrase->doclist.nList = 0;
  113669. pPhrase->doclist.bFreeList = 0;
  113670. }
  113671. /*
  113672. ** This function is called to edit the position list associated with
  113673. ** the phrase object passed as the fifth argument according to a NEAR
  113674. ** condition. For example:
  113675. **
  113676. ** abc NEAR/5 "def ghi"
  113677. **
  113678. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  113679. ** the example above). When this function is called, *paPoslist points to
  113680. ** the position list, and *pnToken is the number of phrase tokens in, the
  113681. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  113682. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  113683. ** the position list associated with phrase "abc".
  113684. **
  113685. ** All positions in the pPhrase position list that are not sufficiently
  113686. ** close to a position in the *paPoslist position list are removed. If this
  113687. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  113688. **
  113689. ** Before returning, *paPoslist is set to point to the position lsit
  113690. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  113691. ** pPhrase.
  113692. */
  113693. static int fts3EvalNearTrim(
  113694. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  113695. char *aTmp, /* Temporary space to use */
  113696. char **paPoslist, /* IN/OUT: Position list */
  113697. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  113698. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  113699. ){
  113700. int nParam1 = nNear + pPhrase->nToken;
  113701. int nParam2 = nNear + *pnToken;
  113702. int nNew;
  113703. char *p2;
  113704. char *pOut;
  113705. int res;
  113706. assert( pPhrase->doclist.pList );
  113707. p2 = pOut = pPhrase->doclist.pList;
  113708. res = fts3PoslistNearMerge(
  113709. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  113710. );
  113711. if( res ){
  113712. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  113713. assert( pPhrase->doclist.pList[nNew]=='\0' );
  113714. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  113715. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  113716. pPhrase->doclist.nList = nNew;
  113717. *paPoslist = pPhrase->doclist.pList;
  113718. *pnToken = pPhrase->nToken;
  113719. }
  113720. return res;
  113721. }
  113722. /*
  113723. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  113724. ** Otherwise, it advances the expression passed as the second argument to
  113725. ** point to the next matching row in the database. Expressions iterate through
  113726. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  113727. ** or descending if it is non-zero.
  113728. **
  113729. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  113730. ** successful, the following variables in pExpr are set:
  113731. **
  113732. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  113733. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  113734. **
  113735. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  113736. ** at EOF, then the following variables are populated with the position list
  113737. ** for the phrase for the visited row:
  113738. **
  113739. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  113740. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  113741. **
  113742. ** It says above that this function advances the expression to the next
  113743. ** matching row. This is usually true, but there are the following exceptions:
  113744. **
  113745. ** 1. Deferred tokens are not taken into account. If a phrase consists
  113746. ** entirely of deferred tokens, it is assumed to match every row in
  113747. ** the db. In this case the position-list is not populated at all.
  113748. **
  113749. ** Or, if a phrase contains one or more deferred tokens and one or
  113750. ** more non-deferred tokens, then the expression is advanced to the
  113751. ** next possible match, considering only non-deferred tokens. In other
  113752. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  113753. ** is advanced to the next row that contains an instance of "A * C",
  113754. ** where "*" may match any single token. The position list in this case
  113755. ** is populated as for "A * C" before returning.
  113756. **
  113757. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  113758. ** advanced to point to the next row that matches "x AND y".
  113759. **
  113760. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  113761. ** really a match, taking into account deferred tokens and NEAR operators.
  113762. */
  113763. static void fts3EvalNextRow(
  113764. Fts3Cursor *pCsr, /* FTS Cursor handle */
  113765. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  113766. int *pRc /* IN/OUT: Error code */
  113767. ){
  113768. if( *pRc==SQLITE_OK ){
  113769. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  113770. assert( pExpr->bEof==0 );
  113771. pExpr->bStart = 1;
  113772. switch( pExpr->eType ){
  113773. case FTSQUERY_NEAR:
  113774. case FTSQUERY_AND: {
  113775. Fts3Expr *pLeft = pExpr->pLeft;
  113776. Fts3Expr *pRight = pExpr->pRight;
  113777. assert( !pLeft->bDeferred || !pRight->bDeferred );
  113778. if( pLeft->bDeferred ){
  113779. /* LHS is entirely deferred. So we assume it matches every row.
  113780. ** Advance the RHS iterator to find the next row visited. */
  113781. fts3EvalNextRow(pCsr, pRight, pRc);
  113782. pExpr->iDocid = pRight->iDocid;
  113783. pExpr->bEof = pRight->bEof;
  113784. }else if( pRight->bDeferred ){
  113785. /* RHS is entirely deferred. So we assume it matches every row.
  113786. ** Advance the LHS iterator to find the next row visited. */
  113787. fts3EvalNextRow(pCsr, pLeft, pRc);
  113788. pExpr->iDocid = pLeft->iDocid;
  113789. pExpr->bEof = pLeft->bEof;
  113790. }else{
  113791. /* Neither the RHS or LHS are deferred. */
  113792. fts3EvalNextRow(pCsr, pLeft, pRc);
  113793. fts3EvalNextRow(pCsr, pRight, pRc);
  113794. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  113795. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  113796. if( iDiff==0 ) break;
  113797. if( iDiff<0 ){
  113798. fts3EvalNextRow(pCsr, pLeft, pRc);
  113799. }else{
  113800. fts3EvalNextRow(pCsr, pRight, pRc);
  113801. }
  113802. }
  113803. pExpr->iDocid = pLeft->iDocid;
  113804. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  113805. }
  113806. break;
  113807. }
  113808. case FTSQUERY_OR: {
  113809. Fts3Expr *pLeft = pExpr->pLeft;
  113810. Fts3Expr *pRight = pExpr->pRight;
  113811. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  113812. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  113813. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  113814. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  113815. fts3EvalNextRow(pCsr, pLeft, pRc);
  113816. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  113817. fts3EvalNextRow(pCsr, pRight, pRc);
  113818. }else{
  113819. fts3EvalNextRow(pCsr, pLeft, pRc);
  113820. fts3EvalNextRow(pCsr, pRight, pRc);
  113821. }
  113822. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  113823. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  113824. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  113825. pExpr->iDocid = pLeft->iDocid;
  113826. }else{
  113827. pExpr->iDocid = pRight->iDocid;
  113828. }
  113829. break;
  113830. }
  113831. case FTSQUERY_NOT: {
  113832. Fts3Expr *pLeft = pExpr->pLeft;
  113833. Fts3Expr *pRight = pExpr->pRight;
  113834. if( pRight->bStart==0 ){
  113835. fts3EvalNextRow(pCsr, pRight, pRc);
  113836. assert( *pRc!=SQLITE_OK || pRight->bStart );
  113837. }
  113838. fts3EvalNextRow(pCsr, pLeft, pRc);
  113839. if( pLeft->bEof==0 ){
  113840. while( !*pRc
  113841. && !pRight->bEof
  113842. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  113843. ){
  113844. fts3EvalNextRow(pCsr, pRight, pRc);
  113845. }
  113846. }
  113847. pExpr->iDocid = pLeft->iDocid;
  113848. pExpr->bEof = pLeft->bEof;
  113849. break;
  113850. }
  113851. default: {
  113852. Fts3Phrase *pPhrase = pExpr->pPhrase;
  113853. fts3EvalInvalidatePoslist(pPhrase);
  113854. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  113855. pExpr->iDocid = pPhrase->doclist.iDocid;
  113856. break;
  113857. }
  113858. }
  113859. }
  113860. }
  113861. /*
  113862. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  113863. ** cluster, then this function returns 1 immediately.
  113864. **
  113865. ** Otherwise, it checks if the current row really does match the NEAR
  113866. ** expression, using the data currently stored in the position lists
  113867. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  113868. **
  113869. ** If the current row is a match, the position list associated with each
  113870. ** phrase in the NEAR expression is edited in place to contain only those
  113871. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  113872. ** constraints. In this case it returns 1. If the NEAR expression does not
  113873. ** match the current row, 0 is returned. The position lists may or may not
  113874. ** be edited if 0 is returned.
  113875. */
  113876. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  113877. int res = 1;
  113878. /* The following block runs if pExpr is the root of a NEAR query.
  113879. ** For example, the query:
  113880. **
  113881. ** "w" NEAR "x" NEAR "y" NEAR "z"
  113882. **
  113883. ** which is represented in tree form as:
  113884. **
  113885. ** |
  113886. ** +--NEAR--+ <-- root of NEAR query
  113887. ** | |
  113888. ** +--NEAR--+ "z"
  113889. ** | |
  113890. ** +--NEAR--+ "y"
  113891. ** | |
  113892. ** "w" "x"
  113893. **
  113894. ** The right-hand child of a NEAR node is always a phrase. The
  113895. ** left-hand child may be either a phrase or a NEAR node. There are
  113896. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  113897. */
  113898. if( *pRc==SQLITE_OK
  113899. && pExpr->eType==FTSQUERY_NEAR
  113900. && pExpr->bEof==0
  113901. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  113902. ){
  113903. Fts3Expr *p;
  113904. int nTmp = 0; /* Bytes of temp space */
  113905. char *aTmp; /* Temp space for PoslistNearMerge() */
  113906. /* Allocate temporary working space. */
  113907. for(p=pExpr; p->pLeft; p=p->pLeft){
  113908. nTmp += p->pRight->pPhrase->doclist.nList;
  113909. }
  113910. nTmp += p->pPhrase->doclist.nList;
  113911. if( nTmp==0 ){
  113912. res = 0;
  113913. }else{
  113914. aTmp = sqlite3_malloc(nTmp*2);
  113915. if( !aTmp ){
  113916. *pRc = SQLITE_NOMEM;
  113917. res = 0;
  113918. }else{
  113919. char *aPoslist = p->pPhrase->doclist.pList;
  113920. int nToken = p->pPhrase->nToken;
  113921. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  113922. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  113923. int nNear = p->nNear;
  113924. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  113925. }
  113926. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  113927. nToken = pExpr->pRight->pPhrase->nToken;
  113928. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  113929. int nNear;
  113930. Fts3Phrase *pPhrase;
  113931. assert( p->pParent && p->pParent->pLeft==p );
  113932. nNear = p->pParent->nNear;
  113933. pPhrase = (
  113934. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  113935. );
  113936. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  113937. }
  113938. }
  113939. sqlite3_free(aTmp);
  113940. }
  113941. }
  113942. return res;
  113943. }
  113944. /*
  113945. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  113946. ** Assuming no error occurs or has occurred, It returns non-zero if the
  113947. ** expression passed as the second argument matches the row that pCsr
  113948. ** currently points to, or zero if it does not.
  113949. **
  113950. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  113951. ** If an error occurs during execution of this function, *pRc is set to
  113952. ** the appropriate SQLite error code. In this case the returned value is
  113953. ** undefined.
  113954. */
  113955. static int fts3EvalTestExpr(
  113956. Fts3Cursor *pCsr, /* FTS cursor handle */
  113957. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  113958. int *pRc /* IN/OUT: Error code */
  113959. ){
  113960. int bHit = 1; /* Return value */
  113961. if( *pRc==SQLITE_OK ){
  113962. switch( pExpr->eType ){
  113963. case FTSQUERY_NEAR:
  113964. case FTSQUERY_AND:
  113965. bHit = (
  113966. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  113967. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  113968. && fts3EvalNearTest(pExpr, pRc)
  113969. );
  113970. /* If the NEAR expression does not match any rows, zero the doclist for
  113971. ** all phrases involved in the NEAR. This is because the snippet(),
  113972. ** offsets() and matchinfo() functions are not supposed to recognize
  113973. ** any instances of phrases that are part of unmatched NEAR queries.
  113974. ** For example if this expression:
  113975. **
  113976. ** ... MATCH 'a OR (b NEAR c)'
  113977. **
  113978. ** is matched against a row containing:
  113979. **
  113980. ** 'a b d e'
  113981. **
  113982. ** then any snippet() should ony highlight the "a" term, not the "b"
  113983. ** (as "b" is part of a non-matching NEAR clause).
  113984. */
  113985. if( bHit==0
  113986. && pExpr->eType==FTSQUERY_NEAR
  113987. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  113988. ){
  113989. Fts3Expr *p;
  113990. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  113991. if( p->pRight->iDocid==pCsr->iPrevId ){
  113992. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  113993. }
  113994. }
  113995. if( p->iDocid==pCsr->iPrevId ){
  113996. fts3EvalInvalidatePoslist(p->pPhrase);
  113997. }
  113998. }
  113999. break;
  114000. case FTSQUERY_OR: {
  114001. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  114002. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  114003. bHit = bHit1 || bHit2;
  114004. break;
  114005. }
  114006. case FTSQUERY_NOT:
  114007. bHit = (
  114008. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  114009. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  114010. );
  114011. break;
  114012. default: {
  114013. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  114014. if( pCsr->pDeferred
  114015. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  114016. ){
  114017. Fts3Phrase *pPhrase = pExpr->pPhrase;
  114018. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  114019. if( pExpr->bDeferred ){
  114020. fts3EvalInvalidatePoslist(pPhrase);
  114021. }
  114022. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  114023. bHit = (pPhrase->doclist.pList!=0);
  114024. pExpr->iDocid = pCsr->iPrevId;
  114025. }else
  114026. #endif
  114027. {
  114028. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  114029. }
  114030. break;
  114031. }
  114032. }
  114033. }
  114034. return bHit;
  114035. }
  114036. /*
  114037. ** This function is called as the second part of each xNext operation when
  114038. ** iterating through the results of a full-text query. At this point the
  114039. ** cursor points to a row that matches the query expression, with the
  114040. ** following caveats:
  114041. **
  114042. ** * Up until this point, "NEAR" operators in the expression have been
  114043. ** treated as "AND".
  114044. **
  114045. ** * Deferred tokens have not yet been considered.
  114046. **
  114047. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  114048. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  114049. ** operators and deferred tokens the current row is still a match for the
  114050. ** expression. It returns 1 if both of the following are true:
  114051. **
  114052. ** 1. *pRc is SQLITE_OK when this function returns, and
  114053. **
  114054. ** 2. After scanning the current FTS table row for the deferred tokens,
  114055. ** it is determined that the row does *not* match the query.
  114056. **
  114057. ** Or, if no error occurs and it seems the current row does match the FTS
  114058. ** query, return 0.
  114059. */
  114060. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  114061. int rc = *pRc;
  114062. int bMiss = 0;
  114063. if( rc==SQLITE_OK ){
  114064. /* If there are one or more deferred tokens, load the current row into
  114065. ** memory and scan it to determine the position list for each deferred
  114066. ** token. Then, see if this row is really a match, considering deferred
  114067. ** tokens and NEAR operators (neither of which were taken into account
  114068. ** earlier, by fts3EvalNextRow()).
  114069. */
  114070. if( pCsr->pDeferred ){
  114071. rc = fts3CursorSeek(0, pCsr);
  114072. if( rc==SQLITE_OK ){
  114073. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  114074. }
  114075. }
  114076. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  114077. /* Free the position-lists accumulated for each deferred token above. */
  114078. sqlite3Fts3FreeDeferredDoclists(pCsr);
  114079. *pRc = rc;
  114080. }
  114081. return (rc==SQLITE_OK && bMiss);
  114082. }
  114083. /*
  114084. ** Advance to the next document that matches the FTS expression in
  114085. ** Fts3Cursor.pExpr.
  114086. */
  114087. static int fts3EvalNext(Fts3Cursor *pCsr){
  114088. int rc = SQLITE_OK; /* Return Code */
  114089. Fts3Expr *pExpr = pCsr->pExpr;
  114090. assert( pCsr->isEof==0 );
  114091. if( pExpr==0 ){
  114092. pCsr->isEof = 1;
  114093. }else{
  114094. do {
  114095. if( pCsr->isRequireSeek==0 ){
  114096. sqlite3_reset(pCsr->pStmt);
  114097. }
  114098. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  114099. fts3EvalNextRow(pCsr, pExpr, &rc);
  114100. pCsr->isEof = pExpr->bEof;
  114101. pCsr->isRequireSeek = 1;
  114102. pCsr->isMatchinfoNeeded = 1;
  114103. pCsr->iPrevId = pExpr->iDocid;
  114104. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  114105. }
  114106. return rc;
  114107. }
  114108. /*
  114109. ** Restart interation for expression pExpr so that the next call to
  114110. ** fts3EvalNext() visits the first row. Do not allow incremental
  114111. ** loading or merging of phrase doclists for this iteration.
  114112. **
  114113. ** If *pRc is other than SQLITE_OK when this function is called, it is
  114114. ** a no-op. If an error occurs within this function, *pRc is set to an
  114115. ** SQLite error code before returning.
  114116. */
  114117. static void fts3EvalRestart(
  114118. Fts3Cursor *pCsr,
  114119. Fts3Expr *pExpr,
  114120. int *pRc
  114121. ){
  114122. if( pExpr && *pRc==SQLITE_OK ){
  114123. Fts3Phrase *pPhrase = pExpr->pPhrase;
  114124. if( pPhrase ){
  114125. fts3EvalInvalidatePoslist(pPhrase);
  114126. if( pPhrase->bIncr ){
  114127. assert( pPhrase->nToken==1 );
  114128. assert( pPhrase->aToken[0].pSegcsr );
  114129. sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
  114130. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  114131. }
  114132. pPhrase->doclist.pNextDocid = 0;
  114133. pPhrase->doclist.iDocid = 0;
  114134. }
  114135. pExpr->iDocid = 0;
  114136. pExpr->bEof = 0;
  114137. pExpr->bStart = 0;
  114138. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  114139. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  114140. }
  114141. }
  114142. /*
  114143. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  114144. ** expression rooted at pExpr, the cursor iterates through all rows matched
  114145. ** by pExpr, calling this function for each row. This function increments
  114146. ** the values in Fts3Expr.aMI[] according to the position-list currently
  114147. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  114148. ** expression nodes.
  114149. */
  114150. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  114151. if( pExpr ){
  114152. Fts3Phrase *pPhrase = pExpr->pPhrase;
  114153. if( pPhrase && pPhrase->doclist.pList ){
  114154. int iCol = 0;
  114155. char *p = pPhrase->doclist.pList;
  114156. assert( *p );
  114157. while( 1 ){
  114158. u8 c = 0;
  114159. int iCnt = 0;
  114160. while( 0xFE & (*p | c) ){
  114161. if( (c&0x80)==0 ) iCnt++;
  114162. c = *p++ & 0x80;
  114163. }
  114164. /* aMI[iCol*3 + 1] = Number of occurrences
  114165. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  114166. */
  114167. pExpr->aMI[iCol*3 + 1] += iCnt;
  114168. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  114169. if( *p==0x00 ) break;
  114170. p++;
  114171. p += sqlite3Fts3GetVarint32(p, &iCol);
  114172. }
  114173. }
  114174. fts3EvalUpdateCounts(pExpr->pLeft);
  114175. fts3EvalUpdateCounts(pExpr->pRight);
  114176. }
  114177. }
  114178. /*
  114179. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  114180. **
  114181. ** If it is not already allocated and populated, this function allocates and
  114182. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  114183. ** of a NEAR expression, then it also allocates and populates the same array
  114184. ** for all other phrases that are part of the NEAR expression.
  114185. **
  114186. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  114187. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  114188. */
  114189. static int fts3EvalGatherStats(
  114190. Fts3Cursor *pCsr, /* Cursor object */
  114191. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  114192. ){
  114193. int rc = SQLITE_OK; /* Return code */
  114194. assert( pExpr->eType==FTSQUERY_PHRASE );
  114195. if( pExpr->aMI==0 ){
  114196. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  114197. Fts3Expr *pRoot; /* Root of NEAR expression */
  114198. Fts3Expr *p; /* Iterator used for several purposes */
  114199. sqlite3_int64 iPrevId = pCsr->iPrevId;
  114200. sqlite3_int64 iDocid;
  114201. u8 bEof;
  114202. /* Find the root of the NEAR expression */
  114203. pRoot = pExpr;
  114204. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  114205. pRoot = pRoot->pParent;
  114206. }
  114207. iDocid = pRoot->iDocid;
  114208. bEof = pRoot->bEof;
  114209. assert( pRoot->bStart );
  114210. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  114211. for(p=pRoot; p; p=p->pLeft){
  114212. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  114213. assert( pE->aMI==0 );
  114214. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  114215. if( !pE->aMI ) return SQLITE_NOMEM;
  114216. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  114217. }
  114218. fts3EvalRestart(pCsr, pRoot, &rc);
  114219. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  114220. do {
  114221. /* Ensure the %_content statement is reset. */
  114222. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  114223. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  114224. /* Advance to the next document */
  114225. fts3EvalNextRow(pCsr, pRoot, &rc);
  114226. pCsr->isEof = pRoot->bEof;
  114227. pCsr->isRequireSeek = 1;
  114228. pCsr->isMatchinfoNeeded = 1;
  114229. pCsr->iPrevId = pRoot->iDocid;
  114230. }while( pCsr->isEof==0
  114231. && pRoot->eType==FTSQUERY_NEAR
  114232. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  114233. );
  114234. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  114235. fts3EvalUpdateCounts(pRoot);
  114236. }
  114237. }
  114238. pCsr->isEof = 0;
  114239. pCsr->iPrevId = iPrevId;
  114240. if( bEof ){
  114241. pRoot->bEof = bEof;
  114242. }else{
  114243. /* Caution: pRoot may iterate through docids in ascending or descending
  114244. ** order. For this reason, even though it seems more defensive, the
  114245. ** do loop can not be written:
  114246. **
  114247. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  114248. */
  114249. fts3EvalRestart(pCsr, pRoot, &rc);
  114250. do {
  114251. fts3EvalNextRow(pCsr, pRoot, &rc);
  114252. assert( pRoot->bEof==0 );
  114253. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  114254. fts3EvalTestDeferredAndNear(pCsr, &rc);
  114255. }
  114256. }
  114257. return rc;
  114258. }
  114259. /*
  114260. ** This function is used by the matchinfo() module to query a phrase
  114261. ** expression node for the following information:
  114262. **
  114263. ** 1. The total number of occurrences of the phrase in each column of
  114264. ** the FTS table (considering all rows), and
  114265. **
  114266. ** 2. For each column, the number of rows in the table for which the
  114267. ** column contains at least one instance of the phrase.
  114268. **
  114269. ** If no error occurs, SQLITE_OK is returned and the values for each column
  114270. ** written into the array aiOut as follows:
  114271. **
  114272. ** aiOut[iCol*3 + 1] = Number of occurrences
  114273. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  114274. **
  114275. ** Caveats:
  114276. **
  114277. ** * If a phrase consists entirely of deferred tokens, then all output
  114278. ** values are set to the number of documents in the table. In other
  114279. ** words we assume that very common tokens occur exactly once in each
  114280. ** column of each row of the table.
  114281. **
  114282. ** * If a phrase contains some deferred tokens (and some non-deferred
  114283. ** tokens), count the potential occurrence identified by considering
  114284. ** the non-deferred tokens instead of actual phrase occurrences.
  114285. **
  114286. ** * If the phrase is part of a NEAR expression, then only phrase instances
  114287. ** that meet the NEAR constraint are included in the counts.
  114288. */
  114289. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  114290. Fts3Cursor *pCsr, /* FTS cursor handle */
  114291. Fts3Expr *pExpr, /* Phrase expression */
  114292. u32 *aiOut /* Array to write results into (see above) */
  114293. ){
  114294. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  114295. int rc = SQLITE_OK;
  114296. int iCol;
  114297. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  114298. assert( pCsr->nDoc>0 );
  114299. for(iCol=0; iCol<pTab->nColumn; iCol++){
  114300. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  114301. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  114302. }
  114303. }else{
  114304. rc = fts3EvalGatherStats(pCsr, pExpr);
  114305. if( rc==SQLITE_OK ){
  114306. assert( pExpr->aMI );
  114307. for(iCol=0; iCol<pTab->nColumn; iCol++){
  114308. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  114309. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  114310. }
  114311. }
  114312. }
  114313. return rc;
  114314. }
  114315. /*
  114316. ** The expression pExpr passed as the second argument to this function
  114317. ** must be of type FTSQUERY_PHRASE.
  114318. **
  114319. ** The returned value is either NULL or a pointer to a buffer containing
  114320. ** a position-list indicating the occurrences of the phrase in column iCol
  114321. ** of the current row.
  114322. **
  114323. ** More specifically, the returned buffer contains 1 varint for each
  114324. ** occurence of the phrase in the column, stored using the normal (delta+2)
  114325. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  114326. ** if the requested column contains "a b X c d X X" and the position-list
  114327. ** for 'X' is requested, the buffer returned may contain:
  114328. **
  114329. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  114330. **
  114331. ** This function works regardless of whether or not the phrase is deferred,
  114332. ** incremental, or neither.
  114333. */
  114334. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  114335. Fts3Cursor *pCsr, /* FTS3 cursor object */
  114336. Fts3Expr *pExpr, /* Phrase to return doclist for */
  114337. int iCol, /* Column to return position list for */
  114338. char **ppOut /* OUT: Pointer to position list */
  114339. ){
  114340. Fts3Phrase *pPhrase = pExpr->pPhrase;
  114341. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  114342. char *pIter;
  114343. int iThis;
  114344. sqlite3_int64 iDocid;
  114345. /* If this phrase is applies specifically to some column other than
  114346. ** column iCol, return a NULL pointer. */
  114347. *ppOut = 0;
  114348. assert( iCol>=0 && iCol<pTab->nColumn );
  114349. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  114350. return SQLITE_OK;
  114351. }
  114352. iDocid = pExpr->iDocid;
  114353. pIter = pPhrase->doclist.pList;
  114354. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  114355. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  114356. int bOr = 0;
  114357. u8 bEof = 0;
  114358. Fts3Expr *p;
  114359. /* Check if this phrase descends from an OR expression node. If not,
  114360. ** return NULL. Otherwise, the entry that corresponds to docid
  114361. ** pCsr->iPrevId may lie earlier in the doclist buffer. */
  114362. for(p=pExpr->pParent; p; p=p->pParent){
  114363. if( p->eType==FTSQUERY_OR ) bOr = 1;
  114364. }
  114365. if( bOr==0 ) return SQLITE_OK;
  114366. /* This is the descendent of an OR node. In this case we cannot use
  114367. ** an incremental phrase. Load the entire doclist for the phrase
  114368. ** into memory in this case. */
  114369. if( pPhrase->bIncr ){
  114370. int rc = SQLITE_OK;
  114371. int bEofSave = pExpr->bEof;
  114372. fts3EvalRestart(pCsr, pExpr, &rc);
  114373. while( rc==SQLITE_OK && !pExpr->bEof ){
  114374. fts3EvalNextRow(pCsr, pExpr, &rc);
  114375. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  114376. }
  114377. pIter = pPhrase->doclist.pList;
  114378. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  114379. if( rc!=SQLITE_OK ) return rc;
  114380. }
  114381. if( pExpr->bEof ){
  114382. pIter = 0;
  114383. iDocid = 0;
  114384. }
  114385. bEof = (pPhrase->doclist.nAll==0);
  114386. assert( bDescDoclist==0 || bDescDoclist==1 );
  114387. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  114388. if( pCsr->bDesc==bDescDoclist ){
  114389. int dummy;
  114390. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  114391. sqlite3Fts3DoclistPrev(
  114392. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  114393. &pIter, &iDocid, &dummy, &bEof
  114394. );
  114395. }
  114396. }else{
  114397. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  114398. sqlite3Fts3DoclistNext(
  114399. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  114400. &pIter, &iDocid, &bEof
  114401. );
  114402. }
  114403. }
  114404. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  114405. }
  114406. if( pIter==0 ) return SQLITE_OK;
  114407. if( *pIter==0x01 ){
  114408. pIter++;
  114409. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  114410. }else{
  114411. iThis = 0;
  114412. }
  114413. while( iThis<iCol ){
  114414. fts3ColumnlistCopy(0, &pIter);
  114415. if( *pIter==0x00 ) return 0;
  114416. pIter++;
  114417. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  114418. }
  114419. *ppOut = ((iCol==iThis)?pIter:0);
  114420. return SQLITE_OK;
  114421. }
  114422. /*
  114423. ** Free all components of the Fts3Phrase structure that were allocated by
  114424. ** the eval module. Specifically, this means to free:
  114425. **
  114426. ** * the contents of pPhrase->doclist, and
  114427. ** * any Fts3MultiSegReader objects held by phrase tokens.
  114428. */
  114429. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  114430. if( pPhrase ){
  114431. int i;
  114432. sqlite3_free(pPhrase->doclist.aAll);
  114433. fts3EvalInvalidatePoslist(pPhrase);
  114434. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  114435. for(i=0; i<pPhrase->nToken; i++){
  114436. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  114437. pPhrase->aToken[i].pSegcsr = 0;
  114438. }
  114439. }
  114440. }
  114441. /*
  114442. ** Return SQLITE_CORRUPT_VTAB.
  114443. */
  114444. #ifdef SQLITE_DEBUG
  114445. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  114446. return SQLITE_CORRUPT_VTAB;
  114447. }
  114448. #endif
  114449. #if !SQLITE_CORE
  114450. /*
  114451. ** Initialize API pointer table, if required.
  114452. */
  114453. SQLITE_API int sqlite3_extension_init(
  114454. sqlite3 *db,
  114455. char **pzErrMsg,
  114456. const sqlite3_api_routines *pApi
  114457. ){
  114458. SQLITE_EXTENSION_INIT2(pApi)
  114459. return sqlite3Fts3Init(db);
  114460. }
  114461. #endif
  114462. #endif
  114463. /************** End of fts3.c ************************************************/
  114464. /************** Begin file fts3_aux.c ****************************************/
  114465. /*
  114466. ** 2011 Jan 27
  114467. **
  114468. ** The author disclaims copyright to this source code. In place of
  114469. ** a legal notice, here is a blessing:
  114470. **
  114471. ** May you do good and not evil.
  114472. ** May you find forgiveness for yourself and forgive others.
  114473. ** May you share freely, never taking more than you give.
  114474. **
  114475. ******************************************************************************
  114476. **
  114477. */
  114478. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  114479. /* #include <string.h> */
  114480. /* #include <assert.h> */
  114481. typedef struct Fts3auxTable Fts3auxTable;
  114482. typedef struct Fts3auxCursor Fts3auxCursor;
  114483. struct Fts3auxTable {
  114484. sqlite3_vtab base; /* Base class used by SQLite core */
  114485. Fts3Table *pFts3Tab;
  114486. };
  114487. struct Fts3auxCursor {
  114488. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  114489. Fts3MultiSegReader csr; /* Must be right after "base" */
  114490. Fts3SegFilter filter;
  114491. char *zStop;
  114492. int nStop; /* Byte-length of string zStop */
  114493. int isEof; /* True if cursor is at EOF */
  114494. sqlite3_int64 iRowid; /* Current rowid */
  114495. int iCol; /* Current value of 'col' column */
  114496. int nStat; /* Size of aStat[] array */
  114497. struct Fts3auxColstats {
  114498. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  114499. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  114500. } *aStat;
  114501. };
  114502. /*
  114503. ** Schema of the terms table.
  114504. */
  114505. #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
  114506. /*
  114507. ** This function does all the work for both the xConnect and xCreate methods.
  114508. ** These tables have no persistent representation of their own, so xConnect
  114509. ** and xCreate are identical operations.
  114510. */
  114511. static int fts3auxConnectMethod(
  114512. sqlite3 *db, /* Database connection */
  114513. void *pUnused, /* Unused */
  114514. int argc, /* Number of elements in argv array */
  114515. const char * const *argv, /* xCreate/xConnect argument array */
  114516. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  114517. char **pzErr /* OUT: sqlite3_malloc'd error message */
  114518. ){
  114519. char const *zDb; /* Name of database (e.g. "main") */
  114520. char const *zFts3; /* Name of fts3 table */
  114521. int nDb; /* Result of strlen(zDb) */
  114522. int nFts3; /* Result of strlen(zFts3) */
  114523. int nByte; /* Bytes of space to allocate here */
  114524. int rc; /* value returned by declare_vtab() */
  114525. Fts3auxTable *p; /* Virtual table object to return */
  114526. UNUSED_PARAMETER(pUnused);
  114527. /* The user should specify a single argument - the name of an fts3 table. */
  114528. if( argc!=4 ){
  114529. *pzErr = sqlite3_mprintf(
  114530. "wrong number of arguments to fts4aux constructor"
  114531. );
  114532. return SQLITE_ERROR;
  114533. }
  114534. zDb = argv[1];
  114535. nDb = (int)strlen(zDb);
  114536. zFts3 = argv[3];
  114537. nFts3 = (int)strlen(zFts3);
  114538. rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
  114539. if( rc!=SQLITE_OK ) return rc;
  114540. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  114541. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  114542. if( !p ) return SQLITE_NOMEM;
  114543. memset(p, 0, nByte);
  114544. p->pFts3Tab = (Fts3Table *)&p[1];
  114545. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  114546. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  114547. p->pFts3Tab->db = db;
  114548. p->pFts3Tab->nIndex = 1;
  114549. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  114550. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  114551. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  114552. *ppVtab = (sqlite3_vtab *)p;
  114553. return SQLITE_OK;
  114554. }
  114555. /*
  114556. ** This function does the work for both the xDisconnect and xDestroy methods.
  114557. ** These tables have no persistent representation of their own, so xDisconnect
  114558. ** and xDestroy are identical operations.
  114559. */
  114560. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  114561. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  114562. Fts3Table *pFts3 = p->pFts3Tab;
  114563. int i;
  114564. /* Free any prepared statements held */
  114565. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  114566. sqlite3_finalize(pFts3->aStmt[i]);
  114567. }
  114568. sqlite3_free(pFts3->zSegmentsTbl);
  114569. sqlite3_free(p);
  114570. return SQLITE_OK;
  114571. }
  114572. #define FTS4AUX_EQ_CONSTRAINT 1
  114573. #define FTS4AUX_GE_CONSTRAINT 2
  114574. #define FTS4AUX_LE_CONSTRAINT 4
  114575. /*
  114576. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  114577. */
  114578. static int fts3auxBestIndexMethod(
  114579. sqlite3_vtab *pVTab,
  114580. sqlite3_index_info *pInfo
  114581. ){
  114582. int i;
  114583. int iEq = -1;
  114584. int iGe = -1;
  114585. int iLe = -1;
  114586. UNUSED_PARAMETER(pVTab);
  114587. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  114588. if( pInfo->nOrderBy==1
  114589. && pInfo->aOrderBy[0].iColumn==0
  114590. && pInfo->aOrderBy[0].desc==0
  114591. ){
  114592. pInfo->orderByConsumed = 1;
  114593. }
  114594. /* Search for equality and range constraints on the "term" column. */
  114595. for(i=0; i<pInfo->nConstraint; i++){
  114596. if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
  114597. int op = pInfo->aConstraint[i].op;
  114598. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  114599. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  114600. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  114601. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  114602. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  114603. }
  114604. }
  114605. if( iEq>=0 ){
  114606. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  114607. pInfo->aConstraintUsage[iEq].argvIndex = 1;
  114608. pInfo->estimatedCost = 5;
  114609. }else{
  114610. pInfo->idxNum = 0;
  114611. pInfo->estimatedCost = 20000;
  114612. if( iGe>=0 ){
  114613. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  114614. pInfo->aConstraintUsage[iGe].argvIndex = 1;
  114615. pInfo->estimatedCost /= 2;
  114616. }
  114617. if( iLe>=0 ){
  114618. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  114619. pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
  114620. pInfo->estimatedCost /= 2;
  114621. }
  114622. }
  114623. return SQLITE_OK;
  114624. }
  114625. /*
  114626. ** xOpen - Open a cursor.
  114627. */
  114628. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  114629. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  114630. UNUSED_PARAMETER(pVTab);
  114631. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  114632. if( !pCsr ) return SQLITE_NOMEM;
  114633. memset(pCsr, 0, sizeof(Fts3auxCursor));
  114634. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  114635. return SQLITE_OK;
  114636. }
  114637. /*
  114638. ** xClose - Close a cursor.
  114639. */
  114640. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  114641. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  114642. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  114643. sqlite3Fts3SegmentsClose(pFts3);
  114644. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  114645. sqlite3_free((void *)pCsr->filter.zTerm);
  114646. sqlite3_free(pCsr->zStop);
  114647. sqlite3_free(pCsr->aStat);
  114648. sqlite3_free(pCsr);
  114649. return SQLITE_OK;
  114650. }
  114651. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  114652. if( nSize>pCsr->nStat ){
  114653. struct Fts3auxColstats *aNew;
  114654. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  114655. sizeof(struct Fts3auxColstats) * nSize
  114656. );
  114657. if( aNew==0 ) return SQLITE_NOMEM;
  114658. memset(&aNew[pCsr->nStat], 0,
  114659. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  114660. );
  114661. pCsr->aStat = aNew;
  114662. pCsr->nStat = nSize;
  114663. }
  114664. return SQLITE_OK;
  114665. }
  114666. /*
  114667. ** xNext - Advance the cursor to the next row, if any.
  114668. */
  114669. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  114670. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  114671. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  114672. int rc;
  114673. /* Increment our pretend rowid value. */
  114674. pCsr->iRowid++;
  114675. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  114676. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  114677. }
  114678. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  114679. if( rc==SQLITE_ROW ){
  114680. int i = 0;
  114681. int nDoclist = pCsr->csr.nDoclist;
  114682. char *aDoclist = pCsr->csr.aDoclist;
  114683. int iCol;
  114684. int eState = 0;
  114685. if( pCsr->zStop ){
  114686. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  114687. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  114688. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  114689. pCsr->isEof = 1;
  114690. return SQLITE_OK;
  114691. }
  114692. }
  114693. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  114694. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  114695. iCol = 0;
  114696. while( i<nDoclist ){
  114697. sqlite3_int64 v = 0;
  114698. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  114699. switch( eState ){
  114700. /* State 0. In this state the integer just read was a docid. */
  114701. case 0:
  114702. pCsr->aStat[0].nDoc++;
  114703. eState = 1;
  114704. iCol = 0;
  114705. break;
  114706. /* State 1. In this state we are expecting either a 1, indicating
  114707. ** that the following integer will be a column number, or the
  114708. ** start of a position list for column 0.
  114709. **
  114710. ** The only difference between state 1 and state 2 is that if the
  114711. ** integer encountered in state 1 is not 0 or 1, then we need to
  114712. ** increment the column 0 "nDoc" count for this term.
  114713. */
  114714. case 1:
  114715. assert( iCol==0 );
  114716. if( v>1 ){
  114717. pCsr->aStat[1].nDoc++;
  114718. }
  114719. eState = 2;
  114720. /* fall through */
  114721. case 2:
  114722. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  114723. eState = 0;
  114724. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  114725. eState = 3;
  114726. }else{ /* 2 or greater. A position. */
  114727. pCsr->aStat[iCol+1].nOcc++;
  114728. pCsr->aStat[0].nOcc++;
  114729. }
  114730. break;
  114731. /* State 3. The integer just read is a column number. */
  114732. default: assert( eState==3 );
  114733. iCol = (int)v;
  114734. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  114735. pCsr->aStat[iCol+1].nDoc++;
  114736. eState = 2;
  114737. break;
  114738. }
  114739. }
  114740. pCsr->iCol = 0;
  114741. rc = SQLITE_OK;
  114742. }else{
  114743. pCsr->isEof = 1;
  114744. }
  114745. return rc;
  114746. }
  114747. /*
  114748. ** xFilter - Initialize a cursor to point at the start of its data.
  114749. */
  114750. static int fts3auxFilterMethod(
  114751. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  114752. int idxNum, /* Strategy index */
  114753. const char *idxStr, /* Unused */
  114754. int nVal, /* Number of elements in apVal */
  114755. sqlite3_value **apVal /* Arguments for the indexing scheme */
  114756. ){
  114757. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  114758. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  114759. int rc;
  114760. int isScan;
  114761. UNUSED_PARAMETER(nVal);
  114762. UNUSED_PARAMETER(idxStr);
  114763. assert( idxStr==0 );
  114764. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  114765. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  114766. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  114767. );
  114768. isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
  114769. /* In case this cursor is being reused, close and zero it. */
  114770. testcase(pCsr->filter.zTerm);
  114771. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  114772. sqlite3_free((void *)pCsr->filter.zTerm);
  114773. sqlite3_free(pCsr->aStat);
  114774. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  114775. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  114776. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  114777. if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
  114778. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  114779. if( zStr ){
  114780. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  114781. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  114782. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  114783. }
  114784. }
  114785. if( idxNum&FTS4AUX_LE_CONSTRAINT ){
  114786. int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
  114787. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
  114788. pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
  114789. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  114790. }
  114791. rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
  114792. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  114793. );
  114794. if( rc==SQLITE_OK ){
  114795. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  114796. }
  114797. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  114798. return rc;
  114799. }
  114800. /*
  114801. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  114802. */
  114803. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  114804. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  114805. return pCsr->isEof;
  114806. }
  114807. /*
  114808. ** xColumn - Return a column value.
  114809. */
  114810. static int fts3auxColumnMethod(
  114811. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  114812. sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
  114813. int iCol /* Index of column to read value from */
  114814. ){
  114815. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  114816. assert( p->isEof==0 );
  114817. if( iCol==0 ){ /* Column "term" */
  114818. sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  114819. }else if( iCol==1 ){ /* Column "col" */
  114820. if( p->iCol ){
  114821. sqlite3_result_int(pContext, p->iCol-1);
  114822. }else{
  114823. sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
  114824. }
  114825. }else if( iCol==2 ){ /* Column "documents" */
  114826. sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
  114827. }else{ /* Column "occurrences" */
  114828. sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
  114829. }
  114830. return SQLITE_OK;
  114831. }
  114832. /*
  114833. ** xRowid - Return the current rowid for the cursor.
  114834. */
  114835. static int fts3auxRowidMethod(
  114836. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  114837. sqlite_int64 *pRowid /* OUT: Rowid value */
  114838. ){
  114839. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  114840. *pRowid = pCsr->iRowid;
  114841. return SQLITE_OK;
  114842. }
  114843. /*
  114844. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  114845. ** if successful or an error code if sqlite3_create_module() fails.
  114846. */
  114847. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  114848. static const sqlite3_module fts3aux_module = {
  114849. 0, /* iVersion */
  114850. fts3auxConnectMethod, /* xCreate */
  114851. fts3auxConnectMethod, /* xConnect */
  114852. fts3auxBestIndexMethod, /* xBestIndex */
  114853. fts3auxDisconnectMethod, /* xDisconnect */
  114854. fts3auxDisconnectMethod, /* xDestroy */
  114855. fts3auxOpenMethod, /* xOpen */
  114856. fts3auxCloseMethod, /* xClose */
  114857. fts3auxFilterMethod, /* xFilter */
  114858. fts3auxNextMethod, /* xNext */
  114859. fts3auxEofMethod, /* xEof */
  114860. fts3auxColumnMethod, /* xColumn */
  114861. fts3auxRowidMethod, /* xRowid */
  114862. 0, /* xUpdate */
  114863. 0, /* xBegin */
  114864. 0, /* xSync */
  114865. 0, /* xCommit */
  114866. 0, /* xRollback */
  114867. 0, /* xFindFunction */
  114868. 0, /* xRename */
  114869. 0, /* xSavepoint */
  114870. 0, /* xRelease */
  114871. 0 /* xRollbackTo */
  114872. };
  114873. int rc; /* Return code */
  114874. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  114875. return rc;
  114876. }
  114877. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  114878. /************** End of fts3_aux.c ********************************************/
  114879. /************** Begin file fts3_expr.c ***************************************/
  114880. /*
  114881. ** 2008 Nov 28
  114882. **
  114883. ** The author disclaims copyright to this source code. In place of
  114884. ** a legal notice, here is a blessing:
  114885. **
  114886. ** May you do good and not evil.
  114887. ** May you find forgiveness for yourself and forgive others.
  114888. ** May you share freely, never taking more than you give.
  114889. **
  114890. ******************************************************************************
  114891. **
  114892. ** This module contains code that implements a parser for fts3 query strings
  114893. ** (the right-hand argument to the MATCH operator). Because the supported
  114894. ** syntax is relatively simple, the whole tokenizer/parser system is
  114895. ** hand-coded.
  114896. */
  114897. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  114898. /*
  114899. ** By default, this module parses the legacy syntax that has been
  114900. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  114901. ** is defined, then it uses the new syntax. The differences between
  114902. ** the new and the old syntaxes are:
  114903. **
  114904. ** a) The new syntax supports parenthesis. The old does not.
  114905. **
  114906. ** b) The new syntax supports the AND and NOT operators. The old does not.
  114907. **
  114908. ** c) The old syntax supports the "-" token qualifier. This is not
  114909. ** supported by the new syntax (it is replaced by the NOT operator).
  114910. **
  114911. ** d) When using the old syntax, the OR operator has a greater precedence
  114912. ** than an implicit AND. When using the new, both implicity and explicit
  114913. ** AND operators have a higher precedence than OR.
  114914. **
  114915. ** If compiled with SQLITE_TEST defined, then this module exports the
  114916. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  114917. ** to zero causes the module to use the old syntax. If it is set to
  114918. ** non-zero the new syntax is activated. This is so both syntaxes can
  114919. ** be tested using a single build of testfixture.
  114920. **
  114921. ** The following describes the syntax supported by the fts3 MATCH
  114922. ** operator in a similar format to that used by the lemon parser
  114923. ** generator. This module does not use actually lemon, it uses a
  114924. ** custom parser.
  114925. **
  114926. ** query ::= andexpr (OR andexpr)*.
  114927. **
  114928. ** andexpr ::= notexpr (AND? notexpr)*.
  114929. **
  114930. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  114931. ** notexpr ::= LP query RP.
  114932. **
  114933. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  114934. **
  114935. ** distance_opt ::= .
  114936. ** distance_opt ::= / INTEGER.
  114937. **
  114938. ** phrase ::= TOKEN.
  114939. ** phrase ::= COLUMN:TOKEN.
  114940. ** phrase ::= "TOKEN TOKEN TOKEN...".
  114941. */
  114942. #ifdef SQLITE_TEST
  114943. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  114944. #else
  114945. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  114946. # define sqlite3_fts3_enable_parentheses 1
  114947. # else
  114948. # define sqlite3_fts3_enable_parentheses 0
  114949. # endif
  114950. #endif
  114951. /*
  114952. ** Default span for NEAR operators.
  114953. */
  114954. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  114955. /* #include <string.h> */
  114956. /* #include <assert.h> */
  114957. /*
  114958. ** isNot:
  114959. ** This variable is used by function getNextNode(). When getNextNode() is
  114960. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  114961. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  114962. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  114963. ** zero.
  114964. */
  114965. typedef struct ParseContext ParseContext;
  114966. struct ParseContext {
  114967. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  114968. int iLangid; /* Language id used with tokenizer */
  114969. const char **azCol; /* Array of column names for fts3 table */
  114970. int bFts4; /* True to allow FTS4-only syntax */
  114971. int nCol; /* Number of entries in azCol[] */
  114972. int iDefaultCol; /* Default column to query */
  114973. int isNot; /* True if getNextNode() sees a unary - */
  114974. sqlite3_context *pCtx; /* Write error message here */
  114975. int nNest; /* Number of nested brackets */
  114976. };
  114977. /*
  114978. ** This function is equivalent to the standard isspace() function.
  114979. **
  114980. ** The standard isspace() can be awkward to use safely, because although it
  114981. ** is defined to accept an argument of type int, its behaviour when passed
  114982. ** an integer that falls outside of the range of the unsigned char type
  114983. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  114984. ** is defined to accept an argument of type char, and always returns 0 for
  114985. ** any values that fall outside of the range of the unsigned char type (i.e.
  114986. ** negative values).
  114987. */
  114988. static int fts3isspace(char c){
  114989. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  114990. }
  114991. /*
  114992. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  114993. ** zero the memory before returning a pointer to it. If unsuccessful,
  114994. ** return NULL.
  114995. */
  114996. static void *fts3MallocZero(int nByte){
  114997. void *pRet = sqlite3_malloc(nByte);
  114998. if( pRet ) memset(pRet, 0, nByte);
  114999. return pRet;
  115000. }
  115001. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  115002. sqlite3_tokenizer *pTokenizer,
  115003. int iLangid,
  115004. const char *z,
  115005. int n,
  115006. sqlite3_tokenizer_cursor **ppCsr
  115007. ){
  115008. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  115009. sqlite3_tokenizer_cursor *pCsr = 0;
  115010. int rc;
  115011. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  115012. assert( rc==SQLITE_OK || pCsr==0 );
  115013. if( rc==SQLITE_OK ){
  115014. pCsr->pTokenizer = pTokenizer;
  115015. if( pModule->iVersion>=1 ){
  115016. rc = pModule->xLanguageid(pCsr, iLangid);
  115017. if( rc!=SQLITE_OK ){
  115018. pModule->xClose(pCsr);
  115019. pCsr = 0;
  115020. }
  115021. }
  115022. }
  115023. *ppCsr = pCsr;
  115024. return rc;
  115025. }
  115026. /*
  115027. ** Extract the next token from buffer z (length n) using the tokenizer
  115028. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  115029. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  115030. ** single token and set *ppExpr to point to it. If the end of the buffer is
  115031. ** reached before a token is found, set *ppExpr to zero. It is the
  115032. ** responsibility of the caller to eventually deallocate the allocated
  115033. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  115034. **
  115035. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  115036. ** fails.
  115037. */
  115038. static int getNextToken(
  115039. ParseContext *pParse, /* fts3 query parse context */
  115040. int iCol, /* Value for Fts3Phrase.iColumn */
  115041. const char *z, int n, /* Input string */
  115042. Fts3Expr **ppExpr, /* OUT: expression */
  115043. int *pnConsumed /* OUT: Number of bytes consumed */
  115044. ){
  115045. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  115046. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  115047. int rc;
  115048. sqlite3_tokenizer_cursor *pCursor;
  115049. Fts3Expr *pRet = 0;
  115050. int nConsumed = 0;
  115051. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  115052. if( rc==SQLITE_OK ){
  115053. const char *zToken;
  115054. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  115055. int nByte; /* total space to allocate */
  115056. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  115057. if( rc==SQLITE_OK ){
  115058. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  115059. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  115060. if( !pRet ){
  115061. rc = SQLITE_NOMEM;
  115062. }else{
  115063. pRet->eType = FTSQUERY_PHRASE;
  115064. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  115065. pRet->pPhrase->nToken = 1;
  115066. pRet->pPhrase->iColumn = iCol;
  115067. pRet->pPhrase->aToken[0].n = nToken;
  115068. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  115069. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  115070. if( iEnd<n && z[iEnd]=='*' ){
  115071. pRet->pPhrase->aToken[0].isPrefix = 1;
  115072. iEnd++;
  115073. }
  115074. while( 1 ){
  115075. if( !sqlite3_fts3_enable_parentheses
  115076. && iStart>0 && z[iStart-1]=='-'
  115077. ){
  115078. pParse->isNot = 1;
  115079. iStart--;
  115080. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  115081. pRet->pPhrase->aToken[0].bFirst = 1;
  115082. iStart--;
  115083. }else{
  115084. break;
  115085. }
  115086. }
  115087. }
  115088. nConsumed = iEnd;
  115089. }
  115090. pModule->xClose(pCursor);
  115091. }
  115092. *pnConsumed = nConsumed;
  115093. *ppExpr = pRet;
  115094. return rc;
  115095. }
  115096. /*
  115097. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  115098. ** then free the old allocation.
  115099. */
  115100. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  115101. void *pRet = sqlite3_realloc(pOrig, nNew);
  115102. if( !pRet ){
  115103. sqlite3_free(pOrig);
  115104. }
  115105. return pRet;
  115106. }
  115107. /*
  115108. ** Buffer zInput, length nInput, contains the contents of a quoted string
  115109. ** that appeared as part of an fts3 query expression. Neither quote character
  115110. ** is included in the buffer. This function attempts to tokenize the entire
  115111. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  115112. ** containing the results.
  115113. **
  115114. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  115115. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  115116. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  115117. ** to 0.
  115118. */
  115119. static int getNextString(
  115120. ParseContext *pParse, /* fts3 query parse context */
  115121. const char *zInput, int nInput, /* Input string */
  115122. Fts3Expr **ppExpr /* OUT: expression */
  115123. ){
  115124. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  115125. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  115126. int rc;
  115127. Fts3Expr *p = 0;
  115128. sqlite3_tokenizer_cursor *pCursor = 0;
  115129. char *zTemp = 0;
  115130. int nTemp = 0;
  115131. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  115132. int nToken = 0;
  115133. /* The final Fts3Expr data structure, including the Fts3Phrase,
  115134. ** Fts3PhraseToken structures token buffers are all stored as a single
  115135. ** allocation so that the expression can be freed with a single call to
  115136. ** sqlite3_free(). Setting this up requires a two pass approach.
  115137. **
  115138. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  115139. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  115140. ** to assemble data in two dynamic buffers:
  115141. **
  115142. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  115143. ** structure, followed by the array of Fts3PhraseToken
  115144. ** structures. This pass only populates the Fts3PhraseToken array.
  115145. **
  115146. ** Buffer zTemp: Contains copies of all tokens.
  115147. **
  115148. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  115149. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  115150. ** structures.
  115151. */
  115152. rc = sqlite3Fts3OpenTokenizer(
  115153. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  115154. if( rc==SQLITE_OK ){
  115155. int ii;
  115156. for(ii=0; rc==SQLITE_OK; ii++){
  115157. const char *zByte;
  115158. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  115159. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  115160. if( rc==SQLITE_OK ){
  115161. Fts3PhraseToken *pToken;
  115162. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  115163. if( !p ) goto no_mem;
  115164. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  115165. if( !zTemp ) goto no_mem;
  115166. assert( nToken==ii );
  115167. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  115168. memset(pToken, 0, sizeof(Fts3PhraseToken));
  115169. memcpy(&zTemp[nTemp], zByte, nByte);
  115170. nTemp += nByte;
  115171. pToken->n = nByte;
  115172. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  115173. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  115174. nToken = ii+1;
  115175. }
  115176. }
  115177. pModule->xClose(pCursor);
  115178. pCursor = 0;
  115179. }
  115180. if( rc==SQLITE_DONE ){
  115181. int jj;
  115182. char *zBuf = 0;
  115183. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  115184. if( !p ) goto no_mem;
  115185. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  115186. p->eType = FTSQUERY_PHRASE;
  115187. p->pPhrase = (Fts3Phrase *)&p[1];
  115188. p->pPhrase->iColumn = pParse->iDefaultCol;
  115189. p->pPhrase->nToken = nToken;
  115190. zBuf = (char *)&p->pPhrase->aToken[nToken];
  115191. if( zTemp ){
  115192. memcpy(zBuf, zTemp, nTemp);
  115193. sqlite3_free(zTemp);
  115194. }else{
  115195. assert( nTemp==0 );
  115196. }
  115197. for(jj=0; jj<p->pPhrase->nToken; jj++){
  115198. p->pPhrase->aToken[jj].z = zBuf;
  115199. zBuf += p->pPhrase->aToken[jj].n;
  115200. }
  115201. rc = SQLITE_OK;
  115202. }
  115203. *ppExpr = p;
  115204. return rc;
  115205. no_mem:
  115206. if( pCursor ){
  115207. pModule->xClose(pCursor);
  115208. }
  115209. sqlite3_free(zTemp);
  115210. sqlite3_free(p);
  115211. *ppExpr = 0;
  115212. return SQLITE_NOMEM;
  115213. }
  115214. /*
  115215. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  115216. ** call fts3ExprParse(). So this forward declaration is required.
  115217. */
  115218. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  115219. /*
  115220. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  115221. ** structure, or set to 0 if the end of the input buffer is reached.
  115222. **
  115223. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  115224. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  115225. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  115226. */
  115227. static int getNextNode(
  115228. ParseContext *pParse, /* fts3 query parse context */
  115229. const char *z, int n, /* Input string */
  115230. Fts3Expr **ppExpr, /* OUT: expression */
  115231. int *pnConsumed /* OUT: Number of bytes consumed */
  115232. ){
  115233. static const struct Fts3Keyword {
  115234. char *z; /* Keyword text */
  115235. unsigned char n; /* Length of the keyword */
  115236. unsigned char parenOnly; /* Only valid in paren mode */
  115237. unsigned char eType; /* Keyword code */
  115238. } aKeyword[] = {
  115239. { "OR" , 2, 0, FTSQUERY_OR },
  115240. { "AND", 3, 1, FTSQUERY_AND },
  115241. { "NOT", 3, 1, FTSQUERY_NOT },
  115242. { "NEAR", 4, 0, FTSQUERY_NEAR }
  115243. };
  115244. int ii;
  115245. int iCol;
  115246. int iColLen;
  115247. int rc;
  115248. Fts3Expr *pRet = 0;
  115249. const char *zInput = z;
  115250. int nInput = n;
  115251. pParse->isNot = 0;
  115252. /* Skip over any whitespace before checking for a keyword, an open or
  115253. ** close bracket, or a quoted string.
  115254. */
  115255. while( nInput>0 && fts3isspace(*zInput) ){
  115256. nInput--;
  115257. zInput++;
  115258. }
  115259. if( nInput==0 ){
  115260. return SQLITE_DONE;
  115261. }
  115262. /* See if we are dealing with a keyword. */
  115263. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  115264. const struct Fts3Keyword *pKey = &aKeyword[ii];
  115265. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  115266. continue;
  115267. }
  115268. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  115269. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  115270. int nKey = pKey->n;
  115271. char cNext;
  115272. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  115273. if( pKey->eType==FTSQUERY_NEAR ){
  115274. assert( nKey==4 );
  115275. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  115276. nNear = 0;
  115277. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  115278. nNear = nNear * 10 + (zInput[nKey] - '0');
  115279. }
  115280. }
  115281. }
  115282. /* At this point this is probably a keyword. But for that to be true,
  115283. ** the next byte must contain either whitespace, an open or close
  115284. ** parenthesis, a quote character, or EOF.
  115285. */
  115286. cNext = zInput[nKey];
  115287. if( fts3isspace(cNext)
  115288. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  115289. ){
  115290. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  115291. if( !pRet ){
  115292. return SQLITE_NOMEM;
  115293. }
  115294. pRet->eType = pKey->eType;
  115295. pRet->nNear = nNear;
  115296. *ppExpr = pRet;
  115297. *pnConsumed = (int)((zInput - z) + nKey);
  115298. return SQLITE_OK;
  115299. }
  115300. /* Turns out that wasn't a keyword after all. This happens if the
  115301. ** user has supplied a token such as "ORacle". Continue.
  115302. */
  115303. }
  115304. }
  115305. /* Check for an open bracket. */
  115306. if( sqlite3_fts3_enable_parentheses ){
  115307. if( *zInput=='(' ){
  115308. int nConsumed;
  115309. pParse->nNest++;
  115310. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  115311. if( rc==SQLITE_OK && !*ppExpr ){
  115312. rc = SQLITE_DONE;
  115313. }
  115314. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  115315. return rc;
  115316. }
  115317. /* Check for a close bracket. */
  115318. if( *zInput==')' ){
  115319. pParse->nNest--;
  115320. *pnConsumed = (int)((zInput - z) + 1);
  115321. return SQLITE_DONE;
  115322. }
  115323. }
  115324. /* See if we are dealing with a quoted phrase. If this is the case, then
  115325. ** search for the closing quote and pass the whole string to getNextString()
  115326. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  115327. ** a quote character embedded in a string.
  115328. */
  115329. if( *zInput=='"' ){
  115330. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  115331. *pnConsumed = (int)((zInput - z) + ii + 1);
  115332. if( ii==nInput ){
  115333. return SQLITE_ERROR;
  115334. }
  115335. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  115336. }
  115337. /* If control flows to this point, this must be a regular token, or
  115338. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  115339. ** interface. Before doing so, figure out if there is an explicit
  115340. ** column specifier for the token.
  115341. **
  115342. ** TODO: Strangely, it is not possible to associate a column specifier
  115343. ** with a quoted phrase, only with a single token. Not sure if this was
  115344. ** an implementation artifact or an intentional decision when fts3 was
  115345. ** first implemented. Whichever it was, this module duplicates the
  115346. ** limitation.
  115347. */
  115348. iCol = pParse->iDefaultCol;
  115349. iColLen = 0;
  115350. for(ii=0; ii<pParse->nCol; ii++){
  115351. const char *zStr = pParse->azCol[ii];
  115352. int nStr = (int)strlen(zStr);
  115353. if( nInput>nStr && zInput[nStr]==':'
  115354. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  115355. ){
  115356. iCol = ii;
  115357. iColLen = (int)((zInput - z) + nStr + 1);
  115358. break;
  115359. }
  115360. }
  115361. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  115362. *pnConsumed += iColLen;
  115363. return rc;
  115364. }
  115365. /*
  115366. ** The argument is an Fts3Expr structure for a binary operator (any type
  115367. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  115368. ** precedence of the operator. Lower values have a higher precedence (i.e.
  115369. ** group more tightly). For example, in the C language, the == operator
  115370. ** groups more tightly than ||, and would therefore have a higher precedence.
  115371. **
  115372. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  115373. ** is defined), the order of the operators in precedence from highest to
  115374. ** lowest is:
  115375. **
  115376. ** NEAR
  115377. ** NOT
  115378. ** AND (including implicit ANDs)
  115379. ** OR
  115380. **
  115381. ** Note that when using the old query syntax, the OR operator has a higher
  115382. ** precedence than the AND operator.
  115383. */
  115384. static int opPrecedence(Fts3Expr *p){
  115385. assert( p->eType!=FTSQUERY_PHRASE );
  115386. if( sqlite3_fts3_enable_parentheses ){
  115387. return p->eType;
  115388. }else if( p->eType==FTSQUERY_NEAR ){
  115389. return 1;
  115390. }else if( p->eType==FTSQUERY_OR ){
  115391. return 2;
  115392. }
  115393. assert( p->eType==FTSQUERY_AND );
  115394. return 3;
  115395. }
  115396. /*
  115397. ** Argument ppHead contains a pointer to the current head of a query
  115398. ** expression tree being parsed. pPrev is the expression node most recently
  115399. ** inserted into the tree. This function adds pNew, which is always a binary
  115400. ** operator node, into the expression tree based on the relative precedence
  115401. ** of pNew and the existing nodes of the tree. This may result in the head
  115402. ** of the tree changing, in which case *ppHead is set to the new root node.
  115403. */
  115404. static void insertBinaryOperator(
  115405. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  115406. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  115407. Fts3Expr *pNew /* New binary node to insert into expression tree */
  115408. ){
  115409. Fts3Expr *pSplit = pPrev;
  115410. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  115411. pSplit = pSplit->pParent;
  115412. }
  115413. if( pSplit->pParent ){
  115414. assert( pSplit->pParent->pRight==pSplit );
  115415. pSplit->pParent->pRight = pNew;
  115416. pNew->pParent = pSplit->pParent;
  115417. }else{
  115418. *ppHead = pNew;
  115419. }
  115420. pNew->pLeft = pSplit;
  115421. pSplit->pParent = pNew;
  115422. }
  115423. /*
  115424. ** Parse the fts3 query expression found in buffer z, length n. This function
  115425. ** returns either when the end of the buffer is reached or an unmatched
  115426. ** closing bracket - ')' - is encountered.
  115427. **
  115428. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  115429. ** parsed form of the expression and *pnConsumed is set to the number of
  115430. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  115431. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  115432. */
  115433. static int fts3ExprParse(
  115434. ParseContext *pParse, /* fts3 query parse context */
  115435. const char *z, int n, /* Text of MATCH query */
  115436. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  115437. int *pnConsumed /* OUT: Number of bytes consumed */
  115438. ){
  115439. Fts3Expr *pRet = 0;
  115440. Fts3Expr *pPrev = 0;
  115441. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  115442. int nIn = n;
  115443. const char *zIn = z;
  115444. int rc = SQLITE_OK;
  115445. int isRequirePhrase = 1;
  115446. while( rc==SQLITE_OK ){
  115447. Fts3Expr *p = 0;
  115448. int nByte = 0;
  115449. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  115450. if( rc==SQLITE_OK ){
  115451. int isPhrase;
  115452. if( !sqlite3_fts3_enable_parentheses
  115453. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  115454. ){
  115455. /* Create an implicit NOT operator. */
  115456. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  115457. if( !pNot ){
  115458. sqlite3Fts3ExprFree(p);
  115459. rc = SQLITE_NOMEM;
  115460. goto exprparse_out;
  115461. }
  115462. pNot->eType = FTSQUERY_NOT;
  115463. pNot->pRight = p;
  115464. if( pNotBranch ){
  115465. pNot->pLeft = pNotBranch;
  115466. }
  115467. pNotBranch = pNot;
  115468. p = pPrev;
  115469. }else{
  115470. int eType = p->eType;
  115471. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  115472. /* The isRequirePhrase variable is set to true if a phrase or
  115473. ** an expression contained in parenthesis is required. If a
  115474. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  115475. ** isRequirePhrase is set, this is a syntax error.
  115476. */
  115477. if( !isPhrase && isRequirePhrase ){
  115478. sqlite3Fts3ExprFree(p);
  115479. rc = SQLITE_ERROR;
  115480. goto exprparse_out;
  115481. }
  115482. if( isPhrase && !isRequirePhrase ){
  115483. /* Insert an implicit AND operator. */
  115484. Fts3Expr *pAnd;
  115485. assert( pRet && pPrev );
  115486. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  115487. if( !pAnd ){
  115488. sqlite3Fts3ExprFree(p);
  115489. rc = SQLITE_NOMEM;
  115490. goto exprparse_out;
  115491. }
  115492. pAnd->eType = FTSQUERY_AND;
  115493. insertBinaryOperator(&pRet, pPrev, pAnd);
  115494. pPrev = pAnd;
  115495. }
  115496. /* This test catches attempts to make either operand of a NEAR
  115497. ** operator something other than a phrase. For example, either of
  115498. ** the following:
  115499. **
  115500. ** (bracketed expression) NEAR phrase
  115501. ** phrase NEAR (bracketed expression)
  115502. **
  115503. ** Return an error in either case.
  115504. */
  115505. if( pPrev && (
  115506. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  115507. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  115508. )){
  115509. sqlite3Fts3ExprFree(p);
  115510. rc = SQLITE_ERROR;
  115511. goto exprparse_out;
  115512. }
  115513. if( isPhrase ){
  115514. if( pRet ){
  115515. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  115516. pPrev->pRight = p;
  115517. p->pParent = pPrev;
  115518. }else{
  115519. pRet = p;
  115520. }
  115521. }else{
  115522. insertBinaryOperator(&pRet, pPrev, p);
  115523. }
  115524. isRequirePhrase = !isPhrase;
  115525. }
  115526. assert( nByte>0 );
  115527. }
  115528. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  115529. nIn -= nByte;
  115530. zIn += nByte;
  115531. pPrev = p;
  115532. }
  115533. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  115534. rc = SQLITE_ERROR;
  115535. }
  115536. if( rc==SQLITE_DONE ){
  115537. rc = SQLITE_OK;
  115538. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  115539. if( !pRet ){
  115540. rc = SQLITE_ERROR;
  115541. }else{
  115542. Fts3Expr *pIter = pNotBranch;
  115543. while( pIter->pLeft ){
  115544. pIter = pIter->pLeft;
  115545. }
  115546. pIter->pLeft = pRet;
  115547. pRet = pNotBranch;
  115548. }
  115549. }
  115550. }
  115551. *pnConsumed = n - nIn;
  115552. exprparse_out:
  115553. if( rc!=SQLITE_OK ){
  115554. sqlite3Fts3ExprFree(pRet);
  115555. sqlite3Fts3ExprFree(pNotBranch);
  115556. pRet = 0;
  115557. }
  115558. *ppExpr = pRet;
  115559. return rc;
  115560. }
  115561. /*
  115562. ** Parameters z and n contain a pointer to and length of a buffer containing
  115563. ** an fts3 query expression, respectively. This function attempts to parse the
  115564. ** query expression and create a tree of Fts3Expr structures representing the
  115565. ** parsed expression. If successful, *ppExpr is set to point to the head
  115566. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  115567. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  115568. ** error) is returned and *ppExpr is set to 0.
  115569. **
  115570. ** If parameter n is a negative number, then z is assumed to point to a
  115571. ** nul-terminated string and the length is determined using strlen().
  115572. **
  115573. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  115574. ** use to normalize query tokens while parsing the expression. The azCol[]
  115575. ** array, which is assumed to contain nCol entries, should contain the names
  115576. ** of each column in the target fts3 table, in order from left to right.
  115577. ** Column names must be nul-terminated strings.
  115578. **
  115579. ** The iDefaultCol parameter should be passed the index of the table column
  115580. ** that appears on the left-hand-side of the MATCH operator (the default
  115581. ** column to match against for tokens for which a column name is not explicitly
  115582. ** specified as part of the query string), or -1 if tokens may by default
  115583. ** match any table column.
  115584. */
  115585. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  115586. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  115587. int iLangid, /* Language id for tokenizer */
  115588. char **azCol, /* Array of column names for fts3 table */
  115589. int bFts4, /* True to allow FTS4-only syntax */
  115590. int nCol, /* Number of entries in azCol[] */
  115591. int iDefaultCol, /* Default column to query */
  115592. const char *z, int n, /* Text of MATCH query */
  115593. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  115594. ){
  115595. int nParsed;
  115596. int rc;
  115597. ParseContext sParse;
  115598. memset(&sParse, 0, sizeof(ParseContext));
  115599. sParse.pTokenizer = pTokenizer;
  115600. sParse.iLangid = iLangid;
  115601. sParse.azCol = (const char **)azCol;
  115602. sParse.nCol = nCol;
  115603. sParse.iDefaultCol = iDefaultCol;
  115604. sParse.bFts4 = bFts4;
  115605. if( z==0 ){
  115606. *ppExpr = 0;
  115607. return SQLITE_OK;
  115608. }
  115609. if( n<0 ){
  115610. n = (int)strlen(z);
  115611. }
  115612. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  115613. /* Check for mismatched parenthesis */
  115614. if( rc==SQLITE_OK && sParse.nNest ){
  115615. rc = SQLITE_ERROR;
  115616. sqlite3Fts3ExprFree(*ppExpr);
  115617. *ppExpr = 0;
  115618. }
  115619. return rc;
  115620. }
  115621. /*
  115622. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  115623. */
  115624. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
  115625. if( p ){
  115626. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  115627. sqlite3Fts3ExprFree(p->pLeft);
  115628. sqlite3Fts3ExprFree(p->pRight);
  115629. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  115630. sqlite3_free(p->aMI);
  115631. sqlite3_free(p);
  115632. }
  115633. }
  115634. /****************************************************************************
  115635. *****************************************************************************
  115636. ** Everything after this point is just test code.
  115637. */
  115638. #ifdef SQLITE_TEST
  115639. /* #include <stdio.h> */
  115640. /*
  115641. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  115642. */
  115643. static int queryTestTokenizer(
  115644. sqlite3 *db,
  115645. const char *zName,
  115646. const sqlite3_tokenizer_module **pp
  115647. ){
  115648. int rc;
  115649. sqlite3_stmt *pStmt;
  115650. const char zSql[] = "SELECT fts3_tokenizer(?)";
  115651. *pp = 0;
  115652. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  115653. if( rc!=SQLITE_OK ){
  115654. return rc;
  115655. }
  115656. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  115657. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115658. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  115659. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  115660. }
  115661. }
  115662. return sqlite3_finalize(pStmt);
  115663. }
  115664. /*
  115665. ** Return a pointer to a buffer containing a text representation of the
  115666. ** expression passed as the first argument. The buffer is obtained from
  115667. ** sqlite3_malloc(). It is the responsibility of the caller to use
  115668. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  115669. ** NULL is returned.
  115670. **
  115671. ** If the second argument is not NULL, then its contents are prepended to
  115672. ** the returned expression text and then freed using sqlite3_free().
  115673. */
  115674. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  115675. switch( pExpr->eType ){
  115676. case FTSQUERY_PHRASE: {
  115677. Fts3Phrase *pPhrase = pExpr->pPhrase;
  115678. int i;
  115679. zBuf = sqlite3_mprintf(
  115680. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  115681. for(i=0; zBuf && i<pPhrase->nToken; i++){
  115682. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  115683. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  115684. (pPhrase->aToken[i].isPrefix?"+":"")
  115685. );
  115686. }
  115687. return zBuf;
  115688. }
  115689. case FTSQUERY_NEAR:
  115690. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  115691. break;
  115692. case FTSQUERY_NOT:
  115693. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  115694. break;
  115695. case FTSQUERY_AND:
  115696. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  115697. break;
  115698. case FTSQUERY_OR:
  115699. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  115700. break;
  115701. }
  115702. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  115703. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  115704. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  115705. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  115706. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  115707. return zBuf;
  115708. }
  115709. /*
  115710. ** This is the implementation of a scalar SQL function used to test the
  115711. ** expression parser. It should be called as follows:
  115712. **
  115713. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  115714. **
  115715. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  115716. ** to parse the query expression (see README.tokenizers). The second argument
  115717. ** is the query expression to parse. Each subsequent argument is the name
  115718. ** of a column of the fts3 table that the query expression may refer to.
  115719. ** For example:
  115720. **
  115721. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  115722. */
  115723. static void fts3ExprTest(
  115724. sqlite3_context *context,
  115725. int argc,
  115726. sqlite3_value **argv
  115727. ){
  115728. sqlite3_tokenizer_module const *pModule = 0;
  115729. sqlite3_tokenizer *pTokenizer = 0;
  115730. int rc;
  115731. char **azCol = 0;
  115732. const char *zExpr;
  115733. int nExpr;
  115734. int nCol;
  115735. int ii;
  115736. Fts3Expr *pExpr;
  115737. char *zBuf = 0;
  115738. sqlite3 *db = sqlite3_context_db_handle(context);
  115739. if( argc<3 ){
  115740. sqlite3_result_error(context,
  115741. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  115742. );
  115743. return;
  115744. }
  115745. rc = queryTestTokenizer(db,
  115746. (const char *)sqlite3_value_text(argv[0]), &pModule);
  115747. if( rc==SQLITE_NOMEM ){
  115748. sqlite3_result_error_nomem(context);
  115749. goto exprtest_out;
  115750. }else if( !pModule ){
  115751. sqlite3_result_error(context, "No such tokenizer module", -1);
  115752. goto exprtest_out;
  115753. }
  115754. rc = pModule->xCreate(0, 0, &pTokenizer);
  115755. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  115756. if( rc==SQLITE_NOMEM ){
  115757. sqlite3_result_error_nomem(context);
  115758. goto exprtest_out;
  115759. }
  115760. pTokenizer->pModule = pModule;
  115761. zExpr = (const char *)sqlite3_value_text(argv[1]);
  115762. nExpr = sqlite3_value_bytes(argv[1]);
  115763. nCol = argc-2;
  115764. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  115765. if( !azCol ){
  115766. sqlite3_result_error_nomem(context);
  115767. goto exprtest_out;
  115768. }
  115769. for(ii=0; ii<nCol; ii++){
  115770. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  115771. }
  115772. rc = sqlite3Fts3ExprParse(
  115773. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  115774. );
  115775. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  115776. sqlite3_result_error(context, "Error parsing expression", -1);
  115777. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  115778. sqlite3_result_error_nomem(context);
  115779. }else{
  115780. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  115781. sqlite3_free(zBuf);
  115782. }
  115783. sqlite3Fts3ExprFree(pExpr);
  115784. exprtest_out:
  115785. if( pModule && pTokenizer ){
  115786. rc = pModule->xDestroy(pTokenizer);
  115787. }
  115788. sqlite3_free(azCol);
  115789. }
  115790. /*
  115791. ** Register the query expression parser test function fts3_exprtest()
  115792. ** with database connection db.
  115793. */
  115794. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  115795. return sqlite3_create_function(
  115796. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  115797. );
  115798. }
  115799. #endif
  115800. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  115801. /************** End of fts3_expr.c *******************************************/
  115802. /************** Begin file fts3_hash.c ***************************************/
  115803. /*
  115804. ** 2001 September 22
  115805. **
  115806. ** The author disclaims copyright to this source code. In place of
  115807. ** a legal notice, here is a blessing:
  115808. **
  115809. ** May you do good and not evil.
  115810. ** May you find forgiveness for yourself and forgive others.
  115811. ** May you share freely, never taking more than you give.
  115812. **
  115813. *************************************************************************
  115814. ** This is the implementation of generic hash-tables used in SQLite.
  115815. ** We've modified it slightly to serve as a standalone hash table
  115816. ** implementation for the full-text indexing module.
  115817. */
  115818. /*
  115819. ** The code in this file is only compiled if:
  115820. **
  115821. ** * The FTS3 module is being built as an extension
  115822. ** (in which case SQLITE_CORE is not defined), or
  115823. **
  115824. ** * The FTS3 module is being built into the core of
  115825. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  115826. */
  115827. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  115828. /* #include <assert.h> */
  115829. /* #include <stdlib.h> */
  115830. /* #include <string.h> */
  115831. /*
  115832. ** Malloc and Free functions
  115833. */
  115834. static void *fts3HashMalloc(int n){
  115835. void *p = sqlite3_malloc(n);
  115836. if( p ){
  115837. memset(p, 0, n);
  115838. }
  115839. return p;
  115840. }
  115841. static void fts3HashFree(void *p){
  115842. sqlite3_free(p);
  115843. }
  115844. /* Turn bulk memory into a hash table object by initializing the
  115845. ** fields of the Hash structure.
  115846. **
  115847. ** "pNew" is a pointer to the hash table that is to be initialized.
  115848. ** keyClass is one of the constants
  115849. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  115850. ** determines what kind of key the hash table will use. "copyKey" is
  115851. ** true if the hash table should make its own private copy of keys and
  115852. ** false if it should just use the supplied pointer.
  115853. */
  115854. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  115855. assert( pNew!=0 );
  115856. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  115857. pNew->keyClass = keyClass;
  115858. pNew->copyKey = copyKey;
  115859. pNew->first = 0;
  115860. pNew->count = 0;
  115861. pNew->htsize = 0;
  115862. pNew->ht = 0;
  115863. }
  115864. /* Remove all entries from a hash table. Reclaim all memory.
  115865. ** Call this routine to delete a hash table or to reset a hash table
  115866. ** to the empty state.
  115867. */
  115868. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  115869. Fts3HashElem *elem; /* For looping over all elements of the table */
  115870. assert( pH!=0 );
  115871. elem = pH->first;
  115872. pH->first = 0;
  115873. fts3HashFree(pH->ht);
  115874. pH->ht = 0;
  115875. pH->htsize = 0;
  115876. while( elem ){
  115877. Fts3HashElem *next_elem = elem->next;
  115878. if( pH->copyKey && elem->pKey ){
  115879. fts3HashFree(elem->pKey);
  115880. }
  115881. fts3HashFree(elem);
  115882. elem = next_elem;
  115883. }
  115884. pH->count = 0;
  115885. }
  115886. /*
  115887. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  115888. */
  115889. static int fts3StrHash(const void *pKey, int nKey){
  115890. const char *z = (const char *)pKey;
  115891. int h = 0;
  115892. if( nKey<=0 ) nKey = (int) strlen(z);
  115893. while( nKey > 0 ){
  115894. h = (h<<3) ^ h ^ *z++;
  115895. nKey--;
  115896. }
  115897. return h & 0x7fffffff;
  115898. }
  115899. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  115900. if( n1!=n2 ) return 1;
  115901. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  115902. }
  115903. /*
  115904. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  115905. */
  115906. static int fts3BinHash(const void *pKey, int nKey){
  115907. int h = 0;
  115908. const char *z = (const char *)pKey;
  115909. while( nKey-- > 0 ){
  115910. h = (h<<3) ^ h ^ *(z++);
  115911. }
  115912. return h & 0x7fffffff;
  115913. }
  115914. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  115915. if( n1!=n2 ) return 1;
  115916. return memcmp(pKey1,pKey2,n1);
  115917. }
  115918. /*
  115919. ** Return a pointer to the appropriate hash function given the key class.
  115920. **
  115921. ** The C syntax in this function definition may be unfamilar to some
  115922. ** programmers, so we provide the following additional explanation:
  115923. **
  115924. ** The name of the function is "ftsHashFunction". The function takes a
  115925. ** single parameter "keyClass". The return value of ftsHashFunction()
  115926. ** is a pointer to another function. Specifically, the return value
  115927. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  115928. ** with types "const void*" and "int" and returns an "int".
  115929. */
  115930. static int (*ftsHashFunction(int keyClass))(const void*,int){
  115931. if( keyClass==FTS3_HASH_STRING ){
  115932. return &fts3StrHash;
  115933. }else{
  115934. assert( keyClass==FTS3_HASH_BINARY );
  115935. return &fts3BinHash;
  115936. }
  115937. }
  115938. /*
  115939. ** Return a pointer to the appropriate hash function given the key class.
  115940. **
  115941. ** For help in interpreted the obscure C code in the function definition,
  115942. ** see the header comment on the previous function.
  115943. */
  115944. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  115945. if( keyClass==FTS3_HASH_STRING ){
  115946. return &fts3StrCompare;
  115947. }else{
  115948. assert( keyClass==FTS3_HASH_BINARY );
  115949. return &fts3BinCompare;
  115950. }
  115951. }
  115952. /* Link an element into the hash table
  115953. */
  115954. static void fts3HashInsertElement(
  115955. Fts3Hash *pH, /* The complete hash table */
  115956. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  115957. Fts3HashElem *pNew /* The element to be inserted */
  115958. ){
  115959. Fts3HashElem *pHead; /* First element already in pEntry */
  115960. pHead = pEntry->chain;
  115961. if( pHead ){
  115962. pNew->next = pHead;
  115963. pNew->prev = pHead->prev;
  115964. if( pHead->prev ){ pHead->prev->next = pNew; }
  115965. else { pH->first = pNew; }
  115966. pHead->prev = pNew;
  115967. }else{
  115968. pNew->next = pH->first;
  115969. if( pH->first ){ pH->first->prev = pNew; }
  115970. pNew->prev = 0;
  115971. pH->first = pNew;
  115972. }
  115973. pEntry->count++;
  115974. pEntry->chain = pNew;
  115975. }
  115976. /* Resize the hash table so that it cantains "new_size" buckets.
  115977. ** "new_size" must be a power of 2. The hash table might fail
  115978. ** to resize if sqliteMalloc() fails.
  115979. **
  115980. ** Return non-zero if a memory allocation error occurs.
  115981. */
  115982. static int fts3Rehash(Fts3Hash *pH, int new_size){
  115983. struct _fts3ht *new_ht; /* The new hash table */
  115984. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  115985. int (*xHash)(const void*,int); /* The hash function */
  115986. assert( (new_size & (new_size-1))==0 );
  115987. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  115988. if( new_ht==0 ) return 1;
  115989. fts3HashFree(pH->ht);
  115990. pH->ht = new_ht;
  115991. pH->htsize = new_size;
  115992. xHash = ftsHashFunction(pH->keyClass);
  115993. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  115994. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  115995. next_elem = elem->next;
  115996. fts3HashInsertElement(pH, &new_ht[h], elem);
  115997. }
  115998. return 0;
  115999. }
  116000. /* This function (for internal use only) locates an element in an
  116001. ** hash table that matches the given key. The hash for this key has
  116002. ** already been computed and is passed as the 4th parameter.
  116003. */
  116004. static Fts3HashElem *fts3FindElementByHash(
  116005. const Fts3Hash *pH, /* The pH to be searched */
  116006. const void *pKey, /* The key we are searching for */
  116007. int nKey,
  116008. int h /* The hash for this key. */
  116009. ){
  116010. Fts3HashElem *elem; /* Used to loop thru the element list */
  116011. int count; /* Number of elements left to test */
  116012. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  116013. if( pH->ht ){
  116014. struct _fts3ht *pEntry = &pH->ht[h];
  116015. elem = pEntry->chain;
  116016. count = pEntry->count;
  116017. xCompare = ftsCompareFunction(pH->keyClass);
  116018. while( count-- && elem ){
  116019. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  116020. return elem;
  116021. }
  116022. elem = elem->next;
  116023. }
  116024. }
  116025. return 0;
  116026. }
  116027. /* Remove a single entry from the hash table given a pointer to that
  116028. ** element and a hash on the element's key.
  116029. */
  116030. static void fts3RemoveElementByHash(
  116031. Fts3Hash *pH, /* The pH containing "elem" */
  116032. Fts3HashElem* elem, /* The element to be removed from the pH */
  116033. int h /* Hash value for the element */
  116034. ){
  116035. struct _fts3ht *pEntry;
  116036. if( elem->prev ){
  116037. elem->prev->next = elem->next;
  116038. }else{
  116039. pH->first = elem->next;
  116040. }
  116041. if( elem->next ){
  116042. elem->next->prev = elem->prev;
  116043. }
  116044. pEntry = &pH->ht[h];
  116045. if( pEntry->chain==elem ){
  116046. pEntry->chain = elem->next;
  116047. }
  116048. pEntry->count--;
  116049. if( pEntry->count<=0 ){
  116050. pEntry->chain = 0;
  116051. }
  116052. if( pH->copyKey && elem->pKey ){
  116053. fts3HashFree(elem->pKey);
  116054. }
  116055. fts3HashFree( elem );
  116056. pH->count--;
  116057. if( pH->count<=0 ){
  116058. assert( pH->first==0 );
  116059. assert( pH->count==0 );
  116060. fts3HashClear(pH);
  116061. }
  116062. }
  116063. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  116064. const Fts3Hash *pH,
  116065. const void *pKey,
  116066. int nKey
  116067. ){
  116068. int h; /* A hash on key */
  116069. int (*xHash)(const void*,int); /* The hash function */
  116070. if( pH==0 || pH->ht==0 ) return 0;
  116071. xHash = ftsHashFunction(pH->keyClass);
  116072. assert( xHash!=0 );
  116073. h = (*xHash)(pKey,nKey);
  116074. assert( (pH->htsize & (pH->htsize-1))==0 );
  116075. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  116076. }
  116077. /*
  116078. ** Attempt to locate an element of the hash table pH with a key
  116079. ** that matches pKey,nKey. Return the data for this element if it is
  116080. ** found, or NULL if there is no match.
  116081. */
  116082. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  116083. Fts3HashElem *pElem; /* The element that matches key (if any) */
  116084. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  116085. return pElem ? pElem->data : 0;
  116086. }
  116087. /* Insert an element into the hash table pH. The key is pKey,nKey
  116088. ** and the data is "data".
  116089. **
  116090. ** If no element exists with a matching key, then a new
  116091. ** element is created. A copy of the key is made if the copyKey
  116092. ** flag is set. NULL is returned.
  116093. **
  116094. ** If another element already exists with the same key, then the
  116095. ** new data replaces the old data and the old data is returned.
  116096. ** The key is not copied in this instance. If a malloc fails, then
  116097. ** the new data is returned and the hash table is unchanged.
  116098. **
  116099. ** If the "data" parameter to this function is NULL, then the
  116100. ** element corresponding to "key" is removed from the hash table.
  116101. */
  116102. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  116103. Fts3Hash *pH, /* The hash table to insert into */
  116104. const void *pKey, /* The key */
  116105. int nKey, /* Number of bytes in the key */
  116106. void *data /* The data */
  116107. ){
  116108. int hraw; /* Raw hash value of the key */
  116109. int h; /* the hash of the key modulo hash table size */
  116110. Fts3HashElem *elem; /* Used to loop thru the element list */
  116111. Fts3HashElem *new_elem; /* New element added to the pH */
  116112. int (*xHash)(const void*,int); /* The hash function */
  116113. assert( pH!=0 );
  116114. xHash = ftsHashFunction(pH->keyClass);
  116115. assert( xHash!=0 );
  116116. hraw = (*xHash)(pKey, nKey);
  116117. assert( (pH->htsize & (pH->htsize-1))==0 );
  116118. h = hraw & (pH->htsize-1);
  116119. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  116120. if( elem ){
  116121. void *old_data = elem->data;
  116122. if( data==0 ){
  116123. fts3RemoveElementByHash(pH,elem,h);
  116124. }else{
  116125. elem->data = data;
  116126. }
  116127. return old_data;
  116128. }
  116129. if( data==0 ) return 0;
  116130. if( (pH->htsize==0 && fts3Rehash(pH,8))
  116131. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  116132. ){
  116133. pH->count = 0;
  116134. return data;
  116135. }
  116136. assert( pH->htsize>0 );
  116137. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  116138. if( new_elem==0 ) return data;
  116139. if( pH->copyKey && pKey!=0 ){
  116140. new_elem->pKey = fts3HashMalloc( nKey );
  116141. if( new_elem->pKey==0 ){
  116142. fts3HashFree(new_elem);
  116143. return data;
  116144. }
  116145. memcpy((void*)new_elem->pKey, pKey, nKey);
  116146. }else{
  116147. new_elem->pKey = (void*)pKey;
  116148. }
  116149. new_elem->nKey = nKey;
  116150. pH->count++;
  116151. assert( pH->htsize>0 );
  116152. assert( (pH->htsize & (pH->htsize-1))==0 );
  116153. h = hraw & (pH->htsize-1);
  116154. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  116155. new_elem->data = data;
  116156. return 0;
  116157. }
  116158. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  116159. /************** End of fts3_hash.c *******************************************/
  116160. /************** Begin file fts3_porter.c *************************************/
  116161. /*
  116162. ** 2006 September 30
  116163. **
  116164. ** The author disclaims copyright to this source code. In place of
  116165. ** a legal notice, here is a blessing:
  116166. **
  116167. ** May you do good and not evil.
  116168. ** May you find forgiveness for yourself and forgive others.
  116169. ** May you share freely, never taking more than you give.
  116170. **
  116171. *************************************************************************
  116172. ** Implementation of the full-text-search tokenizer that implements
  116173. ** a Porter stemmer.
  116174. */
  116175. /*
  116176. ** The code in this file is only compiled if:
  116177. **
  116178. ** * The FTS3 module is being built as an extension
  116179. ** (in which case SQLITE_CORE is not defined), or
  116180. **
  116181. ** * The FTS3 module is being built into the core of
  116182. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  116183. */
  116184. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  116185. /* #include <assert.h> */
  116186. /* #include <stdlib.h> */
  116187. /* #include <stdio.h> */
  116188. /* #include <string.h> */
  116189. /*
  116190. ** Class derived from sqlite3_tokenizer
  116191. */
  116192. typedef struct porter_tokenizer {
  116193. sqlite3_tokenizer base; /* Base class */
  116194. } porter_tokenizer;
  116195. /*
  116196. ** Class derived from sqlite3_tokenizer_cursor
  116197. */
  116198. typedef struct porter_tokenizer_cursor {
  116199. sqlite3_tokenizer_cursor base;
  116200. const char *zInput; /* input we are tokenizing */
  116201. int nInput; /* size of the input */
  116202. int iOffset; /* current position in zInput */
  116203. int iToken; /* index of next token to be returned */
  116204. char *zToken; /* storage for current token */
  116205. int nAllocated; /* space allocated to zToken buffer */
  116206. } porter_tokenizer_cursor;
  116207. /*
  116208. ** Create a new tokenizer instance.
  116209. */
  116210. static int porterCreate(
  116211. int argc, const char * const *argv,
  116212. sqlite3_tokenizer **ppTokenizer
  116213. ){
  116214. porter_tokenizer *t;
  116215. UNUSED_PARAMETER(argc);
  116216. UNUSED_PARAMETER(argv);
  116217. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  116218. if( t==NULL ) return SQLITE_NOMEM;
  116219. memset(t, 0, sizeof(*t));
  116220. *ppTokenizer = &t->base;
  116221. return SQLITE_OK;
  116222. }
  116223. /*
  116224. ** Destroy a tokenizer
  116225. */
  116226. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  116227. sqlite3_free(pTokenizer);
  116228. return SQLITE_OK;
  116229. }
  116230. /*
  116231. ** Prepare to begin tokenizing a particular string. The input
  116232. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  116233. ** used to incrementally tokenize this string is returned in
  116234. ** *ppCursor.
  116235. */
  116236. static int porterOpen(
  116237. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  116238. const char *zInput, int nInput, /* String to be tokenized */
  116239. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  116240. ){
  116241. porter_tokenizer_cursor *c;
  116242. UNUSED_PARAMETER(pTokenizer);
  116243. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  116244. if( c==NULL ) return SQLITE_NOMEM;
  116245. c->zInput = zInput;
  116246. if( zInput==0 ){
  116247. c->nInput = 0;
  116248. }else if( nInput<0 ){
  116249. c->nInput = (int)strlen(zInput);
  116250. }else{
  116251. c->nInput = nInput;
  116252. }
  116253. c->iOffset = 0; /* start tokenizing at the beginning */
  116254. c->iToken = 0;
  116255. c->zToken = NULL; /* no space allocated, yet. */
  116256. c->nAllocated = 0;
  116257. *ppCursor = &c->base;
  116258. return SQLITE_OK;
  116259. }
  116260. /*
  116261. ** Close a tokenization cursor previously opened by a call to
  116262. ** porterOpen() above.
  116263. */
  116264. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  116265. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  116266. sqlite3_free(c->zToken);
  116267. sqlite3_free(c);
  116268. return SQLITE_OK;
  116269. }
  116270. /*
  116271. ** Vowel or consonant
  116272. */
  116273. static const char cType[] = {
  116274. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  116275. 1, 1, 1, 2, 1
  116276. };
  116277. /*
  116278. ** isConsonant() and isVowel() determine if their first character in
  116279. ** the string they point to is a consonant or a vowel, according
  116280. ** to Porter ruls.
  116281. **
  116282. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  116283. ** 'Y' is a consonant unless it follows another consonant,
  116284. ** in which case it is a vowel.
  116285. **
  116286. ** In these routine, the letters are in reverse order. So the 'y' rule
  116287. ** is that 'y' is a consonant unless it is followed by another
  116288. ** consonent.
  116289. */
  116290. static int isVowel(const char*);
  116291. static int isConsonant(const char *z){
  116292. int j;
  116293. char x = *z;
  116294. if( x==0 ) return 0;
  116295. assert( x>='a' && x<='z' );
  116296. j = cType[x-'a'];
  116297. if( j<2 ) return j;
  116298. return z[1]==0 || isVowel(z + 1);
  116299. }
  116300. static int isVowel(const char *z){
  116301. int j;
  116302. char x = *z;
  116303. if( x==0 ) return 0;
  116304. assert( x>='a' && x<='z' );
  116305. j = cType[x-'a'];
  116306. if( j<2 ) return 1-j;
  116307. return isConsonant(z + 1);
  116308. }
  116309. /*
  116310. ** Let any sequence of one or more vowels be represented by V and let
  116311. ** C be sequence of one or more consonants. Then every word can be
  116312. ** represented as:
  116313. **
  116314. ** [C] (VC){m} [V]
  116315. **
  116316. ** In prose: A word is an optional consonant followed by zero or
  116317. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  116318. ** number of vowel consonant pairs. This routine computes the value
  116319. ** of m for the first i bytes of a word.
  116320. **
  116321. ** Return true if the m-value for z is 1 or more. In other words,
  116322. ** return true if z contains at least one vowel that is followed
  116323. ** by a consonant.
  116324. **
  116325. ** In this routine z[] is in reverse order. So we are really looking
  116326. ** for an instance of of a consonant followed by a vowel.
  116327. */
  116328. static int m_gt_0(const char *z){
  116329. while( isVowel(z) ){ z++; }
  116330. if( *z==0 ) return 0;
  116331. while( isConsonant(z) ){ z++; }
  116332. return *z!=0;
  116333. }
  116334. /* Like mgt0 above except we are looking for a value of m which is
  116335. ** exactly 1
  116336. */
  116337. static int m_eq_1(const char *z){
  116338. while( isVowel(z) ){ z++; }
  116339. if( *z==0 ) return 0;
  116340. while( isConsonant(z) ){ z++; }
  116341. if( *z==0 ) return 0;
  116342. while( isVowel(z) ){ z++; }
  116343. if( *z==0 ) return 1;
  116344. while( isConsonant(z) ){ z++; }
  116345. return *z==0;
  116346. }
  116347. /* Like mgt0 above except we are looking for a value of m>1 instead
  116348. ** or m>0
  116349. */
  116350. static int m_gt_1(const char *z){
  116351. while( isVowel(z) ){ z++; }
  116352. if( *z==0 ) return 0;
  116353. while( isConsonant(z) ){ z++; }
  116354. if( *z==0 ) return 0;
  116355. while( isVowel(z) ){ z++; }
  116356. if( *z==0 ) return 0;
  116357. while( isConsonant(z) ){ z++; }
  116358. return *z!=0;
  116359. }
  116360. /*
  116361. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  116362. */
  116363. static int hasVowel(const char *z){
  116364. while( isConsonant(z) ){ z++; }
  116365. return *z!=0;
  116366. }
  116367. /*
  116368. ** Return TRUE if the word ends in a double consonant.
  116369. **
  116370. ** The text is reversed here. So we are really looking at
  116371. ** the first two characters of z[].
  116372. */
  116373. static int doubleConsonant(const char *z){
  116374. return isConsonant(z) && z[0]==z[1];
  116375. }
  116376. /*
  116377. ** Return TRUE if the word ends with three letters which
  116378. ** are consonant-vowel-consonent and where the final consonant
  116379. ** is not 'w', 'x', or 'y'.
  116380. **
  116381. ** The word is reversed here. So we are really checking the
  116382. ** first three letters and the first one cannot be in [wxy].
  116383. */
  116384. static int star_oh(const char *z){
  116385. return
  116386. isConsonant(z) &&
  116387. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  116388. isVowel(z+1) &&
  116389. isConsonant(z+2);
  116390. }
  116391. /*
  116392. ** If the word ends with zFrom and xCond() is true for the stem
  116393. ** of the word that preceeds the zFrom ending, then change the
  116394. ** ending to zTo.
  116395. **
  116396. ** The input word *pz and zFrom are both in reverse order. zTo
  116397. ** is in normal order.
  116398. **
  116399. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  116400. ** match. Not that TRUE is returned even if xCond() fails and
  116401. ** no substitution occurs.
  116402. */
  116403. static int stem(
  116404. char **pz, /* The word being stemmed (Reversed) */
  116405. const char *zFrom, /* If the ending matches this... (Reversed) */
  116406. const char *zTo, /* ... change the ending to this (not reversed) */
  116407. int (*xCond)(const char*) /* Condition that must be true */
  116408. ){
  116409. char *z = *pz;
  116410. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  116411. if( *zFrom!=0 ) return 0;
  116412. if( xCond && !xCond(z) ) return 1;
  116413. while( *zTo ){
  116414. *(--z) = *(zTo++);
  116415. }
  116416. *pz = z;
  116417. return 1;
  116418. }
  116419. /*
  116420. ** This is the fallback stemmer used when the porter stemmer is
  116421. ** inappropriate. The input word is copied into the output with
  116422. ** US-ASCII case folding. If the input word is too long (more
  116423. ** than 20 bytes if it contains no digits or more than 6 bytes if
  116424. ** it contains digits) then word is truncated to 20 or 6 bytes
  116425. ** by taking 10 or 3 bytes from the beginning and end.
  116426. */
  116427. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  116428. int i, mx, j;
  116429. int hasDigit = 0;
  116430. for(i=0; i<nIn; i++){
  116431. char c = zIn[i];
  116432. if( c>='A' && c<='Z' ){
  116433. zOut[i] = c - 'A' + 'a';
  116434. }else{
  116435. if( c>='0' && c<='9' ) hasDigit = 1;
  116436. zOut[i] = c;
  116437. }
  116438. }
  116439. mx = hasDigit ? 3 : 10;
  116440. if( nIn>mx*2 ){
  116441. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  116442. zOut[j] = zOut[i];
  116443. }
  116444. i = j;
  116445. }
  116446. zOut[i] = 0;
  116447. *pnOut = i;
  116448. }
  116449. /*
  116450. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  116451. ** zOut is at least big enough to hold nIn bytes. Write the actual
  116452. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  116453. **
  116454. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  116455. ** are converted to lower case. Upper-case UTF characters are
  116456. ** unchanged.
  116457. **
  116458. ** Words that are longer than about 20 bytes are stemmed by retaining
  116459. ** a few bytes from the beginning and the end of the word. If the
  116460. ** word contains digits, 3 bytes are taken from the beginning and
  116461. ** 3 bytes from the end. For long words without digits, 10 bytes
  116462. ** are taken from each end. US-ASCII case folding still applies.
  116463. **
  116464. ** If the input word contains not digits but does characters not
  116465. ** in [a-zA-Z] then no stemming is attempted and this routine just
  116466. ** copies the input into the input into the output with US-ASCII
  116467. ** case folding.
  116468. **
  116469. ** Stemming never increases the length of the word. So there is
  116470. ** no chance of overflowing the zOut buffer.
  116471. */
  116472. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  116473. int i, j;
  116474. char zReverse[28];
  116475. char *z, *z2;
  116476. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  116477. /* The word is too big or too small for the porter stemmer.
  116478. ** Fallback to the copy stemmer */
  116479. copy_stemmer(zIn, nIn, zOut, pnOut);
  116480. return;
  116481. }
  116482. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  116483. char c = zIn[i];
  116484. if( c>='A' && c<='Z' ){
  116485. zReverse[j] = c + 'a' - 'A';
  116486. }else if( c>='a' && c<='z' ){
  116487. zReverse[j] = c;
  116488. }else{
  116489. /* The use of a character not in [a-zA-Z] means that we fallback
  116490. ** to the copy stemmer */
  116491. copy_stemmer(zIn, nIn, zOut, pnOut);
  116492. return;
  116493. }
  116494. }
  116495. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  116496. z = &zReverse[j+1];
  116497. /* Step 1a */
  116498. if( z[0]=='s' ){
  116499. if(
  116500. !stem(&z, "sess", "ss", 0) &&
  116501. !stem(&z, "sei", "i", 0) &&
  116502. !stem(&z, "ss", "ss", 0)
  116503. ){
  116504. z++;
  116505. }
  116506. }
  116507. /* Step 1b */
  116508. z2 = z;
  116509. if( stem(&z, "dee", "ee", m_gt_0) ){
  116510. /* Do nothing. The work was all in the test */
  116511. }else if(
  116512. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  116513. && z!=z2
  116514. ){
  116515. if( stem(&z, "ta", "ate", 0) ||
  116516. stem(&z, "lb", "ble", 0) ||
  116517. stem(&z, "zi", "ize", 0) ){
  116518. /* Do nothing. The work was all in the test */
  116519. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  116520. z++;
  116521. }else if( m_eq_1(z) && star_oh(z) ){
  116522. *(--z) = 'e';
  116523. }
  116524. }
  116525. /* Step 1c */
  116526. if( z[0]=='y' && hasVowel(z+1) ){
  116527. z[0] = 'i';
  116528. }
  116529. /* Step 2 */
  116530. switch( z[1] ){
  116531. case 'a':
  116532. stem(&z, "lanoita", "ate", m_gt_0) ||
  116533. stem(&z, "lanoit", "tion", m_gt_0);
  116534. break;
  116535. case 'c':
  116536. stem(&z, "icne", "ence", m_gt_0) ||
  116537. stem(&z, "icna", "ance", m_gt_0);
  116538. break;
  116539. case 'e':
  116540. stem(&z, "rezi", "ize", m_gt_0);
  116541. break;
  116542. case 'g':
  116543. stem(&z, "igol", "log", m_gt_0);
  116544. break;
  116545. case 'l':
  116546. stem(&z, "ilb", "ble", m_gt_0) ||
  116547. stem(&z, "illa", "al", m_gt_0) ||
  116548. stem(&z, "iltne", "ent", m_gt_0) ||
  116549. stem(&z, "ile", "e", m_gt_0) ||
  116550. stem(&z, "ilsuo", "ous", m_gt_0);
  116551. break;
  116552. case 'o':
  116553. stem(&z, "noitazi", "ize", m_gt_0) ||
  116554. stem(&z, "noita", "ate", m_gt_0) ||
  116555. stem(&z, "rota", "ate", m_gt_0);
  116556. break;
  116557. case 's':
  116558. stem(&z, "msila", "al", m_gt_0) ||
  116559. stem(&z, "ssenevi", "ive", m_gt_0) ||
  116560. stem(&z, "ssenluf", "ful", m_gt_0) ||
  116561. stem(&z, "ssensuo", "ous", m_gt_0);
  116562. break;
  116563. case 't':
  116564. stem(&z, "itila", "al", m_gt_0) ||
  116565. stem(&z, "itivi", "ive", m_gt_0) ||
  116566. stem(&z, "itilib", "ble", m_gt_0);
  116567. break;
  116568. }
  116569. /* Step 3 */
  116570. switch( z[0] ){
  116571. case 'e':
  116572. stem(&z, "etaci", "ic", m_gt_0) ||
  116573. stem(&z, "evita", "", m_gt_0) ||
  116574. stem(&z, "ezila", "al", m_gt_0);
  116575. break;
  116576. case 'i':
  116577. stem(&z, "itici", "ic", m_gt_0);
  116578. break;
  116579. case 'l':
  116580. stem(&z, "laci", "ic", m_gt_0) ||
  116581. stem(&z, "luf", "", m_gt_0);
  116582. break;
  116583. case 's':
  116584. stem(&z, "ssen", "", m_gt_0);
  116585. break;
  116586. }
  116587. /* Step 4 */
  116588. switch( z[1] ){
  116589. case 'a':
  116590. if( z[0]=='l' && m_gt_1(z+2) ){
  116591. z += 2;
  116592. }
  116593. break;
  116594. case 'c':
  116595. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  116596. z += 4;
  116597. }
  116598. break;
  116599. case 'e':
  116600. if( z[0]=='r' && m_gt_1(z+2) ){
  116601. z += 2;
  116602. }
  116603. break;
  116604. case 'i':
  116605. if( z[0]=='c' && m_gt_1(z+2) ){
  116606. z += 2;
  116607. }
  116608. break;
  116609. case 'l':
  116610. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  116611. z += 4;
  116612. }
  116613. break;
  116614. case 'n':
  116615. if( z[0]=='t' ){
  116616. if( z[2]=='a' ){
  116617. if( m_gt_1(z+3) ){
  116618. z += 3;
  116619. }
  116620. }else if( z[2]=='e' ){
  116621. stem(&z, "tneme", "", m_gt_1) ||
  116622. stem(&z, "tnem", "", m_gt_1) ||
  116623. stem(&z, "tne", "", m_gt_1);
  116624. }
  116625. }
  116626. break;
  116627. case 'o':
  116628. if( z[0]=='u' ){
  116629. if( m_gt_1(z+2) ){
  116630. z += 2;
  116631. }
  116632. }else if( z[3]=='s' || z[3]=='t' ){
  116633. stem(&z, "noi", "", m_gt_1);
  116634. }
  116635. break;
  116636. case 's':
  116637. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  116638. z += 3;
  116639. }
  116640. break;
  116641. case 't':
  116642. stem(&z, "eta", "", m_gt_1) ||
  116643. stem(&z, "iti", "", m_gt_1);
  116644. break;
  116645. case 'u':
  116646. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  116647. z += 3;
  116648. }
  116649. break;
  116650. case 'v':
  116651. case 'z':
  116652. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  116653. z += 3;
  116654. }
  116655. break;
  116656. }
  116657. /* Step 5a */
  116658. if( z[0]=='e' ){
  116659. if( m_gt_1(z+1) ){
  116660. z++;
  116661. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  116662. z++;
  116663. }
  116664. }
  116665. /* Step 5b */
  116666. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  116667. z++;
  116668. }
  116669. /* z[] is now the stemmed word in reverse order. Flip it back
  116670. ** around into forward order and return.
  116671. */
  116672. *pnOut = i = (int)strlen(z);
  116673. zOut[i] = 0;
  116674. while( *z ){
  116675. zOut[--i] = *(z++);
  116676. }
  116677. }
  116678. /*
  116679. ** Characters that can be part of a token. We assume any character
  116680. ** whose value is greater than 0x80 (any UTF character) can be
  116681. ** part of a token. In other words, delimiters all must have
  116682. ** values of 0x7f or lower.
  116683. */
  116684. static const char porterIdChar[] = {
  116685. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  116686. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  116687. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  116688. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  116689. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  116690. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  116691. };
  116692. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  116693. /*
  116694. ** Extract the next token from a tokenization cursor. The cursor must
  116695. ** have been opened by a prior call to porterOpen().
  116696. */
  116697. static int porterNext(
  116698. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  116699. const char **pzToken, /* OUT: *pzToken is the token text */
  116700. int *pnBytes, /* OUT: Number of bytes in token */
  116701. int *piStartOffset, /* OUT: Starting offset of token */
  116702. int *piEndOffset, /* OUT: Ending offset of token */
  116703. int *piPosition /* OUT: Position integer of token */
  116704. ){
  116705. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  116706. const char *z = c->zInput;
  116707. while( c->iOffset<c->nInput ){
  116708. int iStartOffset, ch;
  116709. /* Scan past delimiter characters */
  116710. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  116711. c->iOffset++;
  116712. }
  116713. /* Count non-delimiter characters. */
  116714. iStartOffset = c->iOffset;
  116715. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  116716. c->iOffset++;
  116717. }
  116718. if( c->iOffset>iStartOffset ){
  116719. int n = c->iOffset-iStartOffset;
  116720. if( n>c->nAllocated ){
  116721. char *pNew;
  116722. c->nAllocated = n+20;
  116723. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  116724. if( !pNew ) return SQLITE_NOMEM;
  116725. c->zToken = pNew;
  116726. }
  116727. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  116728. *pzToken = c->zToken;
  116729. *piStartOffset = iStartOffset;
  116730. *piEndOffset = c->iOffset;
  116731. *piPosition = c->iToken++;
  116732. return SQLITE_OK;
  116733. }
  116734. }
  116735. return SQLITE_DONE;
  116736. }
  116737. /*
  116738. ** The set of routines that implement the porter-stemmer tokenizer
  116739. */
  116740. static const sqlite3_tokenizer_module porterTokenizerModule = {
  116741. 0,
  116742. porterCreate,
  116743. porterDestroy,
  116744. porterOpen,
  116745. porterClose,
  116746. porterNext,
  116747. 0
  116748. };
  116749. /*
  116750. ** Allocate a new porter tokenizer. Return a pointer to the new
  116751. ** tokenizer in *ppModule
  116752. */
  116753. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  116754. sqlite3_tokenizer_module const**ppModule
  116755. ){
  116756. *ppModule = &porterTokenizerModule;
  116757. }
  116758. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  116759. /************** End of fts3_porter.c *****************************************/
  116760. /************** Begin file fts3_tokenizer.c **********************************/
  116761. /*
  116762. ** 2007 June 22
  116763. **
  116764. ** The author disclaims copyright to this source code. In place of
  116765. ** a legal notice, here is a blessing:
  116766. **
  116767. ** May you do good and not evil.
  116768. ** May you find forgiveness for yourself and forgive others.
  116769. ** May you share freely, never taking more than you give.
  116770. **
  116771. ******************************************************************************
  116772. **
  116773. ** This is part of an SQLite module implementing full-text search.
  116774. ** This particular file implements the generic tokenizer interface.
  116775. */
  116776. /*
  116777. ** The code in this file is only compiled if:
  116778. **
  116779. ** * The FTS3 module is being built as an extension
  116780. ** (in which case SQLITE_CORE is not defined), or
  116781. **
  116782. ** * The FTS3 module is being built into the core of
  116783. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  116784. */
  116785. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  116786. /* #include <assert.h> */
  116787. /* #include <string.h> */
  116788. /*
  116789. ** Implementation of the SQL scalar function for accessing the underlying
  116790. ** hash table. This function may be called as follows:
  116791. **
  116792. ** SELECT <function-name>(<key-name>);
  116793. ** SELECT <function-name>(<key-name>, <pointer>);
  116794. **
  116795. ** where <function-name> is the name passed as the second argument
  116796. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  116797. **
  116798. ** If the <pointer> argument is specified, it must be a blob value
  116799. ** containing a pointer to be stored as the hash data corresponding
  116800. ** to the string <key-name>. If <pointer> is not specified, then
  116801. ** the string <key-name> must already exist in the has table. Otherwise,
  116802. ** an error is returned.
  116803. **
  116804. ** Whether or not the <pointer> argument is specified, the value returned
  116805. ** is a blob containing the pointer stored as the hash data corresponding
  116806. ** to string <key-name> (after the hash-table is updated, if applicable).
  116807. */
  116808. static void scalarFunc(
  116809. sqlite3_context *context,
  116810. int argc,
  116811. sqlite3_value **argv
  116812. ){
  116813. Fts3Hash *pHash;
  116814. void *pPtr = 0;
  116815. const unsigned char *zName;
  116816. int nName;
  116817. assert( argc==1 || argc==2 );
  116818. pHash = (Fts3Hash *)sqlite3_user_data(context);
  116819. zName = sqlite3_value_text(argv[0]);
  116820. nName = sqlite3_value_bytes(argv[0])+1;
  116821. if( argc==2 ){
  116822. void *pOld;
  116823. int n = sqlite3_value_bytes(argv[1]);
  116824. if( n!=sizeof(pPtr) ){
  116825. sqlite3_result_error(context, "argument type mismatch", -1);
  116826. return;
  116827. }
  116828. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  116829. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  116830. if( pOld==pPtr ){
  116831. sqlite3_result_error(context, "out of memory", -1);
  116832. return;
  116833. }
  116834. }else{
  116835. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  116836. if( !pPtr ){
  116837. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  116838. sqlite3_result_error(context, zErr, -1);
  116839. sqlite3_free(zErr);
  116840. return;
  116841. }
  116842. }
  116843. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  116844. }
  116845. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  116846. static const char isFtsIdChar[] = {
  116847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  116848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  116849. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  116850. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  116851. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  116852. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  116853. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  116854. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  116855. };
  116856. return (c&0x80 || isFtsIdChar[(int)(c)]);
  116857. }
  116858. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  116859. const char *z1;
  116860. const char *z2 = 0;
  116861. /* Find the start of the next token. */
  116862. z1 = zStr;
  116863. while( z2==0 ){
  116864. char c = *z1;
  116865. switch( c ){
  116866. case '\0': return 0; /* No more tokens here */
  116867. case '\'':
  116868. case '"':
  116869. case '`': {
  116870. z2 = z1;
  116871. while( *++z2 && (*z2!=c || *++z2==c) );
  116872. break;
  116873. }
  116874. case '[':
  116875. z2 = &z1[1];
  116876. while( *z2 && z2[0]!=']' ) z2++;
  116877. if( *z2 ) z2++;
  116878. break;
  116879. default:
  116880. if( sqlite3Fts3IsIdChar(*z1) ){
  116881. z2 = &z1[1];
  116882. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  116883. }else{
  116884. z1++;
  116885. }
  116886. }
  116887. }
  116888. *pn = (int)(z2-z1);
  116889. return z1;
  116890. }
  116891. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  116892. Fts3Hash *pHash, /* Tokenizer hash table */
  116893. const char *zArg, /* Tokenizer name */
  116894. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  116895. char **pzErr /* OUT: Set to malloced error message */
  116896. ){
  116897. int rc;
  116898. char *z = (char *)zArg;
  116899. int n = 0;
  116900. char *zCopy;
  116901. char *zEnd; /* Pointer to nul-term of zCopy */
  116902. sqlite3_tokenizer_module *m;
  116903. zCopy = sqlite3_mprintf("%s", zArg);
  116904. if( !zCopy ) return SQLITE_NOMEM;
  116905. zEnd = &zCopy[strlen(zCopy)];
  116906. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  116907. z[n] = '\0';
  116908. sqlite3Fts3Dequote(z);
  116909. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  116910. if( !m ){
  116911. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  116912. rc = SQLITE_ERROR;
  116913. }else{
  116914. char const **aArg = 0;
  116915. int iArg = 0;
  116916. z = &z[n+1];
  116917. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  116918. int nNew = sizeof(char *)*(iArg+1);
  116919. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  116920. if( !aNew ){
  116921. sqlite3_free(zCopy);
  116922. sqlite3_free((void *)aArg);
  116923. return SQLITE_NOMEM;
  116924. }
  116925. aArg = aNew;
  116926. aArg[iArg++] = z;
  116927. z[n] = '\0';
  116928. sqlite3Fts3Dequote(z);
  116929. z = &z[n+1];
  116930. }
  116931. rc = m->xCreate(iArg, aArg, ppTok);
  116932. assert( rc!=SQLITE_OK || *ppTok );
  116933. if( rc!=SQLITE_OK ){
  116934. *pzErr = sqlite3_mprintf("unknown tokenizer");
  116935. }else{
  116936. (*ppTok)->pModule = m;
  116937. }
  116938. sqlite3_free((void *)aArg);
  116939. }
  116940. sqlite3_free(zCopy);
  116941. return rc;
  116942. }
  116943. #ifdef SQLITE_TEST
  116944. /* #include <tcl.h> */
  116945. /* #include <string.h> */
  116946. /*
  116947. ** Implementation of a special SQL scalar function for testing tokenizers
  116948. ** designed to be used in concert with the Tcl testing framework. This
  116949. ** function must be called with two or more arguments:
  116950. **
  116951. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  116952. **
  116953. ** where <function-name> is the name passed as the second argument
  116954. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  116955. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  116956. **
  116957. ** The return value is a string that may be interpreted as a Tcl
  116958. ** list. For each token in the <input-string>, three elements are
  116959. ** added to the returned list. The first is the token position, the
  116960. ** second is the token text (folded, stemmed, etc.) and the third is the
  116961. ** substring of <input-string> associated with the token. For example,
  116962. ** using the built-in "simple" tokenizer:
  116963. **
  116964. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  116965. **
  116966. ** will return the string:
  116967. **
  116968. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  116969. **
  116970. */
  116971. static void testFunc(
  116972. sqlite3_context *context,
  116973. int argc,
  116974. sqlite3_value **argv
  116975. ){
  116976. Fts3Hash *pHash;
  116977. sqlite3_tokenizer_module *p;
  116978. sqlite3_tokenizer *pTokenizer = 0;
  116979. sqlite3_tokenizer_cursor *pCsr = 0;
  116980. const char *zErr = 0;
  116981. const char *zName;
  116982. int nName;
  116983. const char *zInput;
  116984. int nInput;
  116985. const char *azArg[64];
  116986. const char *zToken;
  116987. int nToken = 0;
  116988. int iStart = 0;
  116989. int iEnd = 0;
  116990. int iPos = 0;
  116991. int i;
  116992. Tcl_Obj *pRet;
  116993. if( argc<2 ){
  116994. sqlite3_result_error(context, "insufficient arguments", -1);
  116995. return;
  116996. }
  116997. nName = sqlite3_value_bytes(argv[0]);
  116998. zName = (const char *)sqlite3_value_text(argv[0]);
  116999. nInput = sqlite3_value_bytes(argv[argc-1]);
  117000. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  117001. pHash = (Fts3Hash *)sqlite3_user_data(context);
  117002. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  117003. if( !p ){
  117004. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  117005. sqlite3_result_error(context, zErr, -1);
  117006. sqlite3_free(zErr);
  117007. return;
  117008. }
  117009. pRet = Tcl_NewObj();
  117010. Tcl_IncrRefCount(pRet);
  117011. for(i=1; i<argc-1; i++){
  117012. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  117013. }
  117014. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  117015. zErr = "error in xCreate()";
  117016. goto finish;
  117017. }
  117018. pTokenizer->pModule = p;
  117019. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  117020. zErr = "error in xOpen()";
  117021. goto finish;
  117022. }
  117023. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  117024. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  117025. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  117026. zToken = &zInput[iStart];
  117027. nToken = iEnd-iStart;
  117028. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  117029. }
  117030. if( SQLITE_OK!=p->xClose(pCsr) ){
  117031. zErr = "error in xClose()";
  117032. goto finish;
  117033. }
  117034. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  117035. zErr = "error in xDestroy()";
  117036. goto finish;
  117037. }
  117038. finish:
  117039. if( zErr ){
  117040. sqlite3_result_error(context, zErr, -1);
  117041. }else{
  117042. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  117043. }
  117044. Tcl_DecrRefCount(pRet);
  117045. }
  117046. static
  117047. int registerTokenizer(
  117048. sqlite3 *db,
  117049. char *zName,
  117050. const sqlite3_tokenizer_module *p
  117051. ){
  117052. int rc;
  117053. sqlite3_stmt *pStmt;
  117054. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  117055. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  117056. if( rc!=SQLITE_OK ){
  117057. return rc;
  117058. }
  117059. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  117060. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  117061. sqlite3_step(pStmt);
  117062. return sqlite3_finalize(pStmt);
  117063. }
  117064. static
  117065. int queryTokenizer(
  117066. sqlite3 *db,
  117067. char *zName,
  117068. const sqlite3_tokenizer_module **pp
  117069. ){
  117070. int rc;
  117071. sqlite3_stmt *pStmt;
  117072. const char zSql[] = "SELECT fts3_tokenizer(?)";
  117073. *pp = 0;
  117074. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  117075. if( rc!=SQLITE_OK ){
  117076. return rc;
  117077. }
  117078. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  117079. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  117080. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  117081. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  117082. }
  117083. }
  117084. return sqlite3_finalize(pStmt);
  117085. }
  117086. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  117087. /*
  117088. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  117089. ** This function is used for testing only, it is not included in the
  117090. ** build unless SQLITE_TEST is defined.
  117091. **
  117092. ** The purpose of this is to test that the fts3_tokenizer() function
  117093. ** can be used as designed by the C-code in the queryTokenizer and
  117094. ** registerTokenizer() functions above. These two functions are repeated
  117095. ** in the README.tokenizer file as an example, so it is important to
  117096. ** test them.
  117097. **
  117098. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  117099. ** function with no arguments. An assert() will fail if a problem is
  117100. ** detected. i.e.:
  117101. **
  117102. ** SELECT fts3_tokenizer_internal_test();
  117103. **
  117104. */
  117105. static void intTestFunc(
  117106. sqlite3_context *context,
  117107. int argc,
  117108. sqlite3_value **argv
  117109. ){
  117110. int rc;
  117111. const sqlite3_tokenizer_module *p1;
  117112. const sqlite3_tokenizer_module *p2;
  117113. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  117114. UNUSED_PARAMETER(argc);
  117115. UNUSED_PARAMETER(argv);
  117116. /* Test the query function */
  117117. sqlite3Fts3SimpleTokenizerModule(&p1);
  117118. rc = queryTokenizer(db, "simple", &p2);
  117119. assert( rc==SQLITE_OK );
  117120. assert( p1==p2 );
  117121. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  117122. assert( rc==SQLITE_ERROR );
  117123. assert( p2==0 );
  117124. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  117125. /* Test the storage function */
  117126. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  117127. assert( rc==SQLITE_OK );
  117128. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  117129. assert( rc==SQLITE_OK );
  117130. assert( p2==p1 );
  117131. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  117132. }
  117133. #endif
  117134. /*
  117135. ** Set up SQL objects in database db used to access the contents of
  117136. ** the hash table pointed to by argument pHash. The hash table must
  117137. ** been initialised to use string keys, and to take a private copy
  117138. ** of the key when a value is inserted. i.e. by a call similar to:
  117139. **
  117140. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  117141. **
  117142. ** This function adds a scalar function (see header comment above
  117143. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  117144. ** defined at compilation time, a temporary virtual table (see header
  117145. ** comment above struct HashTableVtab) to the database schema. Both
  117146. ** provide read/write access to the contents of *pHash.
  117147. **
  117148. ** The third argument to this function, zName, is used as the name
  117149. ** of both the scalar and, if created, the virtual table.
  117150. */
  117151. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  117152. sqlite3 *db,
  117153. Fts3Hash *pHash,
  117154. const char *zName
  117155. ){
  117156. int rc = SQLITE_OK;
  117157. void *p = (void *)pHash;
  117158. const int any = SQLITE_ANY;
  117159. #ifdef SQLITE_TEST
  117160. char *zTest = 0;
  117161. char *zTest2 = 0;
  117162. void *pdb = (void *)db;
  117163. zTest = sqlite3_mprintf("%s_test", zName);
  117164. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  117165. if( !zTest || !zTest2 ){
  117166. rc = SQLITE_NOMEM;
  117167. }
  117168. #endif
  117169. if( SQLITE_OK==rc ){
  117170. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  117171. }
  117172. if( SQLITE_OK==rc ){
  117173. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  117174. }
  117175. #ifdef SQLITE_TEST
  117176. if( SQLITE_OK==rc ){
  117177. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  117178. }
  117179. if( SQLITE_OK==rc ){
  117180. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  117181. }
  117182. #endif
  117183. #ifdef SQLITE_TEST
  117184. sqlite3_free(zTest);
  117185. sqlite3_free(zTest2);
  117186. #endif
  117187. return rc;
  117188. }
  117189. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  117190. /************** End of fts3_tokenizer.c **************************************/
  117191. /************** Begin file fts3_tokenizer1.c *********************************/
  117192. /*
  117193. ** 2006 Oct 10
  117194. **
  117195. ** The author disclaims copyright to this source code. In place of
  117196. ** a legal notice, here is a blessing:
  117197. **
  117198. ** May you do good and not evil.
  117199. ** May you find forgiveness for yourself and forgive others.
  117200. ** May you share freely, never taking more than you give.
  117201. **
  117202. ******************************************************************************
  117203. **
  117204. ** Implementation of the "simple" full-text-search tokenizer.
  117205. */
  117206. /*
  117207. ** The code in this file is only compiled if:
  117208. **
  117209. ** * The FTS3 module is being built as an extension
  117210. ** (in which case SQLITE_CORE is not defined), or
  117211. **
  117212. ** * The FTS3 module is being built into the core of
  117213. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  117214. */
  117215. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117216. /* #include <assert.h> */
  117217. /* #include <stdlib.h> */
  117218. /* #include <stdio.h> */
  117219. /* #include <string.h> */
  117220. typedef struct simple_tokenizer {
  117221. sqlite3_tokenizer base;
  117222. char delim[128]; /* flag ASCII delimiters */
  117223. } simple_tokenizer;
  117224. typedef struct simple_tokenizer_cursor {
  117225. sqlite3_tokenizer_cursor base;
  117226. const char *pInput; /* input we are tokenizing */
  117227. int nBytes; /* size of the input */
  117228. int iOffset; /* current position in pInput */
  117229. int iToken; /* index of next token to be returned */
  117230. char *pToken; /* storage for current token */
  117231. int nTokenAllocated; /* space allocated to zToken buffer */
  117232. } simple_tokenizer_cursor;
  117233. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  117234. return c<0x80 && t->delim[c];
  117235. }
  117236. static int fts3_isalnum(int x){
  117237. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  117238. }
  117239. /*
  117240. ** Create a new tokenizer instance.
  117241. */
  117242. static int simpleCreate(
  117243. int argc, const char * const *argv,
  117244. sqlite3_tokenizer **ppTokenizer
  117245. ){
  117246. simple_tokenizer *t;
  117247. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  117248. if( t==NULL ) return SQLITE_NOMEM;
  117249. memset(t, 0, sizeof(*t));
  117250. /* TODO(shess) Delimiters need to remain the same from run to run,
  117251. ** else we need to reindex. One solution would be a meta-table to
  117252. ** track such information in the database, then we'd only want this
  117253. ** information on the initial create.
  117254. */
  117255. if( argc>1 ){
  117256. int i, n = (int)strlen(argv[1]);
  117257. for(i=0; i<n; i++){
  117258. unsigned char ch = argv[1][i];
  117259. /* We explicitly don't support UTF-8 delimiters for now. */
  117260. if( ch>=0x80 ){
  117261. sqlite3_free(t);
  117262. return SQLITE_ERROR;
  117263. }
  117264. t->delim[ch] = 1;
  117265. }
  117266. } else {
  117267. /* Mark non-alphanumeric ASCII characters as delimiters */
  117268. int i;
  117269. for(i=1; i<0x80; i++){
  117270. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  117271. }
  117272. }
  117273. *ppTokenizer = &t->base;
  117274. return SQLITE_OK;
  117275. }
  117276. /*
  117277. ** Destroy a tokenizer
  117278. */
  117279. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  117280. sqlite3_free(pTokenizer);
  117281. return SQLITE_OK;
  117282. }
  117283. /*
  117284. ** Prepare to begin tokenizing a particular string. The input
  117285. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  117286. ** used to incrementally tokenize this string is returned in
  117287. ** *ppCursor.
  117288. */
  117289. static int simpleOpen(
  117290. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  117291. const char *pInput, int nBytes, /* String to be tokenized */
  117292. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  117293. ){
  117294. simple_tokenizer_cursor *c;
  117295. UNUSED_PARAMETER(pTokenizer);
  117296. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  117297. if( c==NULL ) return SQLITE_NOMEM;
  117298. c->pInput = pInput;
  117299. if( pInput==0 ){
  117300. c->nBytes = 0;
  117301. }else if( nBytes<0 ){
  117302. c->nBytes = (int)strlen(pInput);
  117303. }else{
  117304. c->nBytes = nBytes;
  117305. }
  117306. c->iOffset = 0; /* start tokenizing at the beginning */
  117307. c->iToken = 0;
  117308. c->pToken = NULL; /* no space allocated, yet. */
  117309. c->nTokenAllocated = 0;
  117310. *ppCursor = &c->base;
  117311. return SQLITE_OK;
  117312. }
  117313. /*
  117314. ** Close a tokenization cursor previously opened by a call to
  117315. ** simpleOpen() above.
  117316. */
  117317. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  117318. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  117319. sqlite3_free(c->pToken);
  117320. sqlite3_free(c);
  117321. return SQLITE_OK;
  117322. }
  117323. /*
  117324. ** Extract the next token from a tokenization cursor. The cursor must
  117325. ** have been opened by a prior call to simpleOpen().
  117326. */
  117327. static int simpleNext(
  117328. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  117329. const char **ppToken, /* OUT: *ppToken is the token text */
  117330. int *pnBytes, /* OUT: Number of bytes in token */
  117331. int *piStartOffset, /* OUT: Starting offset of token */
  117332. int *piEndOffset, /* OUT: Ending offset of token */
  117333. int *piPosition /* OUT: Position integer of token */
  117334. ){
  117335. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  117336. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  117337. unsigned char *p = (unsigned char *)c->pInput;
  117338. while( c->iOffset<c->nBytes ){
  117339. int iStartOffset;
  117340. /* Scan past delimiter characters */
  117341. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  117342. c->iOffset++;
  117343. }
  117344. /* Count non-delimiter characters. */
  117345. iStartOffset = c->iOffset;
  117346. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  117347. c->iOffset++;
  117348. }
  117349. if( c->iOffset>iStartOffset ){
  117350. int i, n = c->iOffset-iStartOffset;
  117351. if( n>c->nTokenAllocated ){
  117352. char *pNew;
  117353. c->nTokenAllocated = n+20;
  117354. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  117355. if( !pNew ) return SQLITE_NOMEM;
  117356. c->pToken = pNew;
  117357. }
  117358. for(i=0; i<n; i++){
  117359. /* TODO(shess) This needs expansion to handle UTF-8
  117360. ** case-insensitivity.
  117361. */
  117362. unsigned char ch = p[iStartOffset+i];
  117363. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  117364. }
  117365. *ppToken = c->pToken;
  117366. *pnBytes = n;
  117367. *piStartOffset = iStartOffset;
  117368. *piEndOffset = c->iOffset;
  117369. *piPosition = c->iToken++;
  117370. return SQLITE_OK;
  117371. }
  117372. }
  117373. return SQLITE_DONE;
  117374. }
  117375. /*
  117376. ** The set of routines that implement the simple tokenizer
  117377. */
  117378. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  117379. 0,
  117380. simpleCreate,
  117381. simpleDestroy,
  117382. simpleOpen,
  117383. simpleClose,
  117384. simpleNext,
  117385. 0,
  117386. };
  117387. /*
  117388. ** Allocate a new simple tokenizer. Return a pointer to the new
  117389. ** tokenizer in *ppModule
  117390. */
  117391. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  117392. sqlite3_tokenizer_module const**ppModule
  117393. ){
  117394. *ppModule = &simpleTokenizerModule;
  117395. }
  117396. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  117397. /************** End of fts3_tokenizer1.c *************************************/
  117398. /************** Begin file fts3_write.c **************************************/
  117399. /*
  117400. ** 2009 Oct 23
  117401. **
  117402. ** The author disclaims copyright to this source code. In place of
  117403. ** a legal notice, here is a blessing:
  117404. **
  117405. ** May you do good and not evil.
  117406. ** May you find forgiveness for yourself and forgive others.
  117407. ** May you share freely, never taking more than you give.
  117408. **
  117409. ******************************************************************************
  117410. **
  117411. ** This file is part of the SQLite FTS3 extension module. Specifically,
  117412. ** this file contains code to insert, update and delete rows from FTS3
  117413. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  117414. ** of the sub-routines used to merge segments are also used by the query
  117415. ** code in fts3.c.
  117416. */
  117417. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117418. /* #include <string.h> */
  117419. /* #include <assert.h> */
  117420. /* #include <stdlib.h> */
  117421. #define FTS_MAX_APPENDABLE_HEIGHT 16
  117422. /*
  117423. ** When full-text index nodes are loaded from disk, the buffer that they
  117424. ** are loaded into has the following number of bytes of padding at the end
  117425. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  117426. ** of 920 bytes is allocated for it.
  117427. **
  117428. ** This means that if we have a pointer into a buffer containing node data,
  117429. ** it is always safe to read up to two varints from it without risking an
  117430. ** overread, even if the node data is corrupted.
  117431. */
  117432. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  117433. /*
  117434. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  117435. ** memory incrementally instead of all at once. This can be a big performance
  117436. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  117437. ** method before retrieving all query results (as may happen, for example,
  117438. ** if a query has a LIMIT clause).
  117439. **
  117440. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  117441. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  117442. ** The code is written so that the hard lower-limit for each of these values
  117443. ** is 1. Clearly such small values would be inefficient, but can be useful
  117444. ** for testing purposes.
  117445. **
  117446. ** If this module is built with SQLITE_TEST defined, these constants may
  117447. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  117448. ** a Tcl interface to read and write the values.
  117449. */
  117450. #ifdef SQLITE_TEST
  117451. int test_fts3_node_chunksize = (4*1024);
  117452. int test_fts3_node_chunk_threshold = (4*1024)*4;
  117453. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  117454. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  117455. #else
  117456. # define FTS3_NODE_CHUNKSIZE (4*1024)
  117457. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  117458. #endif
  117459. /*
  117460. ** The two values that may be meaningfully bound to the :1 parameter in
  117461. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  117462. */
  117463. #define FTS_STAT_DOCTOTAL 0
  117464. #define FTS_STAT_INCRMERGEHINT 1
  117465. #define FTS_STAT_AUTOINCRMERGE 2
  117466. /*
  117467. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  117468. ** and incremental merge operation that takes place. This is used for
  117469. ** debugging FTS only, it should not usually be turned on in production
  117470. ** systems.
  117471. */
  117472. #ifdef FTS3_LOG_MERGES
  117473. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  117474. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  117475. }
  117476. #else
  117477. #define fts3LogMerge(x, y)
  117478. #endif
  117479. typedef struct PendingList PendingList;
  117480. typedef struct SegmentNode SegmentNode;
  117481. typedef struct SegmentWriter SegmentWriter;
  117482. /*
  117483. ** An instance of the following data structure is used to build doclists
  117484. ** incrementally. See function fts3PendingListAppend() for details.
  117485. */
  117486. struct PendingList {
  117487. int nData;
  117488. char *aData;
  117489. int nSpace;
  117490. sqlite3_int64 iLastDocid;
  117491. sqlite3_int64 iLastCol;
  117492. sqlite3_int64 iLastPos;
  117493. };
  117494. /*
  117495. ** Each cursor has a (possibly empty) linked list of the following objects.
  117496. */
  117497. struct Fts3DeferredToken {
  117498. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  117499. int iCol; /* Column token must occur in */
  117500. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  117501. PendingList *pList; /* Doclist is assembled here */
  117502. };
  117503. /*
  117504. ** An instance of this structure is used to iterate through the terms on
  117505. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  117506. ** this structure are only manipulated by code in this file, opaque handles
  117507. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  117508. ** terms when querying the full-text index. See functions:
  117509. **
  117510. ** sqlite3Fts3SegReaderNew()
  117511. ** sqlite3Fts3SegReaderFree()
  117512. ** sqlite3Fts3SegReaderIterate()
  117513. **
  117514. ** Methods used to manipulate Fts3SegReader structures:
  117515. **
  117516. ** fts3SegReaderNext()
  117517. ** fts3SegReaderFirstDocid()
  117518. ** fts3SegReaderNextDocid()
  117519. */
  117520. struct Fts3SegReader {
  117521. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  117522. u8 bLookup; /* True for a lookup only */
  117523. u8 rootOnly; /* True for a root-only reader */
  117524. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  117525. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  117526. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  117527. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  117528. char *aNode; /* Pointer to node data (or NULL) */
  117529. int nNode; /* Size of buffer at aNode (or 0) */
  117530. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  117531. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  117532. Fts3HashElem **ppNextElem;
  117533. /* Variables set by fts3SegReaderNext(). These may be read directly
  117534. ** by the caller. They are valid from the time SegmentReaderNew() returns
  117535. ** until SegmentReaderNext() returns something other than SQLITE_OK
  117536. ** (i.e. SQLITE_DONE).
  117537. */
  117538. int nTerm; /* Number of bytes in current term */
  117539. char *zTerm; /* Pointer to current term */
  117540. int nTermAlloc; /* Allocated size of zTerm buffer */
  117541. char *aDoclist; /* Pointer to doclist of current entry */
  117542. int nDoclist; /* Size of doclist in current entry */
  117543. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  117544. ** through the current doclist (aDoclist/nDoclist).
  117545. */
  117546. char *pOffsetList;
  117547. int nOffsetList; /* For descending pending seg-readers only */
  117548. sqlite3_int64 iDocid;
  117549. };
  117550. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  117551. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  117552. /*
  117553. ** An instance of this structure is used to create a segment b-tree in the
  117554. ** database. The internal details of this type are only accessed by the
  117555. ** following functions:
  117556. **
  117557. ** fts3SegWriterAdd()
  117558. ** fts3SegWriterFlush()
  117559. ** fts3SegWriterFree()
  117560. */
  117561. struct SegmentWriter {
  117562. SegmentNode *pTree; /* Pointer to interior tree structure */
  117563. sqlite3_int64 iFirst; /* First slot in %_segments written */
  117564. sqlite3_int64 iFree; /* Next free slot in %_segments */
  117565. char *zTerm; /* Pointer to previous term buffer */
  117566. int nTerm; /* Number of bytes in zTerm */
  117567. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  117568. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  117569. int nSize; /* Size of allocation at aData */
  117570. int nData; /* Bytes of data in aData */
  117571. char *aData; /* Pointer to block from malloc() */
  117572. };
  117573. /*
  117574. ** Type SegmentNode is used by the following three functions to create
  117575. ** the interior part of the segment b+-tree structures (everything except
  117576. ** the leaf nodes). These functions and type are only ever used by code
  117577. ** within the fts3SegWriterXXX() family of functions described above.
  117578. **
  117579. ** fts3NodeAddTerm()
  117580. ** fts3NodeWrite()
  117581. ** fts3NodeFree()
  117582. **
  117583. ** When a b+tree is written to the database (either as a result of a merge
  117584. ** or the pending-terms table being flushed), leaves are written into the
  117585. ** database file as soon as they are completely populated. The interior of
  117586. ** the tree is assembled in memory and written out only once all leaves have
  117587. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  117588. ** very large, meaning that the interior of the tree consumes relatively
  117589. ** little memory.
  117590. */
  117591. struct SegmentNode {
  117592. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  117593. SegmentNode *pRight; /* Pointer to right-sibling */
  117594. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  117595. int nEntry; /* Number of terms written to node so far */
  117596. char *zTerm; /* Pointer to previous term buffer */
  117597. int nTerm; /* Number of bytes in zTerm */
  117598. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  117599. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  117600. int nData; /* Bytes of valid data so far */
  117601. char *aData; /* Node data */
  117602. };
  117603. /*
  117604. ** Valid values for the second argument to fts3SqlStmt().
  117605. */
  117606. #define SQL_DELETE_CONTENT 0
  117607. #define SQL_IS_EMPTY 1
  117608. #define SQL_DELETE_ALL_CONTENT 2
  117609. #define SQL_DELETE_ALL_SEGMENTS 3
  117610. #define SQL_DELETE_ALL_SEGDIR 4
  117611. #define SQL_DELETE_ALL_DOCSIZE 5
  117612. #define SQL_DELETE_ALL_STAT 6
  117613. #define SQL_SELECT_CONTENT_BY_ROWID 7
  117614. #define SQL_NEXT_SEGMENT_INDEX 8
  117615. #define SQL_INSERT_SEGMENTS 9
  117616. #define SQL_NEXT_SEGMENTS_ID 10
  117617. #define SQL_INSERT_SEGDIR 11
  117618. #define SQL_SELECT_LEVEL 12
  117619. #define SQL_SELECT_LEVEL_RANGE 13
  117620. #define SQL_SELECT_LEVEL_COUNT 14
  117621. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  117622. #define SQL_DELETE_SEGDIR_LEVEL 16
  117623. #define SQL_DELETE_SEGMENTS_RANGE 17
  117624. #define SQL_CONTENT_INSERT 18
  117625. #define SQL_DELETE_DOCSIZE 19
  117626. #define SQL_REPLACE_DOCSIZE 20
  117627. #define SQL_SELECT_DOCSIZE 21
  117628. #define SQL_SELECT_STAT 22
  117629. #define SQL_REPLACE_STAT 23
  117630. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  117631. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  117632. #define SQL_DELETE_SEGDIR_RANGE 26
  117633. #define SQL_SELECT_ALL_LANGID 27
  117634. #define SQL_FIND_MERGE_LEVEL 28
  117635. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  117636. #define SQL_DELETE_SEGDIR_ENTRY 30
  117637. #define SQL_SHIFT_SEGDIR_ENTRY 31
  117638. #define SQL_SELECT_SEGDIR 32
  117639. #define SQL_CHOMP_SEGDIR 33
  117640. #define SQL_SEGMENT_IS_APPENDABLE 34
  117641. #define SQL_SELECT_INDEXES 35
  117642. #define SQL_SELECT_MXLEVEL 36
  117643. /*
  117644. ** This function is used to obtain an SQLite prepared statement handle
  117645. ** for the statement identified by the second argument. If successful,
  117646. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  117647. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  117648. **
  117649. ** If argument apVal is not NULL, then it must point to an array with
  117650. ** at least as many entries as the requested statement has bound
  117651. ** parameters. The values are bound to the statements parameters before
  117652. ** returning.
  117653. */
  117654. static int fts3SqlStmt(
  117655. Fts3Table *p, /* Virtual table handle */
  117656. int eStmt, /* One of the SQL_XXX constants above */
  117657. sqlite3_stmt **pp, /* OUT: Statement handle */
  117658. sqlite3_value **apVal /* Values to bind to statement */
  117659. ){
  117660. const char *azSql[] = {
  117661. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  117662. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  117663. /* 2 */ "DELETE FROM %Q.'%q_content'",
  117664. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  117665. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  117666. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  117667. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  117668. /* 7 */ "SELECT %s WHERE rowid=?",
  117669. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  117670. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  117671. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  117672. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  117673. /* Return segments in order from oldest to newest.*/
  117674. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  117675. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  117676. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  117677. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  117678. "ORDER BY level DESC, idx ASC",
  117679. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  117680. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  117681. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  117682. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  117683. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  117684. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  117685. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  117686. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  117687. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  117688. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  117689. /* 24 */ "",
  117690. /* 25 */ "",
  117691. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  117692. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  117693. /* This statement is used to determine which level to read the input from
  117694. ** when performing an incremental merge. It returns the absolute level number
  117695. ** of the oldest level in the db that contains at least ? segments. Or,
  117696. ** if no level in the FTS index contains more than ? segments, the statement
  117697. ** returns zero rows. */
  117698. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  117699. " ORDER BY (level %% 1024) ASC LIMIT 1",
  117700. /* Estimate the upper limit on the number of leaf nodes in a new segment
  117701. ** created by merging the oldest :2 segments from absolute level :1. See
  117702. ** function sqlite3Fts3Incrmerge() for details. */
  117703. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  117704. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  117705. /* SQL_DELETE_SEGDIR_ENTRY
  117706. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  117707. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  117708. /* SQL_SHIFT_SEGDIR_ENTRY
  117709. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  117710. ** to :1. */
  117711. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  117712. /* SQL_SELECT_SEGDIR
  117713. ** Read a single entry from the %_segdir table. The entry from absolute
  117714. ** level :1 with index value :2. */
  117715. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  117716. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  117717. /* SQL_CHOMP_SEGDIR
  117718. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  117719. ** entry located on absolute level :3 with index :4. */
  117720. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  117721. "WHERE level = ? AND idx = ?",
  117722. /* SQL_SEGMENT_IS_APPENDABLE
  117723. ** Return a single row if the segment with end_block=? is appendable. Or
  117724. ** no rows otherwise. */
  117725. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  117726. /* SQL_SELECT_INDEXES
  117727. ** Return the list of valid segment indexes for absolute level ? */
  117728. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  117729. /* SQL_SELECT_MXLEVEL
  117730. ** Return the largest relative level in the FTS index or indexes. */
  117731. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  117732. };
  117733. int rc = SQLITE_OK;
  117734. sqlite3_stmt *pStmt;
  117735. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  117736. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  117737. pStmt = p->aStmt[eStmt];
  117738. if( !pStmt ){
  117739. char *zSql;
  117740. if( eStmt==SQL_CONTENT_INSERT ){
  117741. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  117742. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  117743. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  117744. }else{
  117745. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  117746. }
  117747. if( !zSql ){
  117748. rc = SQLITE_NOMEM;
  117749. }else{
  117750. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  117751. sqlite3_free(zSql);
  117752. assert( rc==SQLITE_OK || pStmt==0 );
  117753. p->aStmt[eStmt] = pStmt;
  117754. }
  117755. }
  117756. if( apVal ){
  117757. int i;
  117758. int nParam = sqlite3_bind_parameter_count(pStmt);
  117759. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  117760. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  117761. }
  117762. }
  117763. *pp = pStmt;
  117764. return rc;
  117765. }
  117766. static int fts3SelectDocsize(
  117767. Fts3Table *pTab, /* FTS3 table handle */
  117768. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  117769. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  117770. ){
  117771. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  117772. int rc; /* Return code */
  117773. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  117774. if( rc==SQLITE_OK ){
  117775. sqlite3_bind_int64(pStmt, 1, iDocid);
  117776. rc = sqlite3_step(pStmt);
  117777. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  117778. rc = sqlite3_reset(pStmt);
  117779. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  117780. pStmt = 0;
  117781. }else{
  117782. rc = SQLITE_OK;
  117783. }
  117784. }
  117785. *ppStmt = pStmt;
  117786. return rc;
  117787. }
  117788. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  117789. Fts3Table *pTab, /* Fts3 table handle */
  117790. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  117791. ){
  117792. sqlite3_stmt *pStmt = 0;
  117793. int rc;
  117794. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  117795. if( rc==SQLITE_OK ){
  117796. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  117797. if( sqlite3_step(pStmt)!=SQLITE_ROW
  117798. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  117799. ){
  117800. rc = sqlite3_reset(pStmt);
  117801. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  117802. pStmt = 0;
  117803. }
  117804. }
  117805. *ppStmt = pStmt;
  117806. return rc;
  117807. }
  117808. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  117809. Fts3Table *pTab, /* Fts3 table handle */
  117810. sqlite3_int64 iDocid, /* Docid to read size data for */
  117811. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  117812. ){
  117813. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  117814. }
  117815. /*
  117816. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  117817. ** array apVal[] to the SQL statement identified by eStmt, the statement
  117818. ** is executed.
  117819. **
  117820. ** Returns SQLITE_OK if the statement is successfully executed, or an
  117821. ** SQLite error code otherwise.
  117822. */
  117823. static void fts3SqlExec(
  117824. int *pRC, /* Result code */
  117825. Fts3Table *p, /* The FTS3 table */
  117826. int eStmt, /* Index of statement to evaluate */
  117827. sqlite3_value **apVal /* Parameters to bind */
  117828. ){
  117829. sqlite3_stmt *pStmt;
  117830. int rc;
  117831. if( *pRC ) return;
  117832. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  117833. if( rc==SQLITE_OK ){
  117834. sqlite3_step(pStmt);
  117835. rc = sqlite3_reset(pStmt);
  117836. }
  117837. *pRC = rc;
  117838. }
  117839. /*
  117840. ** This function ensures that the caller has obtained a shared-cache
  117841. ** table-lock on the %_content table. This is required before reading
  117842. ** data from the fts3 table. If this lock is not acquired first, then
  117843. ** the caller may end up holding read-locks on the %_segments and %_segdir
  117844. ** tables, but no read-lock on the %_content table. If this happens
  117845. ** a second connection will be able to write to the fts3 table, but
  117846. ** attempting to commit those writes might return SQLITE_LOCKED or
  117847. ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
  117848. ** write-locks on the %_segments and %_segdir ** tables).
  117849. **
  117850. ** We try to avoid this because if FTS3 returns any error when committing
  117851. ** a transaction, the whole transaction will be rolled back. And this is
  117852. ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
  117853. ** still happen if the user reads data directly from the %_segments or
  117854. ** %_segdir tables instead of going through FTS3 though.
  117855. **
  117856. ** This reasoning does not apply to a content=xxx table.
  117857. */
  117858. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
  117859. int rc; /* Return code */
  117860. sqlite3_stmt *pStmt; /* Statement used to obtain lock */
  117861. if( p->zContentTbl==0 ){
  117862. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
  117863. if( rc==SQLITE_OK ){
  117864. sqlite3_bind_null(pStmt, 1);
  117865. sqlite3_step(pStmt);
  117866. rc = sqlite3_reset(pStmt);
  117867. }
  117868. }else{
  117869. rc = SQLITE_OK;
  117870. }
  117871. return rc;
  117872. }
  117873. /*
  117874. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  117875. ** Within each language id, a separate index is maintained to store the
  117876. ** document terms, and each configured prefix size (configured the FTS
  117877. ** "prefix=" option). And each index consists of multiple levels ("relative
  117878. ** levels").
  117879. **
  117880. ** All three of these values (the language id, the specific index and the
  117881. ** level within the index) are encoded in 64-bit integer values stored
  117882. ** in the %_segdir table on disk. This function is used to convert three
  117883. ** separate component values into the single 64-bit integer value that
  117884. ** can be used to query the %_segdir table.
  117885. **
  117886. ** Specifically, each language-id/index combination is allocated 1024
  117887. ** 64-bit integer level values ("absolute levels"). The main terms index
  117888. ** for language-id 0 is allocate values 0-1023. The first prefix index
  117889. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  117890. ** Language 1 indexes are allocated immediately following language 0.
  117891. **
  117892. ** So, for a system with nPrefix prefix indexes configured, the block of
  117893. ** absolute levels that corresponds to language-id iLangid and index
  117894. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  117895. */
  117896. static sqlite3_int64 getAbsoluteLevel(
  117897. Fts3Table *p, /* FTS3 table handle */
  117898. int iLangid, /* Language id */
  117899. int iIndex, /* Index in p->aIndex[] */
  117900. int iLevel /* Level of segments */
  117901. ){
  117902. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  117903. assert( iLangid>=0 );
  117904. assert( p->nIndex>0 );
  117905. assert( iIndex>=0 && iIndex<p->nIndex );
  117906. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  117907. return iBase + iLevel;
  117908. }
  117909. /*
  117910. ** Set *ppStmt to a statement handle that may be used to iterate through
  117911. ** all rows in the %_segdir table, from oldest to newest. If successful,
  117912. ** return SQLITE_OK. If an error occurs while preparing the statement,
  117913. ** return an SQLite error code.
  117914. **
  117915. ** There is only ever one instance of this SQL statement compiled for
  117916. ** each FTS3 table.
  117917. **
  117918. ** The statement returns the following columns from the %_segdir table:
  117919. **
  117920. ** 0: idx
  117921. ** 1: start_block
  117922. ** 2: leaves_end_block
  117923. ** 3: end_block
  117924. ** 4: root
  117925. */
  117926. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  117927. Fts3Table *p, /* FTS3 table */
  117928. int iLangid, /* Language being queried */
  117929. int iIndex, /* Index for p->aIndex[] */
  117930. int iLevel, /* Level to select (relative level) */
  117931. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  117932. ){
  117933. int rc;
  117934. sqlite3_stmt *pStmt = 0;
  117935. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  117936. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  117937. assert( iIndex>=0 && iIndex<p->nIndex );
  117938. if( iLevel<0 ){
  117939. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  117940. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  117941. if( rc==SQLITE_OK ){
  117942. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  117943. sqlite3_bind_int64(pStmt, 2,
  117944. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  117945. );
  117946. }
  117947. }else{
  117948. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  117949. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  117950. if( rc==SQLITE_OK ){
  117951. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  117952. }
  117953. }
  117954. *ppStmt = pStmt;
  117955. return rc;
  117956. }
  117957. /*
  117958. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  117959. ** if successful, or an SQLite error code otherwise.
  117960. **
  117961. ** This function also serves to allocate the PendingList structure itself.
  117962. ** For example, to create a new PendingList structure containing two
  117963. ** varints:
  117964. **
  117965. ** PendingList *p = 0;
  117966. ** fts3PendingListAppendVarint(&p, 1);
  117967. ** fts3PendingListAppendVarint(&p, 2);
  117968. */
  117969. static int fts3PendingListAppendVarint(
  117970. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  117971. sqlite3_int64 i /* Value to append to data */
  117972. ){
  117973. PendingList *p = *pp;
  117974. /* Allocate or grow the PendingList as required. */
  117975. if( !p ){
  117976. p = sqlite3_malloc(sizeof(*p) + 100);
  117977. if( !p ){
  117978. return SQLITE_NOMEM;
  117979. }
  117980. p->nSpace = 100;
  117981. p->aData = (char *)&p[1];
  117982. p->nData = 0;
  117983. }
  117984. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  117985. int nNew = p->nSpace * 2;
  117986. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  117987. if( !p ){
  117988. sqlite3_free(*pp);
  117989. *pp = 0;
  117990. return SQLITE_NOMEM;
  117991. }
  117992. p->nSpace = nNew;
  117993. p->aData = (char *)&p[1];
  117994. }
  117995. /* Append the new serialized varint to the end of the list. */
  117996. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  117997. p->aData[p->nData] = '\0';
  117998. *pp = p;
  117999. return SQLITE_OK;
  118000. }
  118001. /*
  118002. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  118003. ** is returned if the structure is sqlite3_realloced as part of adding
  118004. ** the entry. Otherwise, zero.
  118005. **
  118006. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  118007. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  118008. ** it is set to SQLITE_OK.
  118009. */
  118010. static int fts3PendingListAppend(
  118011. PendingList **pp, /* IN/OUT: PendingList structure */
  118012. sqlite3_int64 iDocid, /* Docid for entry to add */
  118013. sqlite3_int64 iCol, /* Column for entry to add */
  118014. sqlite3_int64 iPos, /* Position of term for entry to add */
  118015. int *pRc /* OUT: Return code */
  118016. ){
  118017. PendingList *p = *pp;
  118018. int rc = SQLITE_OK;
  118019. assert( !p || p->iLastDocid<=iDocid );
  118020. if( !p || p->iLastDocid!=iDocid ){
  118021. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  118022. if( p ){
  118023. assert( p->nData<p->nSpace );
  118024. assert( p->aData[p->nData]==0 );
  118025. p->nData++;
  118026. }
  118027. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  118028. goto pendinglistappend_out;
  118029. }
  118030. p->iLastCol = -1;
  118031. p->iLastPos = 0;
  118032. p->iLastDocid = iDocid;
  118033. }
  118034. if( iCol>0 && p->iLastCol!=iCol ){
  118035. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  118036. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  118037. ){
  118038. goto pendinglistappend_out;
  118039. }
  118040. p->iLastCol = iCol;
  118041. p->iLastPos = 0;
  118042. }
  118043. if( iCol>=0 ){
  118044. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  118045. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  118046. if( rc==SQLITE_OK ){
  118047. p->iLastPos = iPos;
  118048. }
  118049. }
  118050. pendinglistappend_out:
  118051. *pRc = rc;
  118052. if( p!=*pp ){
  118053. *pp = p;
  118054. return 1;
  118055. }
  118056. return 0;
  118057. }
  118058. /*
  118059. ** Free a PendingList object allocated by fts3PendingListAppend().
  118060. */
  118061. static void fts3PendingListDelete(PendingList *pList){
  118062. sqlite3_free(pList);
  118063. }
  118064. /*
  118065. ** Add an entry to one of the pending-terms hash tables.
  118066. */
  118067. static int fts3PendingTermsAddOne(
  118068. Fts3Table *p,
  118069. int iCol,
  118070. int iPos,
  118071. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  118072. const char *zToken,
  118073. int nToken
  118074. ){
  118075. PendingList *pList;
  118076. int rc = SQLITE_OK;
  118077. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  118078. if( pList ){
  118079. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  118080. }
  118081. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  118082. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  118083. /* Malloc failed while inserting the new entry. This can only
  118084. ** happen if there was no previous entry for this token.
  118085. */
  118086. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  118087. sqlite3_free(pList);
  118088. rc = SQLITE_NOMEM;
  118089. }
  118090. }
  118091. if( rc==SQLITE_OK ){
  118092. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  118093. }
  118094. return rc;
  118095. }
  118096. /*
  118097. ** Tokenize the nul-terminated string zText and add all tokens to the
  118098. ** pending-terms hash-table. The docid used is that currently stored in
  118099. ** p->iPrevDocid, and the column is specified by argument iCol.
  118100. **
  118101. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  118102. */
  118103. static int fts3PendingTermsAdd(
  118104. Fts3Table *p, /* Table into which text will be inserted */
  118105. int iLangid, /* Language id to use */
  118106. const char *zText, /* Text of document to be inserted */
  118107. int iCol, /* Column into which text is being inserted */
  118108. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  118109. ){
  118110. int rc;
  118111. int iStart = 0;
  118112. int iEnd = 0;
  118113. int iPos = 0;
  118114. int nWord = 0;
  118115. char const *zToken;
  118116. int nToken = 0;
  118117. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  118118. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  118119. sqlite3_tokenizer_cursor *pCsr;
  118120. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  118121. const char**,int*,int*,int*,int*);
  118122. assert( pTokenizer && pModule );
  118123. /* If the user has inserted a NULL value, this function may be called with
  118124. ** zText==0. In this case, add zero token entries to the hash table and
  118125. ** return early. */
  118126. if( zText==0 ){
  118127. *pnWord = 0;
  118128. return SQLITE_OK;
  118129. }
  118130. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  118131. if( rc!=SQLITE_OK ){
  118132. return rc;
  118133. }
  118134. xNext = pModule->xNext;
  118135. while( SQLITE_OK==rc
  118136. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  118137. ){
  118138. int i;
  118139. if( iPos>=nWord ) nWord = iPos+1;
  118140. /* Positions cannot be negative; we use -1 as a terminator internally.
  118141. ** Tokens must have a non-zero length.
  118142. */
  118143. if( iPos<0 || !zToken || nToken<=0 ){
  118144. rc = SQLITE_ERROR;
  118145. break;
  118146. }
  118147. /* Add the term to the terms index */
  118148. rc = fts3PendingTermsAddOne(
  118149. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  118150. );
  118151. /* Add the term to each of the prefix indexes that it is not too
  118152. ** short for. */
  118153. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  118154. struct Fts3Index *pIndex = &p->aIndex[i];
  118155. if( nToken<pIndex->nPrefix ) continue;
  118156. rc = fts3PendingTermsAddOne(
  118157. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  118158. );
  118159. }
  118160. }
  118161. pModule->xClose(pCsr);
  118162. *pnWord += nWord;
  118163. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  118164. }
  118165. /*
  118166. ** Calling this function indicates that subsequent calls to
  118167. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  118168. ** contents of the document with docid iDocid.
  118169. */
  118170. static int fts3PendingTermsDocid(
  118171. Fts3Table *p, /* Full-text table handle */
  118172. int iLangid, /* Language id of row being written */
  118173. sqlite_int64 iDocid /* Docid of row being written */
  118174. ){
  118175. assert( iLangid>=0 );
  118176. /* TODO(shess) Explore whether partially flushing the buffer on
  118177. ** forced-flush would provide better performance. I suspect that if
  118178. ** we ordered the doclists by size and flushed the largest until the
  118179. ** buffer was half empty, that would let the less frequent terms
  118180. ** generate longer doclists.
  118181. */
  118182. if( iDocid<=p->iPrevDocid
  118183. || p->iPrevLangid!=iLangid
  118184. || p->nPendingData>p->nMaxPendingData
  118185. ){
  118186. int rc = sqlite3Fts3PendingTermsFlush(p);
  118187. if( rc!=SQLITE_OK ) return rc;
  118188. }
  118189. p->iPrevDocid = iDocid;
  118190. p->iPrevLangid = iLangid;
  118191. return SQLITE_OK;
  118192. }
  118193. /*
  118194. ** Discard the contents of the pending-terms hash tables.
  118195. */
  118196. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  118197. int i;
  118198. for(i=0; i<p->nIndex; i++){
  118199. Fts3HashElem *pElem;
  118200. Fts3Hash *pHash = &p->aIndex[i].hPending;
  118201. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  118202. PendingList *pList = (PendingList *)fts3HashData(pElem);
  118203. fts3PendingListDelete(pList);
  118204. }
  118205. fts3HashClear(pHash);
  118206. }
  118207. p->nPendingData = 0;
  118208. }
  118209. /*
  118210. ** This function is called by the xUpdate() method as part of an INSERT
  118211. ** operation. It adds entries for each term in the new record to the
  118212. ** pendingTerms hash table.
  118213. **
  118214. ** Argument apVal is the same as the similarly named argument passed to
  118215. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  118216. */
  118217. static int fts3InsertTerms(
  118218. Fts3Table *p,
  118219. int iLangid,
  118220. sqlite3_value **apVal,
  118221. u32 *aSz
  118222. ){
  118223. int i; /* Iterator variable */
  118224. for(i=2; i<p->nColumn+2; i++){
  118225. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  118226. int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
  118227. if( rc!=SQLITE_OK ){
  118228. return rc;
  118229. }
  118230. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  118231. }
  118232. return SQLITE_OK;
  118233. }
  118234. /*
  118235. ** This function is called by the xUpdate() method for an INSERT operation.
  118236. ** The apVal parameter is passed a copy of the apVal argument passed by
  118237. ** SQLite to the xUpdate() method. i.e:
  118238. **
  118239. ** apVal[0] Not used for INSERT.
  118240. ** apVal[1] rowid
  118241. ** apVal[2] Left-most user-defined column
  118242. ** ...
  118243. ** apVal[p->nColumn+1] Right-most user-defined column
  118244. ** apVal[p->nColumn+2] Hidden column with same name as table
  118245. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  118246. ** apVal[p->nColumn+4] Hidden languageid column
  118247. */
  118248. static int fts3InsertData(
  118249. Fts3Table *p, /* Full-text table */
  118250. sqlite3_value **apVal, /* Array of values to insert */
  118251. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  118252. ){
  118253. int rc; /* Return code */
  118254. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  118255. if( p->zContentTbl ){
  118256. sqlite3_value *pRowid = apVal[p->nColumn+3];
  118257. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  118258. pRowid = apVal[1];
  118259. }
  118260. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  118261. return SQLITE_CONSTRAINT;
  118262. }
  118263. *piDocid = sqlite3_value_int64(pRowid);
  118264. return SQLITE_OK;
  118265. }
  118266. /* Locate the statement handle used to insert data into the %_content
  118267. ** table. The SQL for this statement is:
  118268. **
  118269. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  118270. **
  118271. ** The statement features N '?' variables, where N is the number of user
  118272. ** defined columns in the FTS3 table, plus one for the docid field.
  118273. */
  118274. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  118275. if( rc==SQLITE_OK && p->zLanguageid ){
  118276. rc = sqlite3_bind_int(
  118277. pContentInsert, p->nColumn+2,
  118278. sqlite3_value_int(apVal[p->nColumn+4])
  118279. );
  118280. }
  118281. if( rc!=SQLITE_OK ) return rc;
  118282. /* There is a quirk here. The users INSERT statement may have specified
  118283. ** a value for the "rowid" field, for the "docid" field, or for both.
  118284. ** Which is a problem, since "rowid" and "docid" are aliases for the
  118285. ** same value. For example:
  118286. **
  118287. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  118288. **
  118289. ** In FTS3, this is an error. It is an error to specify non-NULL values
  118290. ** for both docid and some other rowid alias.
  118291. */
  118292. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  118293. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  118294. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  118295. ){
  118296. /* A rowid/docid conflict. */
  118297. return SQLITE_ERROR;
  118298. }
  118299. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  118300. if( rc!=SQLITE_OK ) return rc;
  118301. }
  118302. /* Execute the statement to insert the record. Set *piDocid to the
  118303. ** new docid value.
  118304. */
  118305. sqlite3_step(pContentInsert);
  118306. rc = sqlite3_reset(pContentInsert);
  118307. *piDocid = sqlite3_last_insert_rowid(p->db);
  118308. return rc;
  118309. }
  118310. /*
  118311. ** Remove all data from the FTS3 table. Clear the hash table containing
  118312. ** pending terms.
  118313. */
  118314. static int fts3DeleteAll(Fts3Table *p, int bContent){
  118315. int rc = SQLITE_OK; /* Return code */
  118316. /* Discard the contents of the pending-terms hash table. */
  118317. sqlite3Fts3PendingTermsClear(p);
  118318. /* Delete everything from the shadow tables. Except, leave %_content as
  118319. ** is if bContent is false. */
  118320. assert( p->zContentTbl==0 || bContent==0 );
  118321. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  118322. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  118323. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  118324. if( p->bHasDocsize ){
  118325. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  118326. }
  118327. if( p->bHasStat ){
  118328. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  118329. }
  118330. return rc;
  118331. }
  118332. /*
  118333. **
  118334. */
  118335. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  118336. int iLangid = 0;
  118337. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  118338. return iLangid;
  118339. }
  118340. /*
  118341. ** The first element in the apVal[] array is assumed to contain the docid
  118342. ** (an integer) of a row about to be deleted. Remove all terms from the
  118343. ** full-text index.
  118344. */
  118345. static void fts3DeleteTerms(
  118346. int *pRC, /* Result code */
  118347. Fts3Table *p, /* The FTS table to delete from */
  118348. sqlite3_value *pRowid, /* The docid to be deleted */
  118349. u32 *aSz, /* Sizes of deleted document written here */
  118350. int *pbFound /* OUT: Set to true if row really does exist */
  118351. ){
  118352. int rc;
  118353. sqlite3_stmt *pSelect;
  118354. assert( *pbFound==0 );
  118355. if( *pRC ) return;
  118356. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  118357. if( rc==SQLITE_OK ){
  118358. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  118359. int i;
  118360. int iLangid = langidFromSelect(p, pSelect);
  118361. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  118362. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  118363. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  118364. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
  118365. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  118366. }
  118367. if( rc!=SQLITE_OK ){
  118368. sqlite3_reset(pSelect);
  118369. *pRC = rc;
  118370. return;
  118371. }
  118372. *pbFound = 1;
  118373. }
  118374. rc = sqlite3_reset(pSelect);
  118375. }else{
  118376. sqlite3_reset(pSelect);
  118377. }
  118378. *pRC = rc;
  118379. }
  118380. /*
  118381. ** Forward declaration to account for the circular dependency between
  118382. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  118383. */
  118384. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  118385. /*
  118386. ** This function allocates a new level iLevel index in the segdir table.
  118387. ** Usually, indexes are allocated within a level sequentially starting
  118388. ** with 0, so the allocated index is one greater than the value returned
  118389. ** by:
  118390. **
  118391. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  118392. **
  118393. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  118394. ** level, they are merged into a single level (iLevel+1) segment and the
  118395. ** allocated index is 0.
  118396. **
  118397. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  118398. ** returned. Otherwise, an SQLite error code is returned.
  118399. */
  118400. static int fts3AllocateSegdirIdx(
  118401. Fts3Table *p,
  118402. int iLangid, /* Language id */
  118403. int iIndex, /* Index for p->aIndex */
  118404. int iLevel,
  118405. int *piIdx
  118406. ){
  118407. int rc; /* Return Code */
  118408. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  118409. int iNext = 0; /* Result of query pNextIdx */
  118410. assert( iLangid>=0 );
  118411. assert( p->nIndex>=1 );
  118412. /* Set variable iNext to the next available segdir index at level iLevel. */
  118413. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  118414. if( rc==SQLITE_OK ){
  118415. sqlite3_bind_int64(
  118416. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  118417. );
  118418. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  118419. iNext = sqlite3_column_int(pNextIdx, 0);
  118420. }
  118421. rc = sqlite3_reset(pNextIdx);
  118422. }
  118423. if( rc==SQLITE_OK ){
  118424. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  118425. ** full, merge all segments in level iLevel into a single iLevel+1
  118426. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  118427. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  118428. */
  118429. if( iNext>=FTS3_MERGE_COUNT ){
  118430. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  118431. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  118432. *piIdx = 0;
  118433. }else{
  118434. *piIdx = iNext;
  118435. }
  118436. }
  118437. return rc;
  118438. }
  118439. /*
  118440. ** The %_segments table is declared as follows:
  118441. **
  118442. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  118443. **
  118444. ** This function reads data from a single row of the %_segments table. The
  118445. ** specific row is identified by the iBlockid parameter. If paBlob is not
  118446. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  118447. ** with the contents of the blob stored in the "block" column of the
  118448. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  118449. ** to the size of the blob in bytes before returning.
  118450. **
  118451. ** If an error occurs, or the table does not contain the specified row,
  118452. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  118453. ** paBlob is non-NULL, then it is the responsibility of the caller to
  118454. ** eventually free the returned buffer.
  118455. **
  118456. ** This function may leave an open sqlite3_blob* handle in the
  118457. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  118458. ** to this function. The handle may be closed by calling the
  118459. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  118460. ** performance improvement, but the blob handle should always be closed
  118461. ** before control is returned to the user (to prevent a lock being held
  118462. ** on the database file for longer than necessary). Thus, any virtual table
  118463. ** method (xFilter etc.) that may directly or indirectly call this function
  118464. ** must call sqlite3Fts3SegmentsClose() before returning.
  118465. */
  118466. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  118467. Fts3Table *p, /* FTS3 table handle */
  118468. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  118469. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  118470. int *pnBlob, /* OUT: Size of blob data */
  118471. int *pnLoad /* OUT: Bytes actually loaded */
  118472. ){
  118473. int rc; /* Return code */
  118474. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  118475. assert( pnBlob );
  118476. if( p->pSegments ){
  118477. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  118478. }else{
  118479. if( 0==p->zSegmentsTbl ){
  118480. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  118481. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  118482. }
  118483. rc = sqlite3_blob_open(
  118484. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  118485. );
  118486. }
  118487. if( rc==SQLITE_OK ){
  118488. int nByte = sqlite3_blob_bytes(p->pSegments);
  118489. *pnBlob = nByte;
  118490. if( paBlob ){
  118491. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  118492. if( !aByte ){
  118493. rc = SQLITE_NOMEM;
  118494. }else{
  118495. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  118496. nByte = FTS3_NODE_CHUNKSIZE;
  118497. *pnLoad = nByte;
  118498. }
  118499. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  118500. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  118501. if( rc!=SQLITE_OK ){
  118502. sqlite3_free(aByte);
  118503. aByte = 0;
  118504. }
  118505. }
  118506. *paBlob = aByte;
  118507. }
  118508. }
  118509. return rc;
  118510. }
  118511. /*
  118512. ** Close the blob handle at p->pSegments, if it is open. See comments above
  118513. ** the sqlite3Fts3ReadBlock() function for details.
  118514. */
  118515. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  118516. sqlite3_blob_close(p->pSegments);
  118517. p->pSegments = 0;
  118518. }
  118519. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  118520. int nRead; /* Number of bytes to read */
  118521. int rc; /* Return code */
  118522. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  118523. rc = sqlite3_blob_read(
  118524. pReader->pBlob,
  118525. &pReader->aNode[pReader->nPopulate],
  118526. nRead,
  118527. pReader->nPopulate
  118528. );
  118529. if( rc==SQLITE_OK ){
  118530. pReader->nPopulate += nRead;
  118531. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  118532. if( pReader->nPopulate==pReader->nNode ){
  118533. sqlite3_blob_close(pReader->pBlob);
  118534. pReader->pBlob = 0;
  118535. pReader->nPopulate = 0;
  118536. }
  118537. }
  118538. return rc;
  118539. }
  118540. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  118541. int rc = SQLITE_OK;
  118542. assert( !pReader->pBlob
  118543. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  118544. );
  118545. while( pReader->pBlob && rc==SQLITE_OK
  118546. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  118547. ){
  118548. rc = fts3SegReaderIncrRead(pReader);
  118549. }
  118550. return rc;
  118551. }
  118552. /*
  118553. ** Set an Fts3SegReader cursor to point at EOF.
  118554. */
  118555. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  118556. if( !fts3SegReaderIsRootOnly(pSeg) ){
  118557. sqlite3_free(pSeg->aNode);
  118558. sqlite3_blob_close(pSeg->pBlob);
  118559. pSeg->pBlob = 0;
  118560. }
  118561. pSeg->aNode = 0;
  118562. }
  118563. /*
  118564. ** Move the iterator passed as the first argument to the next term in the
  118565. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  118566. ** SQLITE_DONE. Otherwise, an SQLite error code.
  118567. */
  118568. static int fts3SegReaderNext(
  118569. Fts3Table *p,
  118570. Fts3SegReader *pReader,
  118571. int bIncr
  118572. ){
  118573. int rc; /* Return code of various sub-routines */
  118574. char *pNext; /* Cursor variable */
  118575. int nPrefix; /* Number of bytes in term prefix */
  118576. int nSuffix; /* Number of bytes in term suffix */
  118577. if( !pReader->aDoclist ){
  118578. pNext = pReader->aNode;
  118579. }else{
  118580. pNext = &pReader->aDoclist[pReader->nDoclist];
  118581. }
  118582. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  118583. if( fts3SegReaderIsPending(pReader) ){
  118584. Fts3HashElem *pElem = *(pReader->ppNextElem);
  118585. if( pElem==0 ){
  118586. pReader->aNode = 0;
  118587. }else{
  118588. PendingList *pList = (PendingList *)fts3HashData(pElem);
  118589. pReader->zTerm = (char *)fts3HashKey(pElem);
  118590. pReader->nTerm = fts3HashKeysize(pElem);
  118591. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  118592. pReader->aNode = pReader->aDoclist = pList->aData;
  118593. pReader->ppNextElem++;
  118594. assert( pReader->aNode );
  118595. }
  118596. return SQLITE_OK;
  118597. }
  118598. fts3SegReaderSetEof(pReader);
  118599. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  118600. ** blocks have already been traversed. */
  118601. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  118602. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  118603. return SQLITE_OK;
  118604. }
  118605. rc = sqlite3Fts3ReadBlock(
  118606. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  118607. (bIncr ? &pReader->nPopulate : 0)
  118608. );
  118609. if( rc!=SQLITE_OK ) return rc;
  118610. assert( pReader->pBlob==0 );
  118611. if( bIncr && pReader->nPopulate<pReader->nNode ){
  118612. pReader->pBlob = p->pSegments;
  118613. p->pSegments = 0;
  118614. }
  118615. pNext = pReader->aNode;
  118616. }
  118617. assert( !fts3SegReaderIsPending(pReader) );
  118618. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  118619. if( rc!=SQLITE_OK ) return rc;
  118620. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  118621. ** safe (no risk of overread) even if the node data is corrupted. */
  118622. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  118623. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  118624. if( nPrefix<0 || nSuffix<=0
  118625. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  118626. ){
  118627. return FTS_CORRUPT_VTAB;
  118628. }
  118629. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  118630. int nNew = (nPrefix+nSuffix)*2;
  118631. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  118632. if( !zNew ){
  118633. return SQLITE_NOMEM;
  118634. }
  118635. pReader->zTerm = zNew;
  118636. pReader->nTermAlloc = nNew;
  118637. }
  118638. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  118639. if( rc!=SQLITE_OK ) return rc;
  118640. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  118641. pReader->nTerm = nPrefix+nSuffix;
  118642. pNext += nSuffix;
  118643. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  118644. pReader->aDoclist = pNext;
  118645. pReader->pOffsetList = 0;
  118646. /* Check that the doclist does not appear to extend past the end of the
  118647. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  118648. ** of these statements is untrue, then the data structure is corrupt.
  118649. */
  118650. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  118651. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  118652. ){
  118653. return FTS_CORRUPT_VTAB;
  118654. }
  118655. return SQLITE_OK;
  118656. }
  118657. /*
  118658. ** Set the SegReader to point to the first docid in the doclist associated
  118659. ** with the current term.
  118660. */
  118661. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  118662. int rc = SQLITE_OK;
  118663. assert( pReader->aDoclist );
  118664. assert( !pReader->pOffsetList );
  118665. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  118666. u8 bEof = 0;
  118667. pReader->iDocid = 0;
  118668. pReader->nOffsetList = 0;
  118669. sqlite3Fts3DoclistPrev(0,
  118670. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  118671. &pReader->iDocid, &pReader->nOffsetList, &bEof
  118672. );
  118673. }else{
  118674. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  118675. if( rc==SQLITE_OK ){
  118676. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  118677. pReader->pOffsetList = &pReader->aDoclist[n];
  118678. }
  118679. }
  118680. return rc;
  118681. }
  118682. /*
  118683. ** Advance the SegReader to point to the next docid in the doclist
  118684. ** associated with the current term.
  118685. **
  118686. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  118687. ** *ppOffsetList is set to point to the first column-offset list
  118688. ** in the doclist entry (i.e. immediately past the docid varint).
  118689. ** *pnOffsetList is set to the length of the set of column-offset
  118690. ** lists, not including the nul-terminator byte. For example:
  118691. */
  118692. static int fts3SegReaderNextDocid(
  118693. Fts3Table *pTab,
  118694. Fts3SegReader *pReader, /* Reader to advance to next docid */
  118695. char **ppOffsetList, /* OUT: Pointer to current position-list */
  118696. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  118697. ){
  118698. int rc = SQLITE_OK;
  118699. char *p = pReader->pOffsetList;
  118700. char c = 0;
  118701. assert( p );
  118702. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  118703. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  118704. ** Pending-terms doclists are always built up in ascending order, so
  118705. ** we have to iterate through them backwards here. */
  118706. u8 bEof = 0;
  118707. if( ppOffsetList ){
  118708. *ppOffsetList = pReader->pOffsetList;
  118709. *pnOffsetList = pReader->nOffsetList - 1;
  118710. }
  118711. sqlite3Fts3DoclistPrev(0,
  118712. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  118713. &pReader->nOffsetList, &bEof
  118714. );
  118715. if( bEof ){
  118716. pReader->pOffsetList = 0;
  118717. }else{
  118718. pReader->pOffsetList = p;
  118719. }
  118720. }else{
  118721. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  118722. /* Pointer p currently points at the first byte of an offset list. The
  118723. ** following block advances it to point one byte past the end of
  118724. ** the same offset list. */
  118725. while( 1 ){
  118726. /* The following line of code (and the "p++" below the while() loop) is
  118727. ** normally all that is required to move pointer p to the desired
  118728. ** position. The exception is if this node is being loaded from disk
  118729. ** incrementally and pointer "p" now points to the first byte passed
  118730. ** the populated part of pReader->aNode[].
  118731. */
  118732. while( *p | c ) c = *p++ & 0x80;
  118733. assert( *p==0 );
  118734. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  118735. rc = fts3SegReaderIncrRead(pReader);
  118736. if( rc!=SQLITE_OK ) return rc;
  118737. }
  118738. p++;
  118739. /* If required, populate the output variables with a pointer to and the
  118740. ** size of the previous offset-list.
  118741. */
  118742. if( ppOffsetList ){
  118743. *ppOffsetList = pReader->pOffsetList;
  118744. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  118745. }
  118746. while( p<pEnd && *p==0 ) p++;
  118747. /* If there are no more entries in the doclist, set pOffsetList to
  118748. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  118749. ** Fts3SegReader.pOffsetList to point to the next offset list before
  118750. ** returning.
  118751. */
  118752. if( p>=pEnd ){
  118753. pReader->pOffsetList = 0;
  118754. }else{
  118755. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  118756. if( rc==SQLITE_OK ){
  118757. sqlite3_int64 iDelta;
  118758. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  118759. if( pTab->bDescIdx ){
  118760. pReader->iDocid -= iDelta;
  118761. }else{
  118762. pReader->iDocid += iDelta;
  118763. }
  118764. }
  118765. }
  118766. }
  118767. return SQLITE_OK;
  118768. }
  118769. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  118770. Fts3Cursor *pCsr,
  118771. Fts3MultiSegReader *pMsr,
  118772. int *pnOvfl
  118773. ){
  118774. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  118775. int nOvfl = 0;
  118776. int ii;
  118777. int rc = SQLITE_OK;
  118778. int pgsz = p->nPgsz;
  118779. assert( p->bFts4 );
  118780. assert( pgsz>0 );
  118781. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  118782. Fts3SegReader *pReader = pMsr->apSegment[ii];
  118783. if( !fts3SegReaderIsPending(pReader)
  118784. && !fts3SegReaderIsRootOnly(pReader)
  118785. ){
  118786. sqlite3_int64 jj;
  118787. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  118788. int nBlob;
  118789. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  118790. if( rc!=SQLITE_OK ) break;
  118791. if( (nBlob+35)>pgsz ){
  118792. nOvfl += (nBlob + 34)/pgsz;
  118793. }
  118794. }
  118795. }
  118796. }
  118797. *pnOvfl = nOvfl;
  118798. return rc;
  118799. }
  118800. /*
  118801. ** Free all allocations associated with the iterator passed as the
  118802. ** second argument.
  118803. */
  118804. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  118805. if( pReader && !fts3SegReaderIsPending(pReader) ){
  118806. sqlite3_free(pReader->zTerm);
  118807. if( !fts3SegReaderIsRootOnly(pReader) ){
  118808. sqlite3_free(pReader->aNode);
  118809. sqlite3_blob_close(pReader->pBlob);
  118810. }
  118811. }
  118812. sqlite3_free(pReader);
  118813. }
  118814. /*
  118815. ** Allocate a new SegReader object.
  118816. */
  118817. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  118818. int iAge, /* Segment "age". */
  118819. int bLookup, /* True for a lookup only */
  118820. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  118821. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  118822. sqlite3_int64 iEndBlock, /* Final block of segment */
  118823. const char *zRoot, /* Buffer containing root node */
  118824. int nRoot, /* Size of buffer containing root node */
  118825. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  118826. ){
  118827. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  118828. int nExtra = 0; /* Bytes to allocate segment root node */
  118829. assert( iStartLeaf<=iEndLeaf );
  118830. if( iStartLeaf==0 ){
  118831. nExtra = nRoot + FTS3_NODE_PADDING;
  118832. }
  118833. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  118834. if( !pReader ){
  118835. return SQLITE_NOMEM;
  118836. }
  118837. memset(pReader, 0, sizeof(Fts3SegReader));
  118838. pReader->iIdx = iAge;
  118839. pReader->bLookup = bLookup!=0;
  118840. pReader->iStartBlock = iStartLeaf;
  118841. pReader->iLeafEndBlock = iEndLeaf;
  118842. pReader->iEndBlock = iEndBlock;
  118843. if( nExtra ){
  118844. /* The entire segment is stored in the root node. */
  118845. pReader->aNode = (char *)&pReader[1];
  118846. pReader->rootOnly = 1;
  118847. pReader->nNode = nRoot;
  118848. memcpy(pReader->aNode, zRoot, nRoot);
  118849. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  118850. }else{
  118851. pReader->iCurrentBlock = iStartLeaf-1;
  118852. }
  118853. *ppReader = pReader;
  118854. return SQLITE_OK;
  118855. }
  118856. /*
  118857. ** This is a comparison function used as a qsort() callback when sorting
  118858. ** an array of pending terms by term. This occurs as part of flushing
  118859. ** the contents of the pending-terms hash table to the database.
  118860. */
  118861. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  118862. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  118863. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  118864. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  118865. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  118866. int n = (n1<n2 ? n1 : n2);
  118867. int c = memcmp(z1, z2, n);
  118868. if( c==0 ){
  118869. c = n1 - n2;
  118870. }
  118871. return c;
  118872. }
  118873. /*
  118874. ** This function is used to allocate an Fts3SegReader that iterates through
  118875. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  118876. **
  118877. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  118878. ** through each term in the pending-terms table. Or, if isPrefixIter is
  118879. ** non-zero, it iterates through each term and its prefixes. For example, if
  118880. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  118881. ** "firebird", then the iterator visits the following 'terms' (in the order
  118882. ** shown):
  118883. **
  118884. ** f fi fir fire fireb firebi firebir firebird
  118885. ** m my mys mysq mysql
  118886. ** s sq sql sqli sqlit sqlite
  118887. **
  118888. ** Whereas if isPrefixIter is zero, the terms visited are:
  118889. **
  118890. ** firebird mysql sqlite
  118891. */
  118892. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  118893. Fts3Table *p, /* Virtual table handle */
  118894. int iIndex, /* Index for p->aIndex */
  118895. const char *zTerm, /* Term to search for */
  118896. int nTerm, /* Size of buffer zTerm */
  118897. int bPrefix, /* True for a prefix iterator */
  118898. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  118899. ){
  118900. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  118901. Fts3HashElem *pE; /* Iterator variable */
  118902. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  118903. int nElem = 0; /* Size of array at aElem */
  118904. int rc = SQLITE_OK; /* Return Code */
  118905. Fts3Hash *pHash;
  118906. pHash = &p->aIndex[iIndex].hPending;
  118907. if( bPrefix ){
  118908. int nAlloc = 0; /* Size of allocated array at aElem */
  118909. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  118910. char *zKey = (char *)fts3HashKey(pE);
  118911. int nKey = fts3HashKeysize(pE);
  118912. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  118913. if( nElem==nAlloc ){
  118914. Fts3HashElem **aElem2;
  118915. nAlloc += 16;
  118916. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  118917. aElem, nAlloc*sizeof(Fts3HashElem *)
  118918. );
  118919. if( !aElem2 ){
  118920. rc = SQLITE_NOMEM;
  118921. nElem = 0;
  118922. break;
  118923. }
  118924. aElem = aElem2;
  118925. }
  118926. aElem[nElem++] = pE;
  118927. }
  118928. }
  118929. /* If more than one term matches the prefix, sort the Fts3HashElem
  118930. ** objects in term order using qsort(). This uses the same comparison
  118931. ** callback as is used when flushing terms to disk.
  118932. */
  118933. if( nElem>1 ){
  118934. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  118935. }
  118936. }else{
  118937. /* The query is a simple term lookup that matches at most one term in
  118938. ** the index. All that is required is a straight hash-lookup.
  118939. **
  118940. ** Because the stack address of pE may be accessed via the aElem pointer
  118941. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  118942. ** within this entire function, not just this "else{...}" block.
  118943. */
  118944. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  118945. if( pE ){
  118946. aElem = &pE;
  118947. nElem = 1;
  118948. }
  118949. }
  118950. if( nElem>0 ){
  118951. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  118952. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  118953. if( !pReader ){
  118954. rc = SQLITE_NOMEM;
  118955. }else{
  118956. memset(pReader, 0, nByte);
  118957. pReader->iIdx = 0x7FFFFFFF;
  118958. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  118959. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  118960. }
  118961. }
  118962. if( bPrefix ){
  118963. sqlite3_free(aElem);
  118964. }
  118965. *ppReader = pReader;
  118966. return rc;
  118967. }
  118968. /*
  118969. ** Compare the entries pointed to by two Fts3SegReader structures.
  118970. ** Comparison is as follows:
  118971. **
  118972. ** 1) EOF is greater than not EOF.
  118973. **
  118974. ** 2) The current terms (if any) are compared using memcmp(). If one
  118975. ** term is a prefix of another, the longer term is considered the
  118976. ** larger.
  118977. **
  118978. ** 3) By segment age. An older segment is considered larger.
  118979. */
  118980. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  118981. int rc;
  118982. if( pLhs->aNode && pRhs->aNode ){
  118983. int rc2 = pLhs->nTerm - pRhs->nTerm;
  118984. if( rc2<0 ){
  118985. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  118986. }else{
  118987. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  118988. }
  118989. if( rc==0 ){
  118990. rc = rc2;
  118991. }
  118992. }else{
  118993. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  118994. }
  118995. if( rc==0 ){
  118996. rc = pRhs->iIdx - pLhs->iIdx;
  118997. }
  118998. assert( rc!=0 );
  118999. return rc;
  119000. }
  119001. /*
  119002. ** A different comparison function for SegReader structures. In this
  119003. ** version, it is assumed that each SegReader points to an entry in
  119004. ** a doclist for identical terms. Comparison is made as follows:
  119005. **
  119006. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  119007. **
  119008. ** 2) By current docid.
  119009. **
  119010. ** 3) By segment age. An older segment is considered larger.
  119011. */
  119012. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  119013. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  119014. if( rc==0 ){
  119015. if( pLhs->iDocid==pRhs->iDocid ){
  119016. rc = pRhs->iIdx - pLhs->iIdx;
  119017. }else{
  119018. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  119019. }
  119020. }
  119021. assert( pLhs->aNode && pRhs->aNode );
  119022. return rc;
  119023. }
  119024. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  119025. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  119026. if( rc==0 ){
  119027. if( pLhs->iDocid==pRhs->iDocid ){
  119028. rc = pRhs->iIdx - pLhs->iIdx;
  119029. }else{
  119030. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  119031. }
  119032. }
  119033. assert( pLhs->aNode && pRhs->aNode );
  119034. return rc;
  119035. }
  119036. /*
  119037. ** Compare the term that the Fts3SegReader object passed as the first argument
  119038. ** points to with the term specified by arguments zTerm and nTerm.
  119039. **
  119040. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  119041. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  119042. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  119043. */
  119044. static int fts3SegReaderTermCmp(
  119045. Fts3SegReader *pSeg, /* Segment reader object */
  119046. const char *zTerm, /* Term to compare to */
  119047. int nTerm /* Size of term zTerm in bytes */
  119048. ){
  119049. int res = 0;
  119050. if( pSeg->aNode ){
  119051. if( pSeg->nTerm>nTerm ){
  119052. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  119053. }else{
  119054. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  119055. }
  119056. if( res==0 ){
  119057. res = pSeg->nTerm-nTerm;
  119058. }
  119059. }
  119060. return res;
  119061. }
  119062. /*
  119063. ** Argument apSegment is an array of nSegment elements. It is known that
  119064. ** the final (nSegment-nSuspect) members are already in sorted order
  119065. ** (according to the comparison function provided). This function shuffles
  119066. ** the array around until all entries are in sorted order.
  119067. */
  119068. static void fts3SegReaderSort(
  119069. Fts3SegReader **apSegment, /* Array to sort entries of */
  119070. int nSegment, /* Size of apSegment array */
  119071. int nSuspect, /* Unsorted entry count */
  119072. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  119073. ){
  119074. int i; /* Iterator variable */
  119075. assert( nSuspect<=nSegment );
  119076. if( nSuspect==nSegment ) nSuspect--;
  119077. for(i=nSuspect-1; i>=0; i--){
  119078. int j;
  119079. for(j=i; j<(nSegment-1); j++){
  119080. Fts3SegReader *pTmp;
  119081. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  119082. pTmp = apSegment[j+1];
  119083. apSegment[j+1] = apSegment[j];
  119084. apSegment[j] = pTmp;
  119085. }
  119086. }
  119087. #ifndef NDEBUG
  119088. /* Check that the list really is sorted now. */
  119089. for(i=0; i<(nSuspect-1); i++){
  119090. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  119091. }
  119092. #endif
  119093. }
  119094. /*
  119095. ** Insert a record into the %_segments table.
  119096. */
  119097. static int fts3WriteSegment(
  119098. Fts3Table *p, /* Virtual table handle */
  119099. sqlite3_int64 iBlock, /* Block id for new block */
  119100. char *z, /* Pointer to buffer containing block data */
  119101. int n /* Size of buffer z in bytes */
  119102. ){
  119103. sqlite3_stmt *pStmt;
  119104. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  119105. if( rc==SQLITE_OK ){
  119106. sqlite3_bind_int64(pStmt, 1, iBlock);
  119107. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  119108. sqlite3_step(pStmt);
  119109. rc = sqlite3_reset(pStmt);
  119110. }
  119111. return rc;
  119112. }
  119113. /*
  119114. ** Find the largest relative level number in the table. If successful, set
  119115. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  119116. ** set *pnMax to zero and return an SQLite error code.
  119117. */
  119118. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  119119. int rc;
  119120. int mxLevel = 0;
  119121. sqlite3_stmt *pStmt = 0;
  119122. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  119123. if( rc==SQLITE_OK ){
  119124. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  119125. mxLevel = sqlite3_column_int(pStmt, 0);
  119126. }
  119127. rc = sqlite3_reset(pStmt);
  119128. }
  119129. *pnMax = mxLevel;
  119130. return rc;
  119131. }
  119132. /*
  119133. ** Insert a record into the %_segdir table.
  119134. */
  119135. static int fts3WriteSegdir(
  119136. Fts3Table *p, /* Virtual table handle */
  119137. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  119138. int iIdx, /* Value for "idx" field */
  119139. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  119140. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  119141. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  119142. char *zRoot, /* Blob value for "root" field */
  119143. int nRoot /* Number of bytes in buffer zRoot */
  119144. ){
  119145. sqlite3_stmt *pStmt;
  119146. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  119147. if( rc==SQLITE_OK ){
  119148. sqlite3_bind_int64(pStmt, 1, iLevel);
  119149. sqlite3_bind_int(pStmt, 2, iIdx);
  119150. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  119151. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  119152. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  119153. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  119154. sqlite3_step(pStmt);
  119155. rc = sqlite3_reset(pStmt);
  119156. }
  119157. return rc;
  119158. }
  119159. /*
  119160. ** Return the size of the common prefix (if any) shared by zPrev and
  119161. ** zNext, in bytes. For example,
  119162. **
  119163. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  119164. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  119165. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  119166. */
  119167. static int fts3PrefixCompress(
  119168. const char *zPrev, /* Buffer containing previous term */
  119169. int nPrev, /* Size of buffer zPrev in bytes */
  119170. const char *zNext, /* Buffer containing next term */
  119171. int nNext /* Size of buffer zNext in bytes */
  119172. ){
  119173. int n;
  119174. UNUSED_PARAMETER(nNext);
  119175. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  119176. return n;
  119177. }
  119178. /*
  119179. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  119180. ** (according to memcmp) than the previous term.
  119181. */
  119182. static int fts3NodeAddTerm(
  119183. Fts3Table *p, /* Virtual table handle */
  119184. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  119185. int isCopyTerm, /* True if zTerm/nTerm is transient */
  119186. const char *zTerm, /* Pointer to buffer containing term */
  119187. int nTerm /* Size of term in bytes */
  119188. ){
  119189. SegmentNode *pTree = *ppTree;
  119190. int rc;
  119191. SegmentNode *pNew;
  119192. /* First try to append the term to the current node. Return early if
  119193. ** this is possible.
  119194. */
  119195. if( pTree ){
  119196. int nData = pTree->nData; /* Current size of node in bytes */
  119197. int nReq = nData; /* Required space after adding zTerm */
  119198. int nPrefix; /* Number of bytes of prefix compression */
  119199. int nSuffix; /* Suffix length */
  119200. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  119201. nSuffix = nTerm-nPrefix;
  119202. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  119203. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  119204. if( nReq>p->nNodeSize ){
  119205. /* An unusual case: this is the first term to be added to the node
  119206. ** and the static node buffer (p->nNodeSize bytes) is not large
  119207. ** enough. Use a separately malloced buffer instead This wastes
  119208. ** p->nNodeSize bytes, but since this scenario only comes about when
  119209. ** the database contain two terms that share a prefix of almost 2KB,
  119210. ** this is not expected to be a serious problem.
  119211. */
  119212. assert( pTree->aData==(char *)&pTree[1] );
  119213. pTree->aData = (char *)sqlite3_malloc(nReq);
  119214. if( !pTree->aData ){
  119215. return SQLITE_NOMEM;
  119216. }
  119217. }
  119218. if( pTree->zTerm ){
  119219. /* There is no prefix-length field for first term in a node */
  119220. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  119221. }
  119222. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  119223. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  119224. pTree->nData = nData + nSuffix;
  119225. pTree->nEntry++;
  119226. if( isCopyTerm ){
  119227. if( pTree->nMalloc<nTerm ){
  119228. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  119229. if( !zNew ){
  119230. return SQLITE_NOMEM;
  119231. }
  119232. pTree->nMalloc = nTerm*2;
  119233. pTree->zMalloc = zNew;
  119234. }
  119235. pTree->zTerm = pTree->zMalloc;
  119236. memcpy(pTree->zTerm, zTerm, nTerm);
  119237. pTree->nTerm = nTerm;
  119238. }else{
  119239. pTree->zTerm = (char *)zTerm;
  119240. pTree->nTerm = nTerm;
  119241. }
  119242. return SQLITE_OK;
  119243. }
  119244. }
  119245. /* If control flows to here, it was not possible to append zTerm to the
  119246. ** current node. Create a new node (a right-sibling of the current node).
  119247. ** If this is the first node in the tree, the term is added to it.
  119248. **
  119249. ** Otherwise, the term is not added to the new node, it is left empty for
  119250. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  119251. ** has no parent, one is created here.
  119252. */
  119253. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  119254. if( !pNew ){
  119255. return SQLITE_NOMEM;
  119256. }
  119257. memset(pNew, 0, sizeof(SegmentNode));
  119258. pNew->nData = 1 + FTS3_VARINT_MAX;
  119259. pNew->aData = (char *)&pNew[1];
  119260. if( pTree ){
  119261. SegmentNode *pParent = pTree->pParent;
  119262. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  119263. if( pTree->pParent==0 ){
  119264. pTree->pParent = pParent;
  119265. }
  119266. pTree->pRight = pNew;
  119267. pNew->pLeftmost = pTree->pLeftmost;
  119268. pNew->pParent = pParent;
  119269. pNew->zMalloc = pTree->zMalloc;
  119270. pNew->nMalloc = pTree->nMalloc;
  119271. pTree->zMalloc = 0;
  119272. }else{
  119273. pNew->pLeftmost = pNew;
  119274. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  119275. }
  119276. *ppTree = pNew;
  119277. return rc;
  119278. }
  119279. /*
  119280. ** Helper function for fts3NodeWrite().
  119281. */
  119282. static int fts3TreeFinishNode(
  119283. SegmentNode *pTree,
  119284. int iHeight,
  119285. sqlite3_int64 iLeftChild
  119286. ){
  119287. int nStart;
  119288. assert( iHeight>=1 && iHeight<128 );
  119289. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  119290. pTree->aData[nStart] = (char)iHeight;
  119291. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  119292. return nStart;
  119293. }
  119294. /*
  119295. ** Write the buffer for the segment node pTree and all of its peers to the
  119296. ** database. Then call this function recursively to write the parent of
  119297. ** pTree and its peers to the database.
  119298. **
  119299. ** Except, if pTree is a root node, do not write it to the database. Instead,
  119300. ** set output variables *paRoot and *pnRoot to contain the root node.
  119301. **
  119302. ** If successful, SQLITE_OK is returned and output variable *piLast is
  119303. ** set to the largest blockid written to the database (or zero if no
  119304. ** blocks were written to the db). Otherwise, an SQLite error code is
  119305. ** returned.
  119306. */
  119307. static int fts3NodeWrite(
  119308. Fts3Table *p, /* Virtual table handle */
  119309. SegmentNode *pTree, /* SegmentNode handle */
  119310. int iHeight, /* Height of this node in tree */
  119311. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  119312. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  119313. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  119314. char **paRoot, /* OUT: Data for root node */
  119315. int *pnRoot /* OUT: Size of root node in bytes */
  119316. ){
  119317. int rc = SQLITE_OK;
  119318. if( !pTree->pParent ){
  119319. /* Root node of the tree. */
  119320. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  119321. *piLast = iFree-1;
  119322. *pnRoot = pTree->nData - nStart;
  119323. *paRoot = &pTree->aData[nStart];
  119324. }else{
  119325. SegmentNode *pIter;
  119326. sqlite3_int64 iNextFree = iFree;
  119327. sqlite3_int64 iNextLeaf = iLeaf;
  119328. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  119329. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  119330. int nWrite = pIter->nData - nStart;
  119331. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  119332. iNextFree++;
  119333. iNextLeaf += (pIter->nEntry+1);
  119334. }
  119335. if( rc==SQLITE_OK ){
  119336. assert( iNextLeaf==iFree );
  119337. rc = fts3NodeWrite(
  119338. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  119339. );
  119340. }
  119341. }
  119342. return rc;
  119343. }
  119344. /*
  119345. ** Free all memory allocations associated with the tree pTree.
  119346. */
  119347. static void fts3NodeFree(SegmentNode *pTree){
  119348. if( pTree ){
  119349. SegmentNode *p = pTree->pLeftmost;
  119350. fts3NodeFree(p->pParent);
  119351. while( p ){
  119352. SegmentNode *pRight = p->pRight;
  119353. if( p->aData!=(char *)&p[1] ){
  119354. sqlite3_free(p->aData);
  119355. }
  119356. assert( pRight==0 || p->zMalloc==0 );
  119357. sqlite3_free(p->zMalloc);
  119358. sqlite3_free(p);
  119359. p = pRight;
  119360. }
  119361. }
  119362. }
  119363. /*
  119364. ** Add a term to the segment being constructed by the SegmentWriter object
  119365. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  119366. ** be passed NULL. This function will allocate a new SegmentWriter object
  119367. ** and return it via the input/output variable *ppWriter in this case.
  119368. **
  119369. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  119370. */
  119371. static int fts3SegWriterAdd(
  119372. Fts3Table *p, /* Virtual table handle */
  119373. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  119374. int isCopyTerm, /* True if buffer zTerm must be copied */
  119375. const char *zTerm, /* Pointer to buffer containing term */
  119376. int nTerm, /* Size of term in bytes */
  119377. const char *aDoclist, /* Pointer to buffer containing doclist */
  119378. int nDoclist /* Size of doclist in bytes */
  119379. ){
  119380. int nPrefix; /* Size of term prefix in bytes */
  119381. int nSuffix; /* Size of term suffix in bytes */
  119382. int nReq; /* Number of bytes required on leaf page */
  119383. int nData;
  119384. SegmentWriter *pWriter = *ppWriter;
  119385. if( !pWriter ){
  119386. int rc;
  119387. sqlite3_stmt *pStmt;
  119388. /* Allocate the SegmentWriter structure */
  119389. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  119390. if( !pWriter ) return SQLITE_NOMEM;
  119391. memset(pWriter, 0, sizeof(SegmentWriter));
  119392. *ppWriter = pWriter;
  119393. /* Allocate a buffer in which to accumulate data */
  119394. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  119395. if( !pWriter->aData ) return SQLITE_NOMEM;
  119396. pWriter->nSize = p->nNodeSize;
  119397. /* Find the next free blockid in the %_segments table */
  119398. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  119399. if( rc!=SQLITE_OK ) return rc;
  119400. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  119401. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  119402. pWriter->iFirst = pWriter->iFree;
  119403. }
  119404. rc = sqlite3_reset(pStmt);
  119405. if( rc!=SQLITE_OK ) return rc;
  119406. }
  119407. nData = pWriter->nData;
  119408. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  119409. nSuffix = nTerm-nPrefix;
  119410. /* Figure out how many bytes are required by this new entry */
  119411. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  119412. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  119413. nSuffix + /* Term suffix */
  119414. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  119415. nDoclist; /* Doclist data */
  119416. if( nData>0 && nData+nReq>p->nNodeSize ){
  119417. int rc;
  119418. /* The current leaf node is full. Write it out to the database. */
  119419. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  119420. if( rc!=SQLITE_OK ) return rc;
  119421. p->nLeafAdd++;
  119422. /* Add the current term to the interior node tree. The term added to
  119423. ** the interior tree must:
  119424. **
  119425. ** a) be greater than the largest term on the leaf node just written
  119426. ** to the database (still available in pWriter->zTerm), and
  119427. **
  119428. ** b) be less than or equal to the term about to be added to the new
  119429. ** leaf node (zTerm/nTerm).
  119430. **
  119431. ** In other words, it must be the prefix of zTerm 1 byte longer than
  119432. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  119433. */
  119434. assert( nPrefix<nTerm );
  119435. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  119436. if( rc!=SQLITE_OK ) return rc;
  119437. nData = 0;
  119438. pWriter->nTerm = 0;
  119439. nPrefix = 0;
  119440. nSuffix = nTerm;
  119441. nReq = 1 + /* varint containing prefix size */
  119442. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  119443. nTerm + /* Term suffix */
  119444. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  119445. nDoclist; /* Doclist data */
  119446. }
  119447. /* If the buffer currently allocated is too small for this entry, realloc
  119448. ** the buffer to make it large enough.
  119449. */
  119450. if( nReq>pWriter->nSize ){
  119451. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  119452. if( !aNew ) return SQLITE_NOMEM;
  119453. pWriter->aData = aNew;
  119454. pWriter->nSize = nReq;
  119455. }
  119456. assert( nData+nReq<=pWriter->nSize );
  119457. /* Append the prefix-compressed term and doclist to the buffer. */
  119458. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  119459. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  119460. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  119461. nData += nSuffix;
  119462. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  119463. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  119464. pWriter->nData = nData + nDoclist;
  119465. /* Save the current term so that it can be used to prefix-compress the next.
  119466. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  119467. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  119468. ** store a copy of the pointer.
  119469. */
  119470. if( isCopyTerm ){
  119471. if( nTerm>pWriter->nMalloc ){
  119472. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  119473. if( !zNew ){
  119474. return SQLITE_NOMEM;
  119475. }
  119476. pWriter->nMalloc = nTerm*2;
  119477. pWriter->zMalloc = zNew;
  119478. pWriter->zTerm = zNew;
  119479. }
  119480. assert( pWriter->zTerm==pWriter->zMalloc );
  119481. memcpy(pWriter->zTerm, zTerm, nTerm);
  119482. }else{
  119483. pWriter->zTerm = (char *)zTerm;
  119484. }
  119485. pWriter->nTerm = nTerm;
  119486. return SQLITE_OK;
  119487. }
  119488. /*
  119489. ** Flush all data associated with the SegmentWriter object pWriter to the
  119490. ** database. This function must be called after all terms have been added
  119491. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  119492. ** returned. Otherwise, an SQLite error code.
  119493. */
  119494. static int fts3SegWriterFlush(
  119495. Fts3Table *p, /* Virtual table handle */
  119496. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  119497. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  119498. int iIdx /* Value for 'idx' column of %_segdir */
  119499. ){
  119500. int rc; /* Return code */
  119501. if( pWriter->pTree ){
  119502. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  119503. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  119504. char *zRoot = NULL; /* Pointer to buffer containing root node */
  119505. int nRoot = 0; /* Size of buffer zRoot */
  119506. iLastLeaf = pWriter->iFree;
  119507. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  119508. if( rc==SQLITE_OK ){
  119509. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  119510. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  119511. }
  119512. if( rc==SQLITE_OK ){
  119513. rc = fts3WriteSegdir(
  119514. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  119515. }
  119516. }else{
  119517. /* The entire tree fits on the root node. Write it to the segdir table. */
  119518. rc = fts3WriteSegdir(
  119519. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  119520. }
  119521. p->nLeafAdd++;
  119522. return rc;
  119523. }
  119524. /*
  119525. ** Release all memory held by the SegmentWriter object passed as the
  119526. ** first argument.
  119527. */
  119528. static void fts3SegWriterFree(SegmentWriter *pWriter){
  119529. if( pWriter ){
  119530. sqlite3_free(pWriter->aData);
  119531. sqlite3_free(pWriter->zMalloc);
  119532. fts3NodeFree(pWriter->pTree);
  119533. sqlite3_free(pWriter);
  119534. }
  119535. }
  119536. /*
  119537. ** The first value in the apVal[] array is assumed to contain an integer.
  119538. ** This function tests if there exist any documents with docid values that
  119539. ** are different from that integer. i.e. if deleting the document with docid
  119540. ** pRowid would mean the FTS3 table were empty.
  119541. **
  119542. ** If successful, *pisEmpty is set to true if the table is empty except for
  119543. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  119544. ** error occurs, an SQLite error code is returned.
  119545. */
  119546. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  119547. sqlite3_stmt *pStmt;
  119548. int rc;
  119549. if( p->zContentTbl ){
  119550. /* If using the content=xxx option, assume the table is never empty */
  119551. *pisEmpty = 0;
  119552. rc = SQLITE_OK;
  119553. }else{
  119554. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  119555. if( rc==SQLITE_OK ){
  119556. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  119557. *pisEmpty = sqlite3_column_int(pStmt, 0);
  119558. }
  119559. rc = sqlite3_reset(pStmt);
  119560. }
  119561. }
  119562. return rc;
  119563. }
  119564. /*
  119565. ** Set *pnMax to the largest segment level in the database for the index
  119566. ** iIndex.
  119567. **
  119568. ** Segment levels are stored in the 'level' column of the %_segdir table.
  119569. **
  119570. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  119571. */
  119572. static int fts3SegmentMaxLevel(
  119573. Fts3Table *p,
  119574. int iLangid,
  119575. int iIndex,
  119576. sqlite3_int64 *pnMax
  119577. ){
  119578. sqlite3_stmt *pStmt;
  119579. int rc;
  119580. assert( iIndex>=0 && iIndex<p->nIndex );
  119581. /* Set pStmt to the compiled version of:
  119582. **
  119583. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  119584. **
  119585. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  119586. */
  119587. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  119588. if( rc!=SQLITE_OK ) return rc;
  119589. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  119590. sqlite3_bind_int64(pStmt, 2,
  119591. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  119592. );
  119593. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  119594. *pnMax = sqlite3_column_int64(pStmt, 0);
  119595. }
  119596. return sqlite3_reset(pStmt);
  119597. }
  119598. /*
  119599. ** Delete all entries in the %_segments table associated with the segment
  119600. ** opened with seg-reader pSeg. This function does not affect the contents
  119601. ** of the %_segdir table.
  119602. */
  119603. static int fts3DeleteSegment(
  119604. Fts3Table *p, /* FTS table handle */
  119605. Fts3SegReader *pSeg /* Segment to delete */
  119606. ){
  119607. int rc = SQLITE_OK; /* Return code */
  119608. if( pSeg->iStartBlock ){
  119609. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  119610. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  119611. if( rc==SQLITE_OK ){
  119612. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  119613. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  119614. sqlite3_step(pDelete);
  119615. rc = sqlite3_reset(pDelete);
  119616. }
  119617. }
  119618. return rc;
  119619. }
  119620. /*
  119621. ** This function is used after merging multiple segments into a single large
  119622. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  119623. ** it:
  119624. **
  119625. ** 1) Deletes all %_segments entries for the segments associated with
  119626. ** each of the SegReader objects in the array passed as the third
  119627. ** argument, and
  119628. **
  119629. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  119630. ** entries regardless of level if (iLevel<0).
  119631. **
  119632. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  119633. */
  119634. static int fts3DeleteSegdir(
  119635. Fts3Table *p, /* Virtual table handle */
  119636. int iLangid, /* Language id */
  119637. int iIndex, /* Index for p->aIndex */
  119638. int iLevel, /* Level of %_segdir entries to delete */
  119639. Fts3SegReader **apSegment, /* Array of SegReader objects */
  119640. int nReader /* Size of array apSegment */
  119641. ){
  119642. int rc = SQLITE_OK; /* Return Code */
  119643. int i; /* Iterator variable */
  119644. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  119645. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  119646. rc = fts3DeleteSegment(p, apSegment[i]);
  119647. }
  119648. if( rc!=SQLITE_OK ){
  119649. return rc;
  119650. }
  119651. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  119652. if( iLevel==FTS3_SEGCURSOR_ALL ){
  119653. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  119654. if( rc==SQLITE_OK ){
  119655. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  119656. sqlite3_bind_int64(pDelete, 2,
  119657. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  119658. );
  119659. }
  119660. }else{
  119661. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  119662. if( rc==SQLITE_OK ){
  119663. sqlite3_bind_int64(
  119664. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  119665. );
  119666. }
  119667. }
  119668. if( rc==SQLITE_OK ){
  119669. sqlite3_step(pDelete);
  119670. rc = sqlite3_reset(pDelete);
  119671. }
  119672. return rc;
  119673. }
  119674. /*
  119675. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  119676. ** a position list that may (or may not) feature multiple columns. This
  119677. ** function adjusts the pointer *ppList and the length *pnList so that they
  119678. ** identify the subset of the position list that corresponds to column iCol.
  119679. **
  119680. ** If there are no entries in the input position list for column iCol, then
  119681. ** *pnList is set to zero before returning.
  119682. */
  119683. static void fts3ColumnFilter(
  119684. int iCol, /* Column to filter on */
  119685. char **ppList, /* IN/OUT: Pointer to position list */
  119686. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  119687. ){
  119688. char *pList = *ppList;
  119689. int nList = *pnList;
  119690. char *pEnd = &pList[nList];
  119691. int iCurrent = 0;
  119692. char *p = pList;
  119693. assert( iCol>=0 );
  119694. while( 1 ){
  119695. char c = 0;
  119696. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  119697. if( iCol==iCurrent ){
  119698. nList = (int)(p - pList);
  119699. break;
  119700. }
  119701. nList -= (int)(p - pList);
  119702. pList = p;
  119703. if( nList==0 ){
  119704. break;
  119705. }
  119706. p = &pList[1];
  119707. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  119708. }
  119709. *ppList = pList;
  119710. *pnList = nList;
  119711. }
  119712. /*
  119713. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  119714. ** existing data). Grow the buffer if required.
  119715. **
  119716. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  119717. ** trying to resize the buffer, return SQLITE_NOMEM.
  119718. */
  119719. static int fts3MsrBufferData(
  119720. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  119721. char *pList,
  119722. int nList
  119723. ){
  119724. if( nList>pMsr->nBuffer ){
  119725. char *pNew;
  119726. pMsr->nBuffer = nList*2;
  119727. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  119728. if( !pNew ) return SQLITE_NOMEM;
  119729. pMsr->aBuffer = pNew;
  119730. }
  119731. memcpy(pMsr->aBuffer, pList, nList);
  119732. return SQLITE_OK;
  119733. }
  119734. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  119735. Fts3Table *p, /* Virtual table handle */
  119736. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  119737. sqlite3_int64 *piDocid, /* OUT: Docid value */
  119738. char **paPoslist, /* OUT: Pointer to position list */
  119739. int *pnPoslist /* OUT: Size of position list in bytes */
  119740. ){
  119741. int nMerge = pMsr->nAdvance;
  119742. Fts3SegReader **apSegment = pMsr->apSegment;
  119743. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  119744. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  119745. );
  119746. if( nMerge==0 ){
  119747. *paPoslist = 0;
  119748. return SQLITE_OK;
  119749. }
  119750. while( 1 ){
  119751. Fts3SegReader *pSeg;
  119752. pSeg = pMsr->apSegment[0];
  119753. if( pSeg->pOffsetList==0 ){
  119754. *paPoslist = 0;
  119755. break;
  119756. }else{
  119757. int rc;
  119758. char *pList;
  119759. int nList;
  119760. int j;
  119761. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  119762. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  119763. j = 1;
  119764. while( rc==SQLITE_OK
  119765. && j<nMerge
  119766. && apSegment[j]->pOffsetList
  119767. && apSegment[j]->iDocid==iDocid
  119768. ){
  119769. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  119770. j++;
  119771. }
  119772. if( rc!=SQLITE_OK ) return rc;
  119773. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  119774. if( pMsr->iColFilter>=0 ){
  119775. fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
  119776. }
  119777. if( nList>0 ){
  119778. if( fts3SegReaderIsPending(apSegment[0]) ){
  119779. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  119780. if( rc!=SQLITE_OK ) return rc;
  119781. *paPoslist = pMsr->aBuffer;
  119782. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  119783. }else{
  119784. *paPoslist = pList;
  119785. }
  119786. *piDocid = iDocid;
  119787. *pnPoslist = nList;
  119788. break;
  119789. }
  119790. }
  119791. }
  119792. return SQLITE_OK;
  119793. }
  119794. static int fts3SegReaderStart(
  119795. Fts3Table *p, /* Virtual table handle */
  119796. Fts3MultiSegReader *pCsr, /* Cursor object */
  119797. const char *zTerm, /* Term searched for (or NULL) */
  119798. int nTerm /* Length of zTerm in bytes */
  119799. ){
  119800. int i;
  119801. int nSeg = pCsr->nSegment;
  119802. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  119803. ** for, then advance each segment iterator until it points to a term of
  119804. ** equal or greater value than the specified term. This prevents many
  119805. ** unnecessary merge/sort operations for the case where single segment
  119806. ** b-tree leaf nodes contain more than one term.
  119807. */
  119808. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  119809. int res = 0;
  119810. Fts3SegReader *pSeg = pCsr->apSegment[i];
  119811. do {
  119812. int rc = fts3SegReaderNext(p, pSeg, 0);
  119813. if( rc!=SQLITE_OK ) return rc;
  119814. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  119815. if( pSeg->bLookup && res!=0 ){
  119816. fts3SegReaderSetEof(pSeg);
  119817. }
  119818. }
  119819. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  119820. return SQLITE_OK;
  119821. }
  119822. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  119823. Fts3Table *p, /* Virtual table handle */
  119824. Fts3MultiSegReader *pCsr, /* Cursor object */
  119825. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  119826. ){
  119827. pCsr->pFilter = pFilter;
  119828. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  119829. }
  119830. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  119831. Fts3Table *p, /* Virtual table handle */
  119832. Fts3MultiSegReader *pCsr, /* Cursor object */
  119833. int iCol, /* Column to match on. */
  119834. const char *zTerm, /* Term to iterate through a doclist for */
  119835. int nTerm /* Number of bytes in zTerm */
  119836. ){
  119837. int i;
  119838. int rc;
  119839. int nSegment = pCsr->nSegment;
  119840. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  119841. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  119842. );
  119843. assert( pCsr->pFilter==0 );
  119844. assert( zTerm && nTerm>0 );
  119845. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  119846. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  119847. if( rc!=SQLITE_OK ) return rc;
  119848. /* Determine how many of the segments actually point to zTerm/nTerm. */
  119849. for(i=0; i<nSegment; i++){
  119850. Fts3SegReader *pSeg = pCsr->apSegment[i];
  119851. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  119852. break;
  119853. }
  119854. }
  119855. pCsr->nAdvance = i;
  119856. /* Advance each of the segments to point to the first docid. */
  119857. for(i=0; i<pCsr->nAdvance; i++){
  119858. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  119859. if( rc!=SQLITE_OK ) return rc;
  119860. }
  119861. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  119862. assert( iCol<0 || iCol<p->nColumn );
  119863. pCsr->iColFilter = iCol;
  119864. return SQLITE_OK;
  119865. }
  119866. /*
  119867. ** This function is called on a MultiSegReader that has been started using
  119868. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  119869. ** have been made. Calling this function puts the MultiSegReader in such
  119870. ** a state that if the next two calls are:
  119871. **
  119872. ** sqlite3Fts3SegReaderStart()
  119873. ** sqlite3Fts3SegReaderStep()
  119874. **
  119875. ** then the entire doclist for the term is available in
  119876. ** MultiSegReader.aDoclist/nDoclist.
  119877. */
  119878. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  119879. int i; /* Used to iterate through segment-readers */
  119880. assert( pCsr->zTerm==0 );
  119881. assert( pCsr->nTerm==0 );
  119882. assert( pCsr->aDoclist==0 );
  119883. assert( pCsr->nDoclist==0 );
  119884. pCsr->nAdvance = 0;
  119885. pCsr->bRestart = 1;
  119886. for(i=0; i<pCsr->nSegment; i++){
  119887. pCsr->apSegment[i]->pOffsetList = 0;
  119888. pCsr->apSegment[i]->nOffsetList = 0;
  119889. pCsr->apSegment[i]->iDocid = 0;
  119890. }
  119891. return SQLITE_OK;
  119892. }
  119893. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  119894. Fts3Table *p, /* Virtual table handle */
  119895. Fts3MultiSegReader *pCsr /* Cursor object */
  119896. ){
  119897. int rc = SQLITE_OK;
  119898. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  119899. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  119900. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  119901. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  119902. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  119903. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  119904. Fts3SegReader **apSegment = pCsr->apSegment;
  119905. int nSegment = pCsr->nSegment;
  119906. Fts3SegFilter *pFilter = pCsr->pFilter;
  119907. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  119908. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  119909. );
  119910. if( pCsr->nSegment==0 ) return SQLITE_OK;
  119911. do {
  119912. int nMerge;
  119913. int i;
  119914. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  119915. ** forward. Then sort the list in order of current term again.
  119916. */
  119917. for(i=0; i<pCsr->nAdvance; i++){
  119918. Fts3SegReader *pSeg = apSegment[i];
  119919. if( pSeg->bLookup ){
  119920. fts3SegReaderSetEof(pSeg);
  119921. }else{
  119922. rc = fts3SegReaderNext(p, pSeg, 0);
  119923. }
  119924. if( rc!=SQLITE_OK ) return rc;
  119925. }
  119926. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  119927. pCsr->nAdvance = 0;
  119928. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  119929. assert( rc==SQLITE_OK );
  119930. if( apSegment[0]->aNode==0 ) break;
  119931. pCsr->nTerm = apSegment[0]->nTerm;
  119932. pCsr->zTerm = apSegment[0]->zTerm;
  119933. /* If this is a prefix-search, and if the term that apSegment[0] points
  119934. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  119935. ** required callbacks have been made. In this case exit early.
  119936. **
  119937. ** Similarly, if this is a search for an exact match, and the first term
  119938. ** of segment apSegment[0] is not a match, exit early.
  119939. */
  119940. if( pFilter->zTerm && !isScan ){
  119941. if( pCsr->nTerm<pFilter->nTerm
  119942. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  119943. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  119944. ){
  119945. break;
  119946. }
  119947. }
  119948. nMerge = 1;
  119949. while( nMerge<nSegment
  119950. && apSegment[nMerge]->aNode
  119951. && apSegment[nMerge]->nTerm==pCsr->nTerm
  119952. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  119953. ){
  119954. nMerge++;
  119955. }
  119956. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  119957. if( nMerge==1
  119958. && !isIgnoreEmpty
  119959. && !isFirst
  119960. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  119961. ){
  119962. pCsr->nDoclist = apSegment[0]->nDoclist;
  119963. if( fts3SegReaderIsPending(apSegment[0]) ){
  119964. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  119965. pCsr->aDoclist = pCsr->aBuffer;
  119966. }else{
  119967. pCsr->aDoclist = apSegment[0]->aDoclist;
  119968. }
  119969. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  119970. }else{
  119971. int nDoclist = 0; /* Size of doclist */
  119972. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  119973. /* The current term of the first nMerge entries in the array
  119974. ** of Fts3SegReader objects is the same. The doclists must be merged
  119975. ** and a single term returned with the merged doclist.
  119976. */
  119977. for(i=0; i<nMerge; i++){
  119978. fts3SegReaderFirstDocid(p, apSegment[i]);
  119979. }
  119980. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  119981. while( apSegment[0]->pOffsetList ){
  119982. int j; /* Number of segments that share a docid */
  119983. char *pList;
  119984. int nList;
  119985. int nByte;
  119986. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  119987. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  119988. j = 1;
  119989. while( j<nMerge
  119990. && apSegment[j]->pOffsetList
  119991. && apSegment[j]->iDocid==iDocid
  119992. ){
  119993. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  119994. j++;
  119995. }
  119996. if( isColFilter ){
  119997. fts3ColumnFilter(pFilter->iCol, &pList, &nList);
  119998. }
  119999. if( !isIgnoreEmpty || nList>0 ){
  120000. /* Calculate the 'docid' delta value to write into the merged
  120001. ** doclist. */
  120002. sqlite3_int64 iDelta;
  120003. if( p->bDescIdx && nDoclist>0 ){
  120004. iDelta = iPrev - iDocid;
  120005. }else{
  120006. iDelta = iDocid - iPrev;
  120007. }
  120008. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  120009. assert( nDoclist>0 || iDelta==iDocid );
  120010. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  120011. if( nDoclist+nByte>pCsr->nBuffer ){
  120012. char *aNew;
  120013. pCsr->nBuffer = (nDoclist+nByte)*2;
  120014. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  120015. if( !aNew ){
  120016. return SQLITE_NOMEM;
  120017. }
  120018. pCsr->aBuffer = aNew;
  120019. }
  120020. if( isFirst ){
  120021. char *a = &pCsr->aBuffer[nDoclist];
  120022. int nWrite;
  120023. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  120024. if( nWrite ){
  120025. iPrev = iDocid;
  120026. nDoclist += nWrite;
  120027. }
  120028. }else{
  120029. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  120030. iPrev = iDocid;
  120031. if( isRequirePos ){
  120032. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  120033. nDoclist += nList;
  120034. pCsr->aBuffer[nDoclist++] = '\0';
  120035. }
  120036. }
  120037. }
  120038. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  120039. }
  120040. if( nDoclist>0 ){
  120041. pCsr->aDoclist = pCsr->aBuffer;
  120042. pCsr->nDoclist = nDoclist;
  120043. rc = SQLITE_ROW;
  120044. }
  120045. }
  120046. pCsr->nAdvance = nMerge;
  120047. }while( rc==SQLITE_OK );
  120048. return rc;
  120049. }
  120050. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  120051. Fts3MultiSegReader *pCsr /* Cursor object */
  120052. ){
  120053. if( pCsr ){
  120054. int i;
  120055. for(i=0; i<pCsr->nSegment; i++){
  120056. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  120057. }
  120058. sqlite3_free(pCsr->apSegment);
  120059. sqlite3_free(pCsr->aBuffer);
  120060. pCsr->nSegment = 0;
  120061. pCsr->apSegment = 0;
  120062. pCsr->aBuffer = 0;
  120063. }
  120064. }
  120065. /*
  120066. ** Merge all level iLevel segments in the database into a single
  120067. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  120068. ** single segment with a level equal to the numerically largest level
  120069. ** currently present in the database.
  120070. **
  120071. ** If this function is called with iLevel<0, but there is only one
  120072. ** segment in the database, SQLITE_DONE is returned immediately.
  120073. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  120074. ** an SQLite error code is returned.
  120075. */
  120076. static int fts3SegmentMerge(
  120077. Fts3Table *p,
  120078. int iLangid, /* Language id to merge */
  120079. int iIndex, /* Index in p->aIndex[] to merge */
  120080. int iLevel /* Level to merge */
  120081. ){
  120082. int rc; /* Return code */
  120083. int iIdx = 0; /* Index of new segment */
  120084. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  120085. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  120086. Fts3SegFilter filter; /* Segment term filter condition */
  120087. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  120088. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  120089. assert( iLevel==FTS3_SEGCURSOR_ALL
  120090. || iLevel==FTS3_SEGCURSOR_PENDING
  120091. || iLevel>=0
  120092. );
  120093. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  120094. assert( iIndex>=0 && iIndex<p->nIndex );
  120095. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  120096. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  120097. if( iLevel==FTS3_SEGCURSOR_ALL ){
  120098. /* This call is to merge all segments in the database to a single
  120099. ** segment. The level of the new segment is equal to the numerically
  120100. ** greatest segment level currently present in the database for this
  120101. ** index. The idx of the new segment is always 0. */
  120102. if( csr.nSegment==1 ){
  120103. rc = SQLITE_DONE;
  120104. goto finished;
  120105. }
  120106. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  120107. bIgnoreEmpty = 1;
  120108. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  120109. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  120110. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  120111. }else{
  120112. /* This call is to merge all segments at level iLevel. find the next
  120113. ** available segment index at level iLevel+1. The call to
  120114. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  120115. ** a single iLevel+2 segment if necessary. */
  120116. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  120117. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  120118. }
  120119. if( rc!=SQLITE_OK ) goto finished;
  120120. assert( csr.nSegment>0 );
  120121. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  120122. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  120123. memset(&filter, 0, sizeof(Fts3SegFilter));
  120124. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  120125. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  120126. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  120127. while( SQLITE_OK==rc ){
  120128. rc = sqlite3Fts3SegReaderStep(p, &csr);
  120129. if( rc!=SQLITE_ROW ) break;
  120130. rc = fts3SegWriterAdd(p, &pWriter, 1,
  120131. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  120132. }
  120133. if( rc!=SQLITE_OK ) goto finished;
  120134. assert( pWriter );
  120135. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  120136. rc = fts3DeleteSegdir(
  120137. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  120138. );
  120139. if( rc!=SQLITE_OK ) goto finished;
  120140. }
  120141. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  120142. finished:
  120143. fts3SegWriterFree(pWriter);
  120144. sqlite3Fts3SegReaderFinish(&csr);
  120145. return rc;
  120146. }
  120147. /*
  120148. ** Flush the contents of pendingTerms to level 0 segments.
  120149. */
  120150. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  120151. int rc = SQLITE_OK;
  120152. int i;
  120153. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  120154. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  120155. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  120156. }
  120157. sqlite3Fts3PendingTermsClear(p);
  120158. /* Determine the auto-incr-merge setting if unknown. If enabled,
  120159. ** estimate the number of leaf blocks of content to be written
  120160. */
  120161. if( rc==SQLITE_OK && p->bHasStat
  120162. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  120163. ){
  120164. sqlite3_stmt *pStmt = 0;
  120165. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  120166. if( rc==SQLITE_OK ){
  120167. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  120168. rc = sqlite3_step(pStmt);
  120169. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  120170. rc = sqlite3_reset(pStmt);
  120171. }
  120172. }
  120173. return rc;
  120174. }
  120175. /*
  120176. ** Encode N integers as varints into a blob.
  120177. */
  120178. static void fts3EncodeIntArray(
  120179. int N, /* The number of integers to encode */
  120180. u32 *a, /* The integer values */
  120181. char *zBuf, /* Write the BLOB here */
  120182. int *pNBuf /* Write number of bytes if zBuf[] used here */
  120183. ){
  120184. int i, j;
  120185. for(i=j=0; i<N; i++){
  120186. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  120187. }
  120188. *pNBuf = j;
  120189. }
  120190. /*
  120191. ** Decode a blob of varints into N integers
  120192. */
  120193. static void fts3DecodeIntArray(
  120194. int N, /* The number of integers to decode */
  120195. u32 *a, /* Write the integer values */
  120196. const char *zBuf, /* The BLOB containing the varints */
  120197. int nBuf /* size of the BLOB */
  120198. ){
  120199. int i, j;
  120200. UNUSED_PARAMETER(nBuf);
  120201. for(i=j=0; i<N; i++){
  120202. sqlite3_int64 x;
  120203. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  120204. assert(j<=nBuf);
  120205. a[i] = (u32)(x & 0xffffffff);
  120206. }
  120207. }
  120208. /*
  120209. ** Insert the sizes (in tokens) for each column of the document
  120210. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  120211. ** a blob of varints.
  120212. */
  120213. static void fts3InsertDocsize(
  120214. int *pRC, /* Result code */
  120215. Fts3Table *p, /* Table into which to insert */
  120216. u32 *aSz /* Sizes of each column, in tokens */
  120217. ){
  120218. char *pBlob; /* The BLOB encoding of the document size */
  120219. int nBlob; /* Number of bytes in the BLOB */
  120220. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  120221. int rc; /* Result code from subfunctions */
  120222. if( *pRC ) return;
  120223. pBlob = sqlite3_malloc( 10*p->nColumn );
  120224. if( pBlob==0 ){
  120225. *pRC = SQLITE_NOMEM;
  120226. return;
  120227. }
  120228. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  120229. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  120230. if( rc ){
  120231. sqlite3_free(pBlob);
  120232. *pRC = rc;
  120233. return;
  120234. }
  120235. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  120236. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  120237. sqlite3_step(pStmt);
  120238. *pRC = sqlite3_reset(pStmt);
  120239. }
  120240. /*
  120241. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  120242. ** where N is the number of user defined columns in the fts3 table plus
  120243. ** two. If nCol is the number of user defined columns, then values of the
  120244. ** varints are set as follows:
  120245. **
  120246. ** Varint 0: Total number of rows in the table.
  120247. **
  120248. ** Varint 1..nCol: For each column, the total number of tokens stored in
  120249. ** the column for all rows of the table.
  120250. **
  120251. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  120252. ** columns of all rows of the table.
  120253. **
  120254. */
  120255. static void fts3UpdateDocTotals(
  120256. int *pRC, /* The result code */
  120257. Fts3Table *p, /* Table being updated */
  120258. u32 *aSzIns, /* Size increases */
  120259. u32 *aSzDel, /* Size decreases */
  120260. int nChng /* Change in the number of documents */
  120261. ){
  120262. char *pBlob; /* Storage for BLOB written into %_stat */
  120263. int nBlob; /* Size of BLOB written into %_stat */
  120264. u32 *a; /* Array of integers that becomes the BLOB */
  120265. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  120266. int i; /* Loop counter */
  120267. int rc; /* Result code from subfunctions */
  120268. const int nStat = p->nColumn+2;
  120269. if( *pRC ) return;
  120270. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  120271. if( a==0 ){
  120272. *pRC = SQLITE_NOMEM;
  120273. return;
  120274. }
  120275. pBlob = (char*)&a[nStat];
  120276. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  120277. if( rc ){
  120278. sqlite3_free(a);
  120279. *pRC = rc;
  120280. return;
  120281. }
  120282. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  120283. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  120284. fts3DecodeIntArray(nStat, a,
  120285. sqlite3_column_blob(pStmt, 0),
  120286. sqlite3_column_bytes(pStmt, 0));
  120287. }else{
  120288. memset(a, 0, sizeof(u32)*(nStat) );
  120289. }
  120290. rc = sqlite3_reset(pStmt);
  120291. if( rc!=SQLITE_OK ){
  120292. sqlite3_free(a);
  120293. *pRC = rc;
  120294. return;
  120295. }
  120296. if( nChng<0 && a[0]<(u32)(-nChng) ){
  120297. a[0] = 0;
  120298. }else{
  120299. a[0] += nChng;
  120300. }
  120301. for(i=0; i<p->nColumn+1; i++){
  120302. u32 x = a[i+1];
  120303. if( x+aSzIns[i] < aSzDel[i] ){
  120304. x = 0;
  120305. }else{
  120306. x = x + aSzIns[i] - aSzDel[i];
  120307. }
  120308. a[i+1] = x;
  120309. }
  120310. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  120311. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  120312. if( rc ){
  120313. sqlite3_free(a);
  120314. *pRC = rc;
  120315. return;
  120316. }
  120317. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  120318. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  120319. sqlite3_step(pStmt);
  120320. *pRC = sqlite3_reset(pStmt);
  120321. sqlite3_free(a);
  120322. }
  120323. /*
  120324. ** Merge the entire database so that there is one segment for each
  120325. ** iIndex/iLangid combination.
  120326. */
  120327. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  120328. int bSeenDone = 0;
  120329. int rc;
  120330. sqlite3_stmt *pAllLangid = 0;
  120331. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  120332. if( rc==SQLITE_OK ){
  120333. int rc2;
  120334. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  120335. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  120336. int i;
  120337. int iLangid = sqlite3_column_int(pAllLangid, 0);
  120338. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  120339. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  120340. if( rc==SQLITE_DONE ){
  120341. bSeenDone = 1;
  120342. rc = SQLITE_OK;
  120343. }
  120344. }
  120345. }
  120346. rc2 = sqlite3_reset(pAllLangid);
  120347. if( rc==SQLITE_OK ) rc = rc2;
  120348. }
  120349. sqlite3Fts3SegmentsClose(p);
  120350. sqlite3Fts3PendingTermsClear(p);
  120351. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  120352. }
  120353. /*
  120354. ** This function is called when the user executes the following statement:
  120355. **
  120356. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  120357. **
  120358. ** The entire FTS index is discarded and rebuilt. If the table is one
  120359. ** created using the content=xxx option, then the new index is based on
  120360. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  120361. ** on the contents of the %_content table.
  120362. */
  120363. static int fts3DoRebuild(Fts3Table *p){
  120364. int rc; /* Return Code */
  120365. rc = fts3DeleteAll(p, 0);
  120366. if( rc==SQLITE_OK ){
  120367. u32 *aSz = 0;
  120368. u32 *aSzIns = 0;
  120369. u32 *aSzDel = 0;
  120370. sqlite3_stmt *pStmt = 0;
  120371. int nEntry = 0;
  120372. /* Compose and prepare an SQL statement to loop through the content table */
  120373. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  120374. if( !zSql ){
  120375. rc = SQLITE_NOMEM;
  120376. }else{
  120377. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  120378. sqlite3_free(zSql);
  120379. }
  120380. if( rc==SQLITE_OK ){
  120381. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  120382. aSz = (u32 *)sqlite3_malloc(nByte);
  120383. if( aSz==0 ){
  120384. rc = SQLITE_NOMEM;
  120385. }else{
  120386. memset(aSz, 0, nByte);
  120387. aSzIns = &aSz[p->nColumn+1];
  120388. aSzDel = &aSzIns[p->nColumn+1];
  120389. }
  120390. }
  120391. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  120392. int iCol;
  120393. int iLangid = langidFromSelect(p, pStmt);
  120394. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  120395. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  120396. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  120397. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  120398. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  120399. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  120400. }
  120401. if( p->bHasDocsize ){
  120402. fts3InsertDocsize(&rc, p, aSz);
  120403. }
  120404. if( rc!=SQLITE_OK ){
  120405. sqlite3_finalize(pStmt);
  120406. pStmt = 0;
  120407. }else{
  120408. nEntry++;
  120409. for(iCol=0; iCol<=p->nColumn; iCol++){
  120410. aSzIns[iCol] += aSz[iCol];
  120411. }
  120412. }
  120413. }
  120414. if( p->bFts4 ){
  120415. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  120416. }
  120417. sqlite3_free(aSz);
  120418. if( pStmt ){
  120419. int rc2 = sqlite3_finalize(pStmt);
  120420. if( rc==SQLITE_OK ){
  120421. rc = rc2;
  120422. }
  120423. }
  120424. }
  120425. return rc;
  120426. }
  120427. /*
  120428. ** This function opens a cursor used to read the input data for an
  120429. ** incremental merge operation. Specifically, it opens a cursor to scan
  120430. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  120431. ** level iAbsLevel.
  120432. */
  120433. static int fts3IncrmergeCsr(
  120434. Fts3Table *p, /* FTS3 table handle */
  120435. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  120436. int nSeg, /* Number of segments to merge */
  120437. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  120438. ){
  120439. int rc; /* Return Code */
  120440. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  120441. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  120442. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  120443. memset(pCsr, 0, sizeof(*pCsr));
  120444. nByte = sizeof(Fts3SegReader *) * nSeg;
  120445. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  120446. if( pCsr->apSegment==0 ){
  120447. rc = SQLITE_NOMEM;
  120448. }else{
  120449. memset(pCsr->apSegment, 0, nByte);
  120450. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  120451. }
  120452. if( rc==SQLITE_OK ){
  120453. int i;
  120454. int rc2;
  120455. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  120456. assert( pCsr->nSegment==0 );
  120457. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  120458. rc = sqlite3Fts3SegReaderNew(i, 0,
  120459. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  120460. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  120461. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  120462. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  120463. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  120464. &pCsr->apSegment[i]
  120465. );
  120466. pCsr->nSegment++;
  120467. }
  120468. rc2 = sqlite3_reset(pStmt);
  120469. if( rc==SQLITE_OK ) rc = rc2;
  120470. }
  120471. return rc;
  120472. }
  120473. typedef struct IncrmergeWriter IncrmergeWriter;
  120474. typedef struct NodeWriter NodeWriter;
  120475. typedef struct Blob Blob;
  120476. typedef struct NodeReader NodeReader;
  120477. /*
  120478. ** An instance of the following structure is used as a dynamic buffer
  120479. ** to build up nodes or other blobs of data in.
  120480. **
  120481. ** The function blobGrowBuffer() is used to extend the allocation.
  120482. */
  120483. struct Blob {
  120484. char *a; /* Pointer to allocation */
  120485. int n; /* Number of valid bytes of data in a[] */
  120486. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  120487. };
  120488. /*
  120489. ** This structure is used to build up buffers containing segment b-tree
  120490. ** nodes (blocks).
  120491. */
  120492. struct NodeWriter {
  120493. sqlite3_int64 iBlock; /* Current block id */
  120494. Blob key; /* Last key written to the current block */
  120495. Blob block; /* Current block image */
  120496. };
  120497. /*
  120498. ** An object of this type contains the state required to create or append
  120499. ** to an appendable b-tree segment.
  120500. */
  120501. struct IncrmergeWriter {
  120502. int nLeafEst; /* Space allocated for leaf blocks */
  120503. int nWork; /* Number of leaf pages flushed */
  120504. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  120505. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  120506. sqlite3_int64 iStart; /* Block number of first allocated block */
  120507. sqlite3_int64 iEnd; /* Block number of last allocated block */
  120508. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  120509. };
  120510. /*
  120511. ** An object of the following type is used to read data from a single
  120512. ** FTS segment node. See the following functions:
  120513. **
  120514. ** nodeReaderInit()
  120515. ** nodeReaderNext()
  120516. ** nodeReaderRelease()
  120517. */
  120518. struct NodeReader {
  120519. const char *aNode;
  120520. int nNode;
  120521. int iOff; /* Current offset within aNode[] */
  120522. /* Output variables. Containing the current node entry. */
  120523. sqlite3_int64 iChild; /* Pointer to child node */
  120524. Blob term; /* Current term */
  120525. const char *aDoclist; /* Pointer to doclist */
  120526. int nDoclist; /* Size of doclist in bytes */
  120527. };
  120528. /*
  120529. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  120530. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  120531. ** bytes in size, extend (realloc) it to be so.
  120532. **
  120533. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  120534. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  120535. ** to reflect the new size of the pBlob->a[] buffer.
  120536. */
  120537. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  120538. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  120539. int nAlloc = nMin;
  120540. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  120541. if( a ){
  120542. pBlob->nAlloc = nAlloc;
  120543. pBlob->a = a;
  120544. }else{
  120545. *pRc = SQLITE_NOMEM;
  120546. }
  120547. }
  120548. }
  120549. /*
  120550. ** Attempt to advance the node-reader object passed as the first argument to
  120551. ** the next entry on the node.
  120552. **
  120553. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  120554. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  120555. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  120556. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  120557. ** variables for the new entry.
  120558. */
  120559. static int nodeReaderNext(NodeReader *p){
  120560. int bFirst = (p->term.n==0); /* True for first term on the node */
  120561. int nPrefix = 0; /* Bytes to copy from previous term */
  120562. int nSuffix = 0; /* Bytes to append to the prefix */
  120563. int rc = SQLITE_OK; /* Return code */
  120564. assert( p->aNode );
  120565. if( p->iChild && bFirst==0 ) p->iChild++;
  120566. if( p->iOff>=p->nNode ){
  120567. /* EOF */
  120568. p->aNode = 0;
  120569. }else{
  120570. if( bFirst==0 ){
  120571. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  120572. }
  120573. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  120574. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  120575. if( rc==SQLITE_OK ){
  120576. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  120577. p->term.n = nPrefix+nSuffix;
  120578. p->iOff += nSuffix;
  120579. if( p->iChild==0 ){
  120580. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  120581. p->aDoclist = &p->aNode[p->iOff];
  120582. p->iOff += p->nDoclist;
  120583. }
  120584. }
  120585. }
  120586. assert( p->iOff<=p->nNode );
  120587. return rc;
  120588. }
  120589. /*
  120590. ** Release all dynamic resources held by node-reader object *p.
  120591. */
  120592. static void nodeReaderRelease(NodeReader *p){
  120593. sqlite3_free(p->term.a);
  120594. }
  120595. /*
  120596. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  120597. **
  120598. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  120599. ** point to the first entry on the node (if any). Otherwise, an SQLite
  120600. ** error code is returned.
  120601. */
  120602. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  120603. memset(p, 0, sizeof(NodeReader));
  120604. p->aNode = aNode;
  120605. p->nNode = nNode;
  120606. /* Figure out if this is a leaf or an internal node. */
  120607. if( p->aNode[0] ){
  120608. /* An internal node. */
  120609. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  120610. }else{
  120611. p->iOff = 1;
  120612. }
  120613. return nodeReaderNext(p);
  120614. }
  120615. /*
  120616. ** This function is called while writing an FTS segment each time a leaf o
  120617. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  120618. ** to be greater than the largest key on the node just written, but smaller
  120619. ** than or equal to the first key that will be written to the next leaf
  120620. ** node.
  120621. **
  120622. ** The block id of the leaf node just written to disk may be found in
  120623. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  120624. */
  120625. static int fts3IncrmergePush(
  120626. Fts3Table *p, /* Fts3 table handle */
  120627. IncrmergeWriter *pWriter, /* Writer object */
  120628. const char *zTerm, /* Term to write to internal node */
  120629. int nTerm /* Bytes at zTerm */
  120630. ){
  120631. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  120632. int iLayer;
  120633. assert( nTerm>0 );
  120634. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  120635. sqlite3_int64 iNextPtr = 0;
  120636. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  120637. int rc = SQLITE_OK;
  120638. int nPrefix;
  120639. int nSuffix;
  120640. int nSpace;
  120641. /* Figure out how much space the key will consume if it is written to
  120642. ** the current node of layer iLayer. Due to the prefix compression,
  120643. ** the space required changes depending on which node the key is to
  120644. ** be added to. */
  120645. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  120646. nSuffix = nTerm - nPrefix;
  120647. nSpace = sqlite3Fts3VarintLen(nPrefix);
  120648. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  120649. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  120650. /* If the current node of layer iLayer contains zero keys, or if adding
  120651. ** the key to it will not cause it to grow to larger than nNodeSize
  120652. ** bytes in size, write the key here. */
  120653. Blob *pBlk = &pNode->block;
  120654. if( pBlk->n==0 ){
  120655. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  120656. if( rc==SQLITE_OK ){
  120657. pBlk->a[0] = (char)iLayer;
  120658. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  120659. }
  120660. }
  120661. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  120662. blobGrowBuffer(&pNode->key, nTerm, &rc);
  120663. if( rc==SQLITE_OK ){
  120664. if( pNode->key.n ){
  120665. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  120666. }
  120667. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  120668. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  120669. pBlk->n += nSuffix;
  120670. memcpy(pNode->key.a, zTerm, nTerm);
  120671. pNode->key.n = nTerm;
  120672. }
  120673. }else{
  120674. /* Otherwise, flush the current node of layer iLayer to disk.
  120675. ** Then allocate a new, empty sibling node. The key will be written
  120676. ** into the parent of this node. */
  120677. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  120678. assert( pNode->block.nAlloc>=p->nNodeSize );
  120679. pNode->block.a[0] = (char)iLayer;
  120680. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  120681. iNextPtr = pNode->iBlock;
  120682. pNode->iBlock++;
  120683. pNode->key.n = 0;
  120684. }
  120685. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  120686. iPtr = iNextPtr;
  120687. }
  120688. assert( 0 );
  120689. return 0;
  120690. }
  120691. /*
  120692. ** Append a term and (optionally) doclist to the FTS segment node currently
  120693. ** stored in blob *pNode. The node need not contain any terms, but the
  120694. ** header must be written before this function is called.
  120695. **
  120696. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  120697. ** followed by the left-hand-child varint for an internal node.
  120698. **
  120699. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  120700. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  120701. ** node, both aDoclist and nDoclist must be passed 0.
  120702. **
  120703. ** If the size of the value in blob pPrev is zero, then this is the first
  120704. ** term written to the node. Otherwise, pPrev contains a copy of the
  120705. ** previous term. Before this function returns, it is updated to contain a
  120706. ** copy of zTerm/nTerm.
  120707. **
  120708. ** It is assumed that the buffer associated with pNode is already large
  120709. ** enough to accommodate the new entry. The buffer associated with pPrev
  120710. ** is extended by this function if requrired.
  120711. **
  120712. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  120713. ** returned. Otherwise, SQLITE_OK.
  120714. */
  120715. static int fts3AppendToNode(
  120716. Blob *pNode, /* Current node image to append to */
  120717. Blob *pPrev, /* Buffer containing previous term written */
  120718. const char *zTerm, /* New term to write */
  120719. int nTerm, /* Size of zTerm in bytes */
  120720. const char *aDoclist, /* Doclist (or NULL) to write */
  120721. int nDoclist /* Size of aDoclist in bytes */
  120722. ){
  120723. int rc = SQLITE_OK; /* Return code */
  120724. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  120725. int nPrefix; /* Size of term prefix in bytes */
  120726. int nSuffix; /* Size of term suffix in bytes */
  120727. /* Node must have already been started. There must be a doclist for a
  120728. ** leaf node, and there must not be a doclist for an internal node. */
  120729. assert( pNode->n>0 );
  120730. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  120731. blobGrowBuffer(pPrev, nTerm, &rc);
  120732. if( rc!=SQLITE_OK ) return rc;
  120733. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  120734. nSuffix = nTerm - nPrefix;
  120735. memcpy(pPrev->a, zTerm, nTerm);
  120736. pPrev->n = nTerm;
  120737. if( bFirst==0 ){
  120738. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  120739. }
  120740. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  120741. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  120742. pNode->n += nSuffix;
  120743. if( aDoclist ){
  120744. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  120745. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  120746. pNode->n += nDoclist;
  120747. }
  120748. assert( pNode->n<=pNode->nAlloc );
  120749. return SQLITE_OK;
  120750. }
  120751. /*
  120752. ** Append the current term and doclist pointed to by cursor pCsr to the
  120753. ** appendable b-tree segment opened for writing by pWriter.
  120754. **
  120755. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  120756. */
  120757. static int fts3IncrmergeAppend(
  120758. Fts3Table *p, /* Fts3 table handle */
  120759. IncrmergeWriter *pWriter, /* Writer object */
  120760. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  120761. ){
  120762. const char *zTerm = pCsr->zTerm;
  120763. int nTerm = pCsr->nTerm;
  120764. const char *aDoclist = pCsr->aDoclist;
  120765. int nDoclist = pCsr->nDoclist;
  120766. int rc = SQLITE_OK; /* Return code */
  120767. int nSpace; /* Total space in bytes required on leaf */
  120768. int nPrefix; /* Size of prefix shared with previous term */
  120769. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  120770. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  120771. pLeaf = &pWriter->aNodeWriter[0];
  120772. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  120773. nSuffix = nTerm - nPrefix;
  120774. nSpace = sqlite3Fts3VarintLen(nPrefix);
  120775. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  120776. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  120777. /* If the current block is not empty, and if adding this term/doclist
  120778. ** to the current block would make it larger than Fts3Table.nNodeSize
  120779. ** bytes, write this block out to the database. */
  120780. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  120781. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  120782. pWriter->nWork++;
  120783. /* Add the current term to the parent node. The term added to the
  120784. ** parent must:
  120785. **
  120786. ** a) be greater than the largest term on the leaf node just written
  120787. ** to the database (still available in pLeaf->key), and
  120788. **
  120789. ** b) be less than or equal to the term about to be added to the new
  120790. ** leaf node (zTerm/nTerm).
  120791. **
  120792. ** In other words, it must be the prefix of zTerm 1 byte longer than
  120793. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  120794. */
  120795. if( rc==SQLITE_OK ){
  120796. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  120797. }
  120798. /* Advance to the next output block */
  120799. pLeaf->iBlock++;
  120800. pLeaf->key.n = 0;
  120801. pLeaf->block.n = 0;
  120802. nSuffix = nTerm;
  120803. nSpace = 1;
  120804. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  120805. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  120806. }
  120807. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  120808. if( rc==SQLITE_OK ){
  120809. if( pLeaf->block.n==0 ){
  120810. pLeaf->block.n = 1;
  120811. pLeaf->block.a[0] = '\0';
  120812. }
  120813. rc = fts3AppendToNode(
  120814. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  120815. );
  120816. }
  120817. return rc;
  120818. }
  120819. /*
  120820. ** This function is called to release all dynamic resources held by the
  120821. ** merge-writer object pWriter, and if no error has occurred, to flush
  120822. ** all outstanding node buffers held by pWriter to disk.
  120823. **
  120824. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  120825. ** is made to write any data to disk. Instead, this function serves only
  120826. ** to release outstanding resources.
  120827. **
  120828. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  120829. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  120830. ** returning.
  120831. */
  120832. static void fts3IncrmergeRelease(
  120833. Fts3Table *p, /* FTS3 table handle */
  120834. IncrmergeWriter *pWriter, /* Merge-writer object */
  120835. int *pRc /* IN/OUT: Error code */
  120836. ){
  120837. int i; /* Used to iterate through non-root layers */
  120838. int iRoot; /* Index of root in pWriter->aNodeWriter */
  120839. NodeWriter *pRoot; /* NodeWriter for root node */
  120840. int rc = *pRc; /* Error code */
  120841. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  120842. ** root node. If the segment fits entirely on a single leaf node, iRoot
  120843. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  120844. ** will be 1. And so on. */
  120845. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  120846. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  120847. if( pNode->block.n>0 ) break;
  120848. assert( *pRc || pNode->block.nAlloc==0 );
  120849. assert( *pRc || pNode->key.nAlloc==0 );
  120850. sqlite3_free(pNode->block.a);
  120851. sqlite3_free(pNode->key.a);
  120852. }
  120853. /* Empty output segment. This is a no-op. */
  120854. if( iRoot<0 ) return;
  120855. /* The entire output segment fits on a single node. Normally, this means
  120856. ** the node would be stored as a blob in the "root" column of the %_segdir
  120857. ** table. However, this is not permitted in this case. The problem is that
  120858. ** space has already been reserved in the %_segments table, and so the
  120859. ** start_block and end_block fields of the %_segdir table must be populated.
  120860. ** And, by design or by accident, released versions of FTS cannot handle
  120861. ** segments that fit entirely on the root node with start_block!=0.
  120862. **
  120863. ** Instead, create a synthetic root node that contains nothing but a
  120864. ** pointer to the single content node. So that the segment consists of a
  120865. ** single leaf and a single interior (root) node.
  120866. **
  120867. ** Todo: Better might be to defer allocating space in the %_segments
  120868. ** table until we are sure it is needed.
  120869. */
  120870. if( iRoot==0 ){
  120871. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  120872. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  120873. if( rc==SQLITE_OK ){
  120874. pBlock->a[0] = 0x01;
  120875. pBlock->n = 1 + sqlite3Fts3PutVarint(
  120876. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  120877. );
  120878. }
  120879. iRoot = 1;
  120880. }
  120881. pRoot = &pWriter->aNodeWriter[iRoot];
  120882. /* Flush all currently outstanding nodes to disk. */
  120883. for(i=0; i<iRoot; i++){
  120884. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  120885. if( pNode->block.n>0 && rc==SQLITE_OK ){
  120886. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  120887. }
  120888. sqlite3_free(pNode->block.a);
  120889. sqlite3_free(pNode->key.a);
  120890. }
  120891. /* Write the %_segdir record. */
  120892. if( rc==SQLITE_OK ){
  120893. rc = fts3WriteSegdir(p,
  120894. pWriter->iAbsLevel+1, /* level */
  120895. pWriter->iIdx, /* idx */
  120896. pWriter->iStart, /* start_block */
  120897. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  120898. pWriter->iEnd, /* end_block */
  120899. pRoot->block.a, pRoot->block.n /* root */
  120900. );
  120901. }
  120902. sqlite3_free(pRoot->block.a);
  120903. sqlite3_free(pRoot->key.a);
  120904. *pRc = rc;
  120905. }
  120906. /*
  120907. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  120908. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  120909. ** the other, it is considered to be smaller than the other.
  120910. **
  120911. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  120912. ** if it is greater.
  120913. */
  120914. static int fts3TermCmp(
  120915. const char *zLhs, int nLhs, /* LHS of comparison */
  120916. const char *zRhs, int nRhs /* RHS of comparison */
  120917. ){
  120918. int nCmp = MIN(nLhs, nRhs);
  120919. int res;
  120920. res = memcmp(zLhs, zRhs, nCmp);
  120921. if( res==0 ) res = nLhs - nRhs;
  120922. return res;
  120923. }
  120924. /*
  120925. ** Query to see if the entry in the %_segments table with blockid iEnd is
  120926. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  120927. ** returning. Otherwise, set *pbRes to 0.
  120928. **
  120929. ** Or, if an error occurs while querying the database, return an SQLite
  120930. ** error code. The final value of *pbRes is undefined in this case.
  120931. **
  120932. ** This is used to test if a segment is an "appendable" segment. If it
  120933. ** is, then a NULL entry has been inserted into the %_segments table
  120934. ** with blockid %_segdir.end_block.
  120935. */
  120936. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  120937. int bRes = 0; /* Result to set *pbRes to */
  120938. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  120939. int rc; /* Return code */
  120940. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  120941. if( rc==SQLITE_OK ){
  120942. sqlite3_bind_int64(pCheck, 1, iEnd);
  120943. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  120944. rc = sqlite3_reset(pCheck);
  120945. }
  120946. *pbRes = bRes;
  120947. return rc;
  120948. }
  120949. /*
  120950. ** This function is called when initializing an incremental-merge operation.
  120951. ** It checks if the existing segment with index value iIdx at absolute level
  120952. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  120953. ** merge-writer object *pWriter is initialized to write to it.
  120954. **
  120955. ** An existing segment can be appended to by an incremental merge if:
  120956. **
  120957. ** * It was initially created as an appendable segment (with all required
  120958. ** space pre-allocated), and
  120959. **
  120960. ** * The first key read from the input (arguments zKey and nKey) is
  120961. ** greater than the largest key currently stored in the potential
  120962. ** output segment.
  120963. */
  120964. static int fts3IncrmergeLoad(
  120965. Fts3Table *p, /* Fts3 table handle */
  120966. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  120967. int iIdx, /* Index of candidate output segment */
  120968. const char *zKey, /* First key to write */
  120969. int nKey, /* Number of bytes in nKey */
  120970. IncrmergeWriter *pWriter /* Populate this object */
  120971. ){
  120972. int rc; /* Return code */
  120973. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  120974. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  120975. if( rc==SQLITE_OK ){
  120976. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  120977. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  120978. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  120979. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  120980. int nRoot = 0; /* Size of aRoot[] in bytes */
  120981. int rc2; /* Return code from sqlite3_reset() */
  120982. int bAppendable = 0; /* Set to true if segment is appendable */
  120983. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  120984. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  120985. sqlite3_bind_int(pSelect, 2, iIdx);
  120986. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  120987. iStart = sqlite3_column_int64(pSelect, 1);
  120988. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  120989. iEnd = sqlite3_column_int64(pSelect, 3);
  120990. nRoot = sqlite3_column_bytes(pSelect, 4);
  120991. aRoot = sqlite3_column_blob(pSelect, 4);
  120992. }else{
  120993. return sqlite3_reset(pSelect);
  120994. }
  120995. /* Check for the zero-length marker in the %_segments table */
  120996. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  120997. /* Check that zKey/nKey is larger than the largest key the candidate */
  120998. if( rc==SQLITE_OK && bAppendable ){
  120999. char *aLeaf = 0;
  121000. int nLeaf = 0;
  121001. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  121002. if( rc==SQLITE_OK ){
  121003. NodeReader reader;
  121004. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  121005. rc==SQLITE_OK && reader.aNode;
  121006. rc = nodeReaderNext(&reader)
  121007. ){
  121008. assert( reader.aNode );
  121009. }
  121010. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  121011. bAppendable = 0;
  121012. }
  121013. nodeReaderRelease(&reader);
  121014. }
  121015. sqlite3_free(aLeaf);
  121016. }
  121017. if( rc==SQLITE_OK && bAppendable ){
  121018. /* It is possible to append to this segment. Set up the IncrmergeWriter
  121019. ** object to do so. */
  121020. int i;
  121021. int nHeight = (int)aRoot[0];
  121022. NodeWriter *pNode;
  121023. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  121024. pWriter->iStart = iStart;
  121025. pWriter->iEnd = iEnd;
  121026. pWriter->iAbsLevel = iAbsLevel;
  121027. pWriter->iIdx = iIdx;
  121028. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  121029. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  121030. }
  121031. pNode = &pWriter->aNodeWriter[nHeight];
  121032. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  121033. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  121034. if( rc==SQLITE_OK ){
  121035. memcpy(pNode->block.a, aRoot, nRoot);
  121036. pNode->block.n = nRoot;
  121037. }
  121038. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  121039. NodeReader reader;
  121040. pNode = &pWriter->aNodeWriter[i];
  121041. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  121042. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  121043. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  121044. if( rc==SQLITE_OK ){
  121045. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  121046. pNode->key.n = reader.term.n;
  121047. if( i>0 ){
  121048. char *aBlock = 0;
  121049. int nBlock = 0;
  121050. pNode = &pWriter->aNodeWriter[i-1];
  121051. pNode->iBlock = reader.iChild;
  121052. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  121053. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  121054. if( rc==SQLITE_OK ){
  121055. memcpy(pNode->block.a, aBlock, nBlock);
  121056. pNode->block.n = nBlock;
  121057. }
  121058. sqlite3_free(aBlock);
  121059. }
  121060. }
  121061. nodeReaderRelease(&reader);
  121062. }
  121063. }
  121064. rc2 = sqlite3_reset(pSelect);
  121065. if( rc==SQLITE_OK ) rc = rc2;
  121066. }
  121067. return rc;
  121068. }
  121069. /*
  121070. ** Determine the largest segment index value that exists within absolute
  121071. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  121072. ** one before returning SQLITE_OK. Or, if there are no segments at all
  121073. ** within level iAbsLevel, set *piIdx to zero.
  121074. **
  121075. ** If an error occurs, return an SQLite error code. The final value of
  121076. ** *piIdx is undefined in this case.
  121077. */
  121078. static int fts3IncrmergeOutputIdx(
  121079. Fts3Table *p, /* FTS Table handle */
  121080. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  121081. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  121082. ){
  121083. int rc;
  121084. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  121085. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  121086. if( rc==SQLITE_OK ){
  121087. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  121088. sqlite3_step(pOutputIdx);
  121089. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  121090. rc = sqlite3_reset(pOutputIdx);
  121091. }
  121092. return rc;
  121093. }
  121094. /*
  121095. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  121096. ** with idx value iIdx.
  121097. **
  121098. ** In the %_segdir table, a segment is defined by the values in three
  121099. ** columns:
  121100. **
  121101. ** start_block
  121102. ** leaves_end_block
  121103. ** end_block
  121104. **
  121105. ** When an appendable segment is allocated, it is estimated that the
  121106. ** maximum number of leaf blocks that may be required is the sum of the
  121107. ** number of leaf blocks consumed by the input segments, plus the number
  121108. ** of input segments, multiplied by two. This value is stored in stack
  121109. ** variable nLeafEst.
  121110. **
  121111. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  121112. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  121113. ** array of leaf nodes starts at the first block allocated. The array
  121114. ** of interior nodes that are parents of the leaf nodes start at block
  121115. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  121116. **
  121117. ** In the actual code below, the value "16" is replaced with the
  121118. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  121119. */
  121120. static int fts3IncrmergeWriter(
  121121. Fts3Table *p, /* Fts3 table handle */
  121122. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  121123. int iIdx, /* Index of new output segment */
  121124. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  121125. IncrmergeWriter *pWriter /* Populate this object */
  121126. ){
  121127. int rc; /* Return Code */
  121128. int i; /* Iterator variable */
  121129. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  121130. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  121131. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  121132. /* Calculate nLeafEst. */
  121133. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  121134. if( rc==SQLITE_OK ){
  121135. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  121136. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  121137. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  121138. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  121139. }
  121140. rc = sqlite3_reset(pLeafEst);
  121141. }
  121142. if( rc!=SQLITE_OK ) return rc;
  121143. /* Calculate the first block to use in the output segment */
  121144. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  121145. if( rc==SQLITE_OK ){
  121146. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  121147. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  121148. pWriter->iEnd = pWriter->iStart - 1;
  121149. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  121150. }
  121151. rc = sqlite3_reset(pFirstBlock);
  121152. }
  121153. if( rc!=SQLITE_OK ) return rc;
  121154. /* Insert the marker in the %_segments table to make sure nobody tries
  121155. ** to steal the space just allocated. This is also used to identify
  121156. ** appendable segments. */
  121157. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  121158. if( rc!=SQLITE_OK ) return rc;
  121159. pWriter->iAbsLevel = iAbsLevel;
  121160. pWriter->nLeafEst = nLeafEst;
  121161. pWriter->iIdx = iIdx;
  121162. /* Set up the array of NodeWriter objects */
  121163. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  121164. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  121165. }
  121166. return SQLITE_OK;
  121167. }
  121168. /*
  121169. ** Remove an entry from the %_segdir table. This involves running the
  121170. ** following two statements:
  121171. **
  121172. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  121173. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  121174. **
  121175. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  121176. ** statement ensures that the remaining segments have contiguously allocated
  121177. ** idx values.
  121178. */
  121179. static int fts3RemoveSegdirEntry(
  121180. Fts3Table *p, /* FTS3 table handle */
  121181. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  121182. int iIdx /* Index of %_segdir entry to delete */
  121183. ){
  121184. int rc; /* Return code */
  121185. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  121186. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  121187. if( rc==SQLITE_OK ){
  121188. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  121189. sqlite3_bind_int(pDelete, 2, iIdx);
  121190. sqlite3_step(pDelete);
  121191. rc = sqlite3_reset(pDelete);
  121192. }
  121193. return rc;
  121194. }
  121195. /*
  121196. ** One or more segments have just been removed from absolute level iAbsLevel.
  121197. ** Update the 'idx' values of the remaining segments in the level so that
  121198. ** the idx values are a contiguous sequence starting from 0.
  121199. */
  121200. static int fts3RepackSegdirLevel(
  121201. Fts3Table *p, /* FTS3 table handle */
  121202. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  121203. ){
  121204. int rc; /* Return code */
  121205. int *aIdx = 0; /* Array of remaining idx values */
  121206. int nIdx = 0; /* Valid entries in aIdx[] */
  121207. int nAlloc = 0; /* Allocated size of aIdx[] */
  121208. int i; /* Iterator variable */
  121209. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  121210. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  121211. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  121212. if( rc==SQLITE_OK ){
  121213. int rc2;
  121214. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  121215. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  121216. if( nIdx>=nAlloc ){
  121217. int *aNew;
  121218. nAlloc += 16;
  121219. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  121220. if( !aNew ){
  121221. rc = SQLITE_NOMEM;
  121222. break;
  121223. }
  121224. aIdx = aNew;
  121225. }
  121226. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  121227. }
  121228. rc2 = sqlite3_reset(pSelect);
  121229. if( rc==SQLITE_OK ) rc = rc2;
  121230. }
  121231. if( rc==SQLITE_OK ){
  121232. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  121233. }
  121234. if( rc==SQLITE_OK ){
  121235. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  121236. }
  121237. assert( p->bIgnoreSavepoint==0 );
  121238. p->bIgnoreSavepoint = 1;
  121239. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  121240. if( aIdx[i]!=i ){
  121241. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  121242. sqlite3_bind_int(pUpdate, 1, i);
  121243. sqlite3_step(pUpdate);
  121244. rc = sqlite3_reset(pUpdate);
  121245. }
  121246. }
  121247. p->bIgnoreSavepoint = 0;
  121248. sqlite3_free(aIdx);
  121249. return rc;
  121250. }
  121251. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  121252. pNode->a[0] = (char)iHeight;
  121253. if( iChild ){
  121254. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  121255. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  121256. }else{
  121257. assert( pNode->nAlloc>=1 );
  121258. pNode->n = 1;
  121259. }
  121260. }
  121261. /*
  121262. ** The first two arguments are a pointer to and the size of a segment b-tree
  121263. ** node. The node may be a leaf or an internal node.
  121264. **
  121265. ** This function creates a new node image in blob object *pNew by copying
  121266. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  121267. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  121268. */
  121269. static int fts3TruncateNode(
  121270. const char *aNode, /* Current node image */
  121271. int nNode, /* Size of aNode in bytes */
  121272. Blob *pNew, /* OUT: Write new node image here */
  121273. const char *zTerm, /* Omit all terms smaller than this */
  121274. int nTerm, /* Size of zTerm in bytes */
  121275. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  121276. ){
  121277. NodeReader reader; /* Reader object */
  121278. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  121279. int rc = SQLITE_OK; /* Return code */
  121280. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  121281. /* Allocate required output space */
  121282. blobGrowBuffer(pNew, nNode, &rc);
  121283. if( rc!=SQLITE_OK ) return rc;
  121284. pNew->n = 0;
  121285. /* Populate new node buffer */
  121286. for(rc = nodeReaderInit(&reader, aNode, nNode);
  121287. rc==SQLITE_OK && reader.aNode;
  121288. rc = nodeReaderNext(&reader)
  121289. ){
  121290. if( pNew->n==0 ){
  121291. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  121292. if( res<0 || (bLeaf==0 && res==0) ) continue;
  121293. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  121294. *piBlock = reader.iChild;
  121295. }
  121296. rc = fts3AppendToNode(
  121297. pNew, &prev, reader.term.a, reader.term.n,
  121298. reader.aDoclist, reader.nDoclist
  121299. );
  121300. if( rc!=SQLITE_OK ) break;
  121301. }
  121302. if( pNew->n==0 ){
  121303. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  121304. *piBlock = reader.iChild;
  121305. }
  121306. assert( pNew->n<=pNew->nAlloc );
  121307. nodeReaderRelease(&reader);
  121308. sqlite3_free(prev.a);
  121309. return rc;
  121310. }
  121311. /*
  121312. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  121313. ** level iAbsLevel. This may involve deleting entries from the %_segments
  121314. ** table, and modifying existing entries in both the %_segments and %_segdir
  121315. ** tables.
  121316. **
  121317. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  121318. ** SQLite error code otherwise.
  121319. */
  121320. static int fts3TruncateSegment(
  121321. Fts3Table *p, /* FTS3 table handle */
  121322. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  121323. int iIdx, /* Index within level of segment to modify */
  121324. const char *zTerm, /* Remove terms smaller than this */
  121325. int nTerm /* Number of bytes in buffer zTerm */
  121326. ){
  121327. int rc = SQLITE_OK; /* Return code */
  121328. Blob root = {0,0,0}; /* New root page image */
  121329. Blob block = {0,0,0}; /* Buffer used for any other block */
  121330. sqlite3_int64 iBlock = 0; /* Block id */
  121331. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  121332. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  121333. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  121334. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  121335. if( rc==SQLITE_OK ){
  121336. int rc2; /* sqlite3_reset() return code */
  121337. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  121338. sqlite3_bind_int(pFetch, 2, iIdx);
  121339. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  121340. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  121341. int nRoot = sqlite3_column_bytes(pFetch, 4);
  121342. iOldStart = sqlite3_column_int64(pFetch, 1);
  121343. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  121344. }
  121345. rc2 = sqlite3_reset(pFetch);
  121346. if( rc==SQLITE_OK ) rc = rc2;
  121347. }
  121348. while( rc==SQLITE_OK && iBlock ){
  121349. char *aBlock = 0;
  121350. int nBlock = 0;
  121351. iNewStart = iBlock;
  121352. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  121353. if( rc==SQLITE_OK ){
  121354. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  121355. }
  121356. if( rc==SQLITE_OK ){
  121357. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  121358. }
  121359. sqlite3_free(aBlock);
  121360. }
  121361. /* Variable iNewStart now contains the first valid leaf node. */
  121362. if( rc==SQLITE_OK && iNewStart ){
  121363. sqlite3_stmt *pDel = 0;
  121364. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  121365. if( rc==SQLITE_OK ){
  121366. sqlite3_bind_int64(pDel, 1, iOldStart);
  121367. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  121368. sqlite3_step(pDel);
  121369. rc = sqlite3_reset(pDel);
  121370. }
  121371. }
  121372. if( rc==SQLITE_OK ){
  121373. sqlite3_stmt *pChomp = 0;
  121374. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  121375. if( rc==SQLITE_OK ){
  121376. sqlite3_bind_int64(pChomp, 1, iNewStart);
  121377. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  121378. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  121379. sqlite3_bind_int(pChomp, 4, iIdx);
  121380. sqlite3_step(pChomp);
  121381. rc = sqlite3_reset(pChomp);
  121382. }
  121383. }
  121384. sqlite3_free(root.a);
  121385. sqlite3_free(block.a);
  121386. return rc;
  121387. }
  121388. /*
  121389. ** This function is called after an incrmental-merge operation has run to
  121390. ** merge (or partially merge) two or more segments from absolute level
  121391. ** iAbsLevel.
  121392. **
  121393. ** Each input segment is either removed from the db completely (if all of
  121394. ** its data was copied to the output segment by the incrmerge operation)
  121395. ** or modified in place so that it no longer contains those entries that
  121396. ** have been duplicated in the output segment.
  121397. */
  121398. static int fts3IncrmergeChomp(
  121399. Fts3Table *p, /* FTS table handle */
  121400. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  121401. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  121402. int *pnRem /* Number of segments not deleted */
  121403. ){
  121404. int i;
  121405. int nRem = 0;
  121406. int rc = SQLITE_OK;
  121407. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  121408. Fts3SegReader *pSeg = 0;
  121409. int j;
  121410. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  121411. ** somewhere in the pCsr->apSegment[] array. */
  121412. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  121413. pSeg = pCsr->apSegment[j];
  121414. if( pSeg->iIdx==i ) break;
  121415. }
  121416. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  121417. if( pSeg->aNode==0 ){
  121418. /* Seg-reader is at EOF. Remove the entire input segment. */
  121419. rc = fts3DeleteSegment(p, pSeg);
  121420. if( rc==SQLITE_OK ){
  121421. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  121422. }
  121423. *pnRem = 0;
  121424. }else{
  121425. /* The incremental merge did not copy all the data from this
  121426. ** segment to the upper level. The segment is modified in place
  121427. ** so that it contains no keys smaller than zTerm/nTerm. */
  121428. const char *zTerm = pSeg->zTerm;
  121429. int nTerm = pSeg->nTerm;
  121430. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  121431. nRem++;
  121432. }
  121433. }
  121434. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  121435. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  121436. }
  121437. *pnRem = nRem;
  121438. return rc;
  121439. }
  121440. /*
  121441. ** Store an incr-merge hint in the database.
  121442. */
  121443. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  121444. sqlite3_stmt *pReplace = 0;
  121445. int rc; /* Return code */
  121446. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  121447. if( rc==SQLITE_OK ){
  121448. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  121449. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  121450. sqlite3_step(pReplace);
  121451. rc = sqlite3_reset(pReplace);
  121452. }
  121453. return rc;
  121454. }
  121455. /*
  121456. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  121457. ** exists, is stored in the rowid==1 row of the %_stat table.
  121458. **
  121459. ** If successful, populate blob *pHint with the value read from the %_stat
  121460. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  121461. ** SQLite error code.
  121462. */
  121463. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  121464. sqlite3_stmt *pSelect = 0;
  121465. int rc;
  121466. pHint->n = 0;
  121467. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  121468. if( rc==SQLITE_OK ){
  121469. int rc2;
  121470. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  121471. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  121472. const char *aHint = sqlite3_column_blob(pSelect, 0);
  121473. int nHint = sqlite3_column_bytes(pSelect, 0);
  121474. if( aHint ){
  121475. blobGrowBuffer(pHint, nHint, &rc);
  121476. if( rc==SQLITE_OK ){
  121477. memcpy(pHint->a, aHint, nHint);
  121478. pHint->n = nHint;
  121479. }
  121480. }
  121481. }
  121482. rc2 = sqlite3_reset(pSelect);
  121483. if( rc==SQLITE_OK ) rc = rc2;
  121484. }
  121485. return rc;
  121486. }
  121487. /*
  121488. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121489. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  121490. ** consists of two varints, the absolute level number of the input segments
  121491. ** and the number of input segments.
  121492. **
  121493. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  121494. ** set *pRc to an SQLite error code before returning.
  121495. */
  121496. static void fts3IncrmergeHintPush(
  121497. Blob *pHint, /* Hint blob to append to */
  121498. i64 iAbsLevel, /* First varint to store in hint */
  121499. int nInput, /* Second varint to store in hint */
  121500. int *pRc /* IN/OUT: Error code */
  121501. ){
  121502. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  121503. if( *pRc==SQLITE_OK ){
  121504. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  121505. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  121506. }
  121507. }
  121508. /*
  121509. ** Read the last entry (most recently pushed) from the hint blob *pHint
  121510. ** and then remove the entry. Write the two values read to *piAbsLevel and
  121511. ** *pnInput before returning.
  121512. **
  121513. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  121514. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  121515. */
  121516. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  121517. const int nHint = pHint->n;
  121518. int i;
  121519. i = pHint->n-2;
  121520. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  121521. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  121522. pHint->n = i;
  121523. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  121524. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  121525. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  121526. return SQLITE_OK;
  121527. }
  121528. /*
  121529. ** Attempt an incremental merge that writes nMerge leaf blocks.
  121530. **
  121531. ** Incremental merges happen nMin segments at a time. The two
  121532. ** segments to be merged are the nMin oldest segments (the ones with
  121533. ** the smallest indexes) in the highest level that contains at least
  121534. ** nMin segments. Multiple merges might occur in an attempt to write the
  121535. ** quota of nMerge leaf blocks.
  121536. */
  121537. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  121538. int rc; /* Return code */
  121539. int nRem = nMerge; /* Number of leaf pages yet to be written */
  121540. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  121541. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  121542. IncrmergeWriter *pWriter; /* Writer object */
  121543. int nSeg = 0; /* Number of input segments */
  121544. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  121545. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  121546. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  121547. /* Allocate space for the cursor, filter and writer objects */
  121548. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  121549. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  121550. if( !pWriter ) return SQLITE_NOMEM;
  121551. pFilter = (Fts3SegFilter *)&pWriter[1];
  121552. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  121553. rc = fts3IncrmergeHintLoad(p, &hint);
  121554. while( rc==SQLITE_OK && nRem>0 ){
  121555. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  121556. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  121557. int bUseHint = 0; /* True if attempting to append */
  121558. /* Search the %_segdir table for the absolute level with the smallest
  121559. ** relative level number that contains at least nMin segments, if any.
  121560. ** If one is found, set iAbsLevel to the absolute level number and
  121561. ** nSeg to nMin. If no level with at least nMin segments can be found,
  121562. ** set nSeg to -1.
  121563. */
  121564. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  121565. sqlite3_bind_int(pFindLevel, 1, nMin);
  121566. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  121567. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  121568. nSeg = nMin;
  121569. }else{
  121570. nSeg = -1;
  121571. }
  121572. rc = sqlite3_reset(pFindLevel);
  121573. /* If the hint read from the %_stat table is not empty, check if the
  121574. ** last entry in it specifies a relative level smaller than or equal
  121575. ** to the level identified by the block above (if any). If so, this
  121576. ** iteration of the loop will work on merging at the hinted level.
  121577. */
  121578. if( rc==SQLITE_OK && hint.n ){
  121579. int nHint = hint.n;
  121580. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  121581. int nHintSeg = 0; /* Hint number of segments */
  121582. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  121583. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  121584. iAbsLevel = iHintAbsLevel;
  121585. nSeg = nHintSeg;
  121586. bUseHint = 1;
  121587. bDirtyHint = 1;
  121588. }else{
  121589. /* This undoes the effect of the HintPop() above - so that no entry
  121590. ** is removed from the hint blob. */
  121591. hint.n = nHint;
  121592. }
  121593. }
  121594. /* If nSeg is less that zero, then there is no level with at least
  121595. ** nMin segments and no hint in the %_stat table. No work to do.
  121596. ** Exit early in this case. */
  121597. if( nSeg<0 ) break;
  121598. /* Open a cursor to iterate through the contents of the oldest nSeg
  121599. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  121600. ** the 'hint' parameters, it is possible that there are less than nSeg
  121601. ** segments available in level iAbsLevel. In this case, no work is
  121602. ** done on iAbsLevel - fall through to the next iteration of the loop
  121603. ** to start work on some other level. */
  121604. memset(pWriter, 0, nAlloc);
  121605. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  121606. if( rc==SQLITE_OK ){
  121607. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  121608. }
  121609. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  121610. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  121611. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  121612. ){
  121613. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  121614. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  121615. if( rc==SQLITE_OK ){
  121616. if( bUseHint && iIdx>0 ){
  121617. const char *zKey = pCsr->zTerm;
  121618. int nKey = pCsr->nTerm;
  121619. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  121620. }else{
  121621. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  121622. }
  121623. }
  121624. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  121625. fts3LogMerge(nSeg, iAbsLevel);
  121626. do {
  121627. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  121628. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  121629. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  121630. }while( rc==SQLITE_ROW );
  121631. /* Update or delete the input segments */
  121632. if( rc==SQLITE_OK ){
  121633. nRem -= (1 + pWriter->nWork);
  121634. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  121635. if( nSeg!=0 ){
  121636. bDirtyHint = 1;
  121637. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  121638. }
  121639. }
  121640. }
  121641. fts3IncrmergeRelease(p, pWriter, &rc);
  121642. }
  121643. sqlite3Fts3SegReaderFinish(pCsr);
  121644. }
  121645. /* Write the hint values into the %_stat table for the next incr-merger */
  121646. if( bDirtyHint && rc==SQLITE_OK ){
  121647. rc = fts3IncrmergeHintStore(p, &hint);
  121648. }
  121649. sqlite3_free(pWriter);
  121650. sqlite3_free(hint.a);
  121651. return rc;
  121652. }
  121653. /*
  121654. ** Convert the text beginning at *pz into an integer and return
  121655. ** its value. Advance *pz to point to the first character past
  121656. ** the integer.
  121657. */
  121658. static int fts3Getint(const char **pz){
  121659. const char *z = *pz;
  121660. int i = 0;
  121661. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  121662. *pz = z;
  121663. return i;
  121664. }
  121665. /*
  121666. ** Process statements of the form:
  121667. **
  121668. ** INSERT INTO table(table) VALUES('merge=A,B');
  121669. **
  121670. ** A and B are integers that decode to be the number of leaf pages
  121671. ** written for the merge, and the minimum number of segments on a level
  121672. ** before it will be selected for a merge, respectively.
  121673. */
  121674. static int fts3DoIncrmerge(
  121675. Fts3Table *p, /* FTS3 table handle */
  121676. const char *zParam /* Nul-terminated string containing "A,B" */
  121677. ){
  121678. int rc;
  121679. int nMin = (FTS3_MERGE_COUNT / 2);
  121680. int nMerge = 0;
  121681. const char *z = zParam;
  121682. /* Read the first integer value */
  121683. nMerge = fts3Getint(&z);
  121684. /* If the first integer value is followed by a ',', read the second
  121685. ** integer value. */
  121686. if( z[0]==',' && z[1]!='\0' ){
  121687. z++;
  121688. nMin = fts3Getint(&z);
  121689. }
  121690. if( z[0]!='\0' || nMin<2 ){
  121691. rc = SQLITE_ERROR;
  121692. }else{
  121693. rc = SQLITE_OK;
  121694. if( !p->bHasStat ){
  121695. assert( p->bFts4==0 );
  121696. sqlite3Fts3CreateStatTable(&rc, p);
  121697. }
  121698. if( rc==SQLITE_OK ){
  121699. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  121700. }
  121701. sqlite3Fts3SegmentsClose(p);
  121702. }
  121703. return rc;
  121704. }
  121705. /*
  121706. ** Process statements of the form:
  121707. **
  121708. ** INSERT INTO table(table) VALUES('automerge=X');
  121709. **
  121710. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  121711. ** turn it on. The setting is persistent.
  121712. */
  121713. static int fts3DoAutoincrmerge(
  121714. Fts3Table *p, /* FTS3 table handle */
  121715. const char *zParam /* Nul-terminated string containing boolean */
  121716. ){
  121717. int rc = SQLITE_OK;
  121718. sqlite3_stmt *pStmt = 0;
  121719. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  121720. if( !p->bHasStat ){
  121721. assert( p->bFts4==0 );
  121722. sqlite3Fts3CreateStatTable(&rc, p);
  121723. if( rc ) return rc;
  121724. }
  121725. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  121726. if( rc ) return rc;;
  121727. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  121728. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  121729. sqlite3_step(pStmt);
  121730. rc = sqlite3_reset(pStmt);
  121731. return rc;
  121732. }
  121733. /*
  121734. ** Return a 64-bit checksum for the FTS index entry specified by the
  121735. ** arguments to this function.
  121736. */
  121737. static u64 fts3ChecksumEntry(
  121738. const char *zTerm, /* Pointer to buffer containing term */
  121739. int nTerm, /* Size of zTerm in bytes */
  121740. int iLangid, /* Language id for current row */
  121741. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  121742. i64 iDocid, /* Docid for current row. */
  121743. int iCol, /* Column number */
  121744. int iPos /* Position */
  121745. ){
  121746. int i;
  121747. u64 ret = (u64)iDocid;
  121748. ret += (ret<<3) + iLangid;
  121749. ret += (ret<<3) + iIndex;
  121750. ret += (ret<<3) + iCol;
  121751. ret += (ret<<3) + iPos;
  121752. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  121753. return ret;
  121754. }
  121755. /*
  121756. ** Return a checksum of all entries in the FTS index that correspond to
  121757. ** language id iLangid. The checksum is calculated by XORing the checksums
  121758. ** of each individual entry (see fts3ChecksumEntry()) together.
  121759. **
  121760. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  121761. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  121762. ** return value is undefined in this case.
  121763. */
  121764. static u64 fts3ChecksumIndex(
  121765. Fts3Table *p, /* FTS3 table handle */
  121766. int iLangid, /* Language id to return cksum for */
  121767. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  121768. int *pRc /* OUT: Return code */
  121769. ){
  121770. Fts3SegFilter filter;
  121771. Fts3MultiSegReader csr;
  121772. int rc;
  121773. u64 cksum = 0;
  121774. assert( *pRc==SQLITE_OK );
  121775. memset(&filter, 0, sizeof(filter));
  121776. memset(&csr, 0, sizeof(csr));
  121777. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  121778. filter.flags |= FTS3_SEGMENT_SCAN;
  121779. rc = sqlite3Fts3SegReaderCursor(
  121780. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  121781. );
  121782. if( rc==SQLITE_OK ){
  121783. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  121784. }
  121785. if( rc==SQLITE_OK ){
  121786. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  121787. char *pCsr = csr.aDoclist;
  121788. char *pEnd = &pCsr[csr.nDoclist];
  121789. i64 iDocid = 0;
  121790. i64 iCol = 0;
  121791. i64 iPos = 0;
  121792. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  121793. while( pCsr<pEnd ){
  121794. i64 iVal = 0;
  121795. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  121796. if( pCsr<pEnd ){
  121797. if( iVal==0 || iVal==1 ){
  121798. iCol = 0;
  121799. iPos = 0;
  121800. if( iVal ){
  121801. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  121802. }else{
  121803. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  121804. iDocid += iVal;
  121805. }
  121806. }else{
  121807. iPos += (iVal - 2);
  121808. cksum = cksum ^ fts3ChecksumEntry(
  121809. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  121810. (int)iCol, (int)iPos
  121811. );
  121812. }
  121813. }
  121814. }
  121815. }
  121816. }
  121817. sqlite3Fts3SegReaderFinish(&csr);
  121818. *pRc = rc;
  121819. return cksum;
  121820. }
  121821. /*
  121822. ** Check if the contents of the FTS index match the current contents of the
  121823. ** content table. If no error occurs and the contents do match, set *pbOk
  121824. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  121825. ** to false before returning.
  121826. **
  121827. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  121828. ** code. The final value of *pbOk is undefined in this case.
  121829. */
  121830. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  121831. int rc = SQLITE_OK; /* Return code */
  121832. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  121833. u64 cksum2 = 0; /* Checksum based on %_content contents */
  121834. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  121835. /* This block calculates the checksum according to the FTS index. */
  121836. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  121837. if( rc==SQLITE_OK ){
  121838. int rc2;
  121839. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  121840. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  121841. int iLangid = sqlite3_column_int(pAllLangid, 0);
  121842. int i;
  121843. for(i=0; i<p->nIndex; i++){
  121844. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  121845. }
  121846. }
  121847. rc2 = sqlite3_reset(pAllLangid);
  121848. if( rc==SQLITE_OK ) rc = rc2;
  121849. }
  121850. /* This block calculates the checksum according to the %_content table */
  121851. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  121852. if( rc==SQLITE_OK ){
  121853. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  121854. sqlite3_stmt *pStmt = 0;
  121855. char *zSql;
  121856. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  121857. if( !zSql ){
  121858. rc = SQLITE_NOMEM;
  121859. }else{
  121860. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  121861. sqlite3_free(zSql);
  121862. }
  121863. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  121864. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  121865. int iLang = langidFromSelect(p, pStmt);
  121866. int iCol;
  121867. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  121868. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  121869. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  121870. sqlite3_tokenizer_cursor *pT = 0;
  121871. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  121872. while( rc==SQLITE_OK ){
  121873. char const *zToken; /* Buffer containing token */
  121874. int nToken = 0; /* Number of bytes in token */
  121875. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  121876. int iPos = 0; /* Position of token in zText */
  121877. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  121878. if( rc==SQLITE_OK ){
  121879. int i;
  121880. cksum2 = cksum2 ^ fts3ChecksumEntry(
  121881. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  121882. );
  121883. for(i=1; i<p->nIndex; i++){
  121884. if( p->aIndex[i].nPrefix<=nToken ){
  121885. cksum2 = cksum2 ^ fts3ChecksumEntry(
  121886. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  121887. );
  121888. }
  121889. }
  121890. }
  121891. }
  121892. if( pT ) pModule->xClose(pT);
  121893. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  121894. }
  121895. }
  121896. sqlite3_finalize(pStmt);
  121897. }
  121898. *pbOk = (cksum1==cksum2);
  121899. return rc;
  121900. }
  121901. /*
  121902. ** Run the integrity-check. If no error occurs and the current contents of
  121903. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  121904. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  121905. **
  121906. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  121907. ** error code.
  121908. **
  121909. ** The integrity-check works as follows. For each token and indexed token
  121910. ** prefix in the document set, a 64-bit checksum is calculated (by code
  121911. ** in fts3ChecksumEntry()) based on the following:
  121912. **
  121913. ** + The index number (0 for the main index, 1 for the first prefix
  121914. ** index etc.),
  121915. ** + The token (or token prefix) text itself,
  121916. ** + The language-id of the row it appears in,
  121917. ** + The docid of the row it appears in,
  121918. ** + The column it appears in, and
  121919. ** + The tokens position within that column.
  121920. **
  121921. ** The checksums for all entries in the index are XORed together to create
  121922. ** a single checksum for the entire index.
  121923. **
  121924. ** The integrity-check code calculates the same checksum in two ways:
  121925. **
  121926. ** 1. By scanning the contents of the FTS index, and
  121927. ** 2. By scanning and tokenizing the content table.
  121928. **
  121929. ** If the two checksums are identical, the integrity-check is deemed to have
  121930. ** passed.
  121931. */
  121932. static int fts3DoIntegrityCheck(
  121933. Fts3Table *p /* FTS3 table handle */
  121934. ){
  121935. int rc;
  121936. int bOk = 0;
  121937. rc = fts3IntegrityCheck(p, &bOk);
  121938. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  121939. return rc;
  121940. }
  121941. /*
  121942. ** Handle a 'special' INSERT of the form:
  121943. **
  121944. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  121945. **
  121946. ** Argument pVal contains the result of <expr>. Currently the only
  121947. ** meaningful value to insert is the text 'optimize'.
  121948. */
  121949. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  121950. int rc; /* Return Code */
  121951. const char *zVal = (const char *)sqlite3_value_text(pVal);
  121952. int nVal = sqlite3_value_bytes(pVal);
  121953. if( !zVal ){
  121954. return SQLITE_NOMEM;
  121955. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  121956. rc = fts3DoOptimize(p, 0);
  121957. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  121958. rc = fts3DoRebuild(p);
  121959. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  121960. rc = fts3DoIntegrityCheck(p);
  121961. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  121962. rc = fts3DoIncrmerge(p, &zVal[6]);
  121963. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  121964. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  121965. #ifdef SQLITE_TEST
  121966. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  121967. p->nNodeSize = atoi(&zVal[9]);
  121968. rc = SQLITE_OK;
  121969. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  121970. p->nMaxPendingData = atoi(&zVal[11]);
  121971. rc = SQLITE_OK;
  121972. #endif
  121973. }else{
  121974. rc = SQLITE_ERROR;
  121975. }
  121976. return rc;
  121977. }
  121978. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121979. /*
  121980. ** Delete all cached deferred doclists. Deferred doclists are cached
  121981. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  121982. */
  121983. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  121984. Fts3DeferredToken *pDef;
  121985. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  121986. fts3PendingListDelete(pDef->pList);
  121987. pDef->pList = 0;
  121988. }
  121989. }
  121990. /*
  121991. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  121992. ** this list using sqlite3Fts3DeferToken().
  121993. */
  121994. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  121995. Fts3DeferredToken *pDef;
  121996. Fts3DeferredToken *pNext;
  121997. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  121998. pNext = pDef->pNext;
  121999. fts3PendingListDelete(pDef->pList);
  122000. sqlite3_free(pDef);
  122001. }
  122002. pCsr->pDeferred = 0;
  122003. }
  122004. /*
  122005. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  122006. ** based on the row that pCsr currently points to.
  122007. **
  122008. ** A deferred-doclist is like any other doclist with position information
  122009. ** included, except that it only contains entries for a single row of the
  122010. ** table, not for all rows.
  122011. */
  122012. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  122013. int rc = SQLITE_OK; /* Return code */
  122014. if( pCsr->pDeferred ){
  122015. int i; /* Used to iterate through table columns */
  122016. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  122017. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  122018. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  122019. sqlite3_tokenizer *pT = p->pTokenizer;
  122020. sqlite3_tokenizer_module const *pModule = pT->pModule;
  122021. assert( pCsr->isRequireSeek==0 );
  122022. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  122023. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  122024. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  122025. sqlite3_tokenizer_cursor *pTC = 0;
  122026. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  122027. while( rc==SQLITE_OK ){
  122028. char const *zToken; /* Buffer containing token */
  122029. int nToken = 0; /* Number of bytes in token */
  122030. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  122031. int iPos = 0; /* Position of token in zText */
  122032. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  122033. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  122034. Fts3PhraseToken *pPT = pDef->pToken;
  122035. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  122036. && (pPT->bFirst==0 || iPos==0)
  122037. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  122038. && (0==memcmp(zToken, pPT->z, pPT->n))
  122039. ){
  122040. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  122041. }
  122042. }
  122043. }
  122044. if( pTC ) pModule->xClose(pTC);
  122045. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  122046. }
  122047. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  122048. if( pDef->pList ){
  122049. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  122050. }
  122051. }
  122052. }
  122053. return rc;
  122054. }
  122055. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  122056. Fts3DeferredToken *p,
  122057. char **ppData,
  122058. int *pnData
  122059. ){
  122060. char *pRet;
  122061. int nSkip;
  122062. sqlite3_int64 dummy;
  122063. *ppData = 0;
  122064. *pnData = 0;
  122065. if( p->pList==0 ){
  122066. return SQLITE_OK;
  122067. }
  122068. pRet = (char *)sqlite3_malloc(p->pList->nData);
  122069. if( !pRet ) return SQLITE_NOMEM;
  122070. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  122071. *pnData = p->pList->nData - nSkip;
  122072. *ppData = pRet;
  122073. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  122074. return SQLITE_OK;
  122075. }
  122076. /*
  122077. ** Add an entry for token pToken to the pCsr->pDeferred list.
  122078. */
  122079. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  122080. Fts3Cursor *pCsr, /* Fts3 table cursor */
  122081. Fts3PhraseToken *pToken, /* Token to defer */
  122082. int iCol /* Column that token must appear in (or -1) */
  122083. ){
  122084. Fts3DeferredToken *pDeferred;
  122085. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  122086. if( !pDeferred ){
  122087. return SQLITE_NOMEM;
  122088. }
  122089. memset(pDeferred, 0, sizeof(*pDeferred));
  122090. pDeferred->pToken = pToken;
  122091. pDeferred->pNext = pCsr->pDeferred;
  122092. pDeferred->iCol = iCol;
  122093. pCsr->pDeferred = pDeferred;
  122094. assert( pToken->pDeferred==0 );
  122095. pToken->pDeferred = pDeferred;
  122096. return SQLITE_OK;
  122097. }
  122098. #endif
  122099. /*
  122100. ** SQLite value pRowid contains the rowid of a row that may or may not be
  122101. ** present in the FTS3 table. If it is, delete it and adjust the contents
  122102. ** of subsiduary data structures accordingly.
  122103. */
  122104. static int fts3DeleteByRowid(
  122105. Fts3Table *p,
  122106. sqlite3_value *pRowid,
  122107. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  122108. u32 *aSzDel
  122109. ){
  122110. int rc = SQLITE_OK; /* Return code */
  122111. int bFound = 0; /* True if *pRowid really is in the table */
  122112. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  122113. if( bFound && rc==SQLITE_OK ){
  122114. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  122115. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  122116. if( rc==SQLITE_OK ){
  122117. if( isEmpty ){
  122118. /* Deleting this row means the whole table is empty. In this case
  122119. ** delete the contents of all three tables and throw away any
  122120. ** data in the pendingTerms hash table. */
  122121. rc = fts3DeleteAll(p, 1);
  122122. *pnChng = 0;
  122123. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  122124. }else{
  122125. *pnChng = *pnChng - 1;
  122126. if( p->zContentTbl==0 ){
  122127. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  122128. }
  122129. if( p->bHasDocsize ){
  122130. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  122131. }
  122132. }
  122133. }
  122134. }
  122135. return rc;
  122136. }
  122137. /*
  122138. ** This function does the work for the xUpdate method of FTS3 virtual
  122139. ** tables. The schema of the virtual table being:
  122140. **
  122141. ** CREATE TABLE <table name>(
  122142. ** <user columns>,
  122143. ** <table name> HIDDEN,
  122144. ** docid HIDDEN,
  122145. ** <langid> HIDDEN
  122146. ** );
  122147. **
  122148. **
  122149. */
  122150. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  122151. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  122152. int nArg, /* Size of argument array */
  122153. sqlite3_value **apVal, /* Array of arguments */
  122154. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  122155. ){
  122156. Fts3Table *p = (Fts3Table *)pVtab;
  122157. int rc = SQLITE_OK; /* Return Code */
  122158. int isRemove = 0; /* True for an UPDATE or DELETE */
  122159. u32 *aSzIns = 0; /* Sizes of inserted documents */
  122160. u32 *aSzDel = 0; /* Sizes of deleted documents */
  122161. int nChng = 0; /* Net change in number of documents */
  122162. int bInsertDone = 0;
  122163. assert( p->pSegments==0 );
  122164. assert(
  122165. nArg==1 /* DELETE operations */
  122166. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  122167. );
  122168. /* Check for a "special" INSERT operation. One of the form:
  122169. **
  122170. ** INSERT INTO xyz(xyz) VALUES('command');
  122171. */
  122172. if( nArg>1
  122173. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  122174. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  122175. ){
  122176. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  122177. goto update_out;
  122178. }
  122179. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  122180. rc = SQLITE_CONSTRAINT;
  122181. goto update_out;
  122182. }
  122183. /* Allocate space to hold the change in document sizes */
  122184. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  122185. if( aSzDel==0 ){
  122186. rc = SQLITE_NOMEM;
  122187. goto update_out;
  122188. }
  122189. aSzIns = &aSzDel[p->nColumn+1];
  122190. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  122191. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  122192. ** value, then this operation requires constraint handling.
  122193. **
  122194. ** If the on-conflict mode is REPLACE, this means that the existing row
  122195. ** should be deleted from the database before inserting the new row. Or,
  122196. ** if the on-conflict mode is other than REPLACE, then this method must
  122197. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  122198. ** modify the database file.
  122199. */
  122200. if( nArg>1 && p->zContentTbl==0 ){
  122201. /* Find the value object that holds the new rowid value. */
  122202. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  122203. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  122204. pNewRowid = apVal[1];
  122205. }
  122206. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  122207. sqlite3_value_type(apVal[0])==SQLITE_NULL
  122208. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  122209. )){
  122210. /* The new rowid is not NULL (in this case the rowid will be
  122211. ** automatically assigned and there is no chance of a conflict), and
  122212. ** the statement is either an INSERT or an UPDATE that modifies the
  122213. ** rowid column. So if the conflict mode is REPLACE, then delete any
  122214. ** existing row with rowid=pNewRowid.
  122215. **
  122216. ** Or, if the conflict mode is not REPLACE, insert the new record into
  122217. ** the %_content table. If we hit the duplicate rowid constraint (or any
  122218. ** other error) while doing so, return immediately.
  122219. **
  122220. ** This branch may also run if pNewRowid contains a value that cannot
  122221. ** be losslessly converted to an integer. In this case, the eventual
  122222. ** call to fts3InsertData() (either just below or further on in this
  122223. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  122224. ** invoked, it will delete zero rows (since no row will have
  122225. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  122226. */
  122227. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  122228. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  122229. }else{
  122230. rc = fts3InsertData(p, apVal, pRowid);
  122231. bInsertDone = 1;
  122232. }
  122233. }
  122234. }
  122235. if( rc!=SQLITE_OK ){
  122236. goto update_out;
  122237. }
  122238. /* If this is a DELETE or UPDATE operation, remove the old record. */
  122239. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  122240. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  122241. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  122242. isRemove = 1;
  122243. }
  122244. /* If this is an INSERT or UPDATE operation, insert the new record. */
  122245. if( nArg>1 && rc==SQLITE_OK ){
  122246. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  122247. if( bInsertDone==0 ){
  122248. rc = fts3InsertData(p, apVal, pRowid);
  122249. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  122250. rc = FTS_CORRUPT_VTAB;
  122251. }
  122252. }
  122253. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  122254. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  122255. }
  122256. if( rc==SQLITE_OK ){
  122257. assert( p->iPrevDocid==*pRowid );
  122258. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  122259. }
  122260. if( p->bHasDocsize ){
  122261. fts3InsertDocsize(&rc, p, aSzIns);
  122262. }
  122263. nChng++;
  122264. }
  122265. if( p->bFts4 ){
  122266. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  122267. }
  122268. update_out:
  122269. sqlite3_free(aSzDel);
  122270. sqlite3Fts3SegmentsClose(p);
  122271. return rc;
  122272. }
  122273. /*
  122274. ** Flush any data in the pending-terms hash table to disk. If successful,
  122275. ** merge all segments in the database (including the new segment, if
  122276. ** there was any data to flush) into a single segment.
  122277. */
  122278. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  122279. int rc;
  122280. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  122281. if( rc==SQLITE_OK ){
  122282. rc = fts3DoOptimize(p, 1);
  122283. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  122284. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  122285. if( rc2!=SQLITE_OK ) rc = rc2;
  122286. }else{
  122287. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  122288. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  122289. }
  122290. }
  122291. sqlite3Fts3SegmentsClose(p);
  122292. return rc;
  122293. }
  122294. #endif
  122295. /************** End of fts3_write.c ******************************************/
  122296. /************** Begin file fts3_snippet.c ************************************/
  122297. /*
  122298. ** 2009 Oct 23
  122299. **
  122300. ** The author disclaims copyright to this source code. In place of
  122301. ** a legal notice, here is a blessing:
  122302. **
  122303. ** May you do good and not evil.
  122304. ** May you find forgiveness for yourself and forgive others.
  122305. ** May you share freely, never taking more than you give.
  122306. **
  122307. ******************************************************************************
  122308. */
  122309. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122310. /* #include <string.h> */
  122311. /* #include <assert.h> */
  122312. /*
  122313. ** Characters that may appear in the second argument to matchinfo().
  122314. */
  122315. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  122316. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  122317. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  122318. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  122319. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  122320. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  122321. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  122322. /*
  122323. ** The default value for the second argument to matchinfo().
  122324. */
  122325. #define FTS3_MATCHINFO_DEFAULT "pcx"
  122326. /*
  122327. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  122328. ** Fts3Expr.aDoclist[]/nDoclist.
  122329. */
  122330. typedef struct LoadDoclistCtx LoadDoclistCtx;
  122331. struct LoadDoclistCtx {
  122332. Fts3Cursor *pCsr; /* FTS3 Cursor */
  122333. int nPhrase; /* Number of phrases seen so far */
  122334. int nToken; /* Number of tokens seen so far */
  122335. };
  122336. /*
  122337. ** The following types are used as part of the implementation of the
  122338. ** fts3BestSnippet() routine.
  122339. */
  122340. typedef struct SnippetIter SnippetIter;
  122341. typedef struct SnippetPhrase SnippetPhrase;
  122342. typedef struct SnippetFragment SnippetFragment;
  122343. struct SnippetIter {
  122344. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  122345. int iCol; /* Extract snippet from this column */
  122346. int nSnippet; /* Requested snippet length (in tokens) */
  122347. int nPhrase; /* Number of phrases in query */
  122348. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  122349. int iCurrent; /* First token of current snippet */
  122350. };
  122351. struct SnippetPhrase {
  122352. int nToken; /* Number of tokens in phrase */
  122353. char *pList; /* Pointer to start of phrase position list */
  122354. int iHead; /* Next value in position list */
  122355. char *pHead; /* Position list data following iHead */
  122356. int iTail; /* Next value in trailing position list */
  122357. char *pTail; /* Position list data following iTail */
  122358. };
  122359. struct SnippetFragment {
  122360. int iCol; /* Column snippet is extracted from */
  122361. int iPos; /* Index of first token in snippet */
  122362. u64 covered; /* Mask of query phrases covered */
  122363. u64 hlmask; /* Mask of snippet terms to highlight */
  122364. };
  122365. /*
  122366. ** This type is used as an fts3ExprIterate() context object while
  122367. ** accumulating the data returned by the matchinfo() function.
  122368. */
  122369. typedef struct MatchInfo MatchInfo;
  122370. struct MatchInfo {
  122371. Fts3Cursor *pCursor; /* FTS3 Cursor */
  122372. int nCol; /* Number of columns in table */
  122373. int nPhrase; /* Number of matchable phrases in query */
  122374. sqlite3_int64 nDoc; /* Number of docs in database */
  122375. u32 *aMatchinfo; /* Pre-allocated buffer */
  122376. };
  122377. /*
  122378. ** The snippet() and offsets() functions both return text values. An instance
  122379. ** of the following structure is used to accumulate those values while the
  122380. ** functions are running. See fts3StringAppend() for details.
  122381. */
  122382. typedef struct StrBuffer StrBuffer;
  122383. struct StrBuffer {
  122384. char *z; /* Pointer to buffer containing string */
  122385. int n; /* Length of z in bytes (excl. nul-term) */
  122386. int nAlloc; /* Allocated size of buffer z in bytes */
  122387. };
  122388. /*
  122389. ** This function is used to help iterate through a position-list. A position
  122390. ** list is a list of unique integers, sorted from smallest to largest. Each
  122391. ** element of the list is represented by an FTS3 varint that takes the value
  122392. ** of the difference between the current element and the previous one plus
  122393. ** two. For example, to store the position-list:
  122394. **
  122395. ** 4 9 113
  122396. **
  122397. ** the three varints:
  122398. **
  122399. ** 6 7 106
  122400. **
  122401. ** are encoded.
  122402. **
  122403. ** When this function is called, *pp points to the start of an element of
  122404. ** the list. *piPos contains the value of the previous entry in the list.
  122405. ** After it returns, *piPos contains the value of the next element of the
  122406. ** list and *pp is advanced to the following varint.
  122407. */
  122408. static void fts3GetDeltaPosition(char **pp, int *piPos){
  122409. int iVal;
  122410. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  122411. *piPos += (iVal-2);
  122412. }
  122413. /*
  122414. ** Helper function for fts3ExprIterate() (see below).
  122415. */
  122416. static int fts3ExprIterate2(
  122417. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  122418. int *piPhrase, /* Pointer to phrase counter */
  122419. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  122420. void *pCtx /* Second argument to pass to callback */
  122421. ){
  122422. int rc; /* Return code */
  122423. int eType = pExpr->eType; /* Type of expression node pExpr */
  122424. if( eType!=FTSQUERY_PHRASE ){
  122425. assert( pExpr->pLeft && pExpr->pRight );
  122426. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  122427. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  122428. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  122429. }
  122430. }else{
  122431. rc = x(pExpr, *piPhrase, pCtx);
  122432. (*piPhrase)++;
  122433. }
  122434. return rc;
  122435. }
  122436. /*
  122437. ** Iterate through all phrase nodes in an FTS3 query, except those that
  122438. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  122439. ** For each phrase node found, the supplied callback function is invoked.
  122440. **
  122441. ** If the callback function returns anything other than SQLITE_OK,
  122442. ** the iteration is abandoned and the error code returned immediately.
  122443. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  122444. ** all eligible phrase nodes.
  122445. */
  122446. static int fts3ExprIterate(
  122447. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  122448. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  122449. void *pCtx /* Second argument to pass to callback */
  122450. ){
  122451. int iPhrase = 0; /* Variable used as the phrase counter */
  122452. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  122453. }
  122454. /*
  122455. ** This is an fts3ExprIterate() callback used while loading the doclists
  122456. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  122457. ** fts3ExprLoadDoclists().
  122458. */
  122459. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  122460. int rc = SQLITE_OK;
  122461. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122462. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  122463. UNUSED_PARAMETER(iPhrase);
  122464. p->nPhrase++;
  122465. p->nToken += pPhrase->nToken;
  122466. return rc;
  122467. }
  122468. /*
  122469. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  122470. ** pCsr.
  122471. **
  122472. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  122473. ** phrases in the expression (all phrases except those directly or
  122474. ** indirectly descended from the right-hand-side of a NOT operator). If
  122475. ** pnToken is not NULL, then it is set to the number of tokens in all
  122476. ** matchable phrases of the expression.
  122477. */
  122478. static int fts3ExprLoadDoclists(
  122479. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  122480. int *pnPhrase, /* OUT: Number of phrases in query */
  122481. int *pnToken /* OUT: Number of tokens in query */
  122482. ){
  122483. int rc; /* Return Code */
  122484. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  122485. sCtx.pCsr = pCsr;
  122486. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  122487. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  122488. if( pnToken ) *pnToken = sCtx.nToken;
  122489. return rc;
  122490. }
  122491. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  122492. (*(int *)ctx)++;
  122493. UNUSED_PARAMETER(pExpr);
  122494. UNUSED_PARAMETER(iPhrase);
  122495. return SQLITE_OK;
  122496. }
  122497. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  122498. int nPhrase = 0;
  122499. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  122500. return nPhrase;
  122501. }
  122502. /*
  122503. ** Advance the position list iterator specified by the first two
  122504. ** arguments so that it points to the first element with a value greater
  122505. ** than or equal to parameter iNext.
  122506. */
  122507. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  122508. char *pIter = *ppIter;
  122509. if( pIter ){
  122510. int iIter = *piIter;
  122511. while( iIter<iNext ){
  122512. if( 0==(*pIter & 0xFE) ){
  122513. iIter = -1;
  122514. pIter = 0;
  122515. break;
  122516. }
  122517. fts3GetDeltaPosition(&pIter, &iIter);
  122518. }
  122519. *piIter = iIter;
  122520. *ppIter = pIter;
  122521. }
  122522. }
  122523. /*
  122524. ** Advance the snippet iterator to the next candidate snippet.
  122525. */
  122526. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  122527. int i; /* Loop counter */
  122528. if( pIter->iCurrent<0 ){
  122529. /* The SnippetIter object has just been initialized. The first snippet
  122530. ** candidate always starts at offset 0 (even if this candidate has a
  122531. ** score of 0.0).
  122532. */
  122533. pIter->iCurrent = 0;
  122534. /* Advance the 'head' iterator of each phrase to the first offset that
  122535. ** is greater than or equal to (iNext+nSnippet).
  122536. */
  122537. for(i=0; i<pIter->nPhrase; i++){
  122538. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  122539. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  122540. }
  122541. }else{
  122542. int iStart;
  122543. int iEnd = 0x7FFFFFFF;
  122544. for(i=0; i<pIter->nPhrase; i++){
  122545. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  122546. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  122547. iEnd = pPhrase->iHead;
  122548. }
  122549. }
  122550. if( iEnd==0x7FFFFFFF ){
  122551. return 1;
  122552. }
  122553. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  122554. for(i=0; i<pIter->nPhrase; i++){
  122555. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  122556. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  122557. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  122558. }
  122559. }
  122560. return 0;
  122561. }
  122562. /*
  122563. ** Retrieve information about the current candidate snippet of snippet
  122564. ** iterator pIter.
  122565. */
  122566. static void fts3SnippetDetails(
  122567. SnippetIter *pIter, /* Snippet iterator */
  122568. u64 mCovered, /* Bitmask of phrases already covered */
  122569. int *piToken, /* OUT: First token of proposed snippet */
  122570. int *piScore, /* OUT: "Score" for this snippet */
  122571. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  122572. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  122573. ){
  122574. int iStart = pIter->iCurrent; /* First token of snippet */
  122575. int iScore = 0; /* Score of this snippet */
  122576. int i; /* Loop counter */
  122577. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  122578. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  122579. for(i=0; i<pIter->nPhrase; i++){
  122580. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  122581. if( pPhrase->pTail ){
  122582. char *pCsr = pPhrase->pTail;
  122583. int iCsr = pPhrase->iTail;
  122584. while( iCsr<(iStart+pIter->nSnippet) ){
  122585. int j;
  122586. u64 mPhrase = (u64)1 << i;
  122587. u64 mPos = (u64)1 << (iCsr - iStart);
  122588. assert( iCsr>=iStart );
  122589. if( (mCover|mCovered)&mPhrase ){
  122590. iScore++;
  122591. }else{
  122592. iScore += 1000;
  122593. }
  122594. mCover |= mPhrase;
  122595. for(j=0; j<pPhrase->nToken; j++){
  122596. mHighlight |= (mPos>>j);
  122597. }
  122598. if( 0==(*pCsr & 0x0FE) ) break;
  122599. fts3GetDeltaPosition(&pCsr, &iCsr);
  122600. }
  122601. }
  122602. }
  122603. /* Set the output variables before returning. */
  122604. *piToken = iStart;
  122605. *piScore = iScore;
  122606. *pmCover = mCover;
  122607. *pmHighlight = mHighlight;
  122608. }
  122609. /*
  122610. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  122611. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  122612. */
  122613. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  122614. SnippetIter *p = (SnippetIter *)ctx;
  122615. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  122616. char *pCsr;
  122617. int rc;
  122618. pPhrase->nToken = pExpr->pPhrase->nToken;
  122619. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  122620. assert( rc==SQLITE_OK || pCsr==0 );
  122621. if( pCsr ){
  122622. int iFirst = 0;
  122623. pPhrase->pList = pCsr;
  122624. fts3GetDeltaPosition(&pCsr, &iFirst);
  122625. assert( iFirst>=0 );
  122626. pPhrase->pHead = pCsr;
  122627. pPhrase->pTail = pCsr;
  122628. pPhrase->iHead = iFirst;
  122629. pPhrase->iTail = iFirst;
  122630. }else{
  122631. assert( rc!=SQLITE_OK || (
  122632. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  122633. ));
  122634. }
  122635. return rc;
  122636. }
  122637. /*
  122638. ** Select the fragment of text consisting of nFragment contiguous tokens
  122639. ** from column iCol that represent the "best" snippet. The best snippet
  122640. ** is the snippet with the highest score, where scores are calculated
  122641. ** by adding:
  122642. **
  122643. ** (a) +1 point for each occurence of a matchable phrase in the snippet.
  122644. **
  122645. ** (b) +1000 points for the first occurence of each matchable phrase in
  122646. ** the snippet for which the corresponding mCovered bit is not set.
  122647. **
  122648. ** The selected snippet parameters are stored in structure *pFragment before
  122649. ** returning. The score of the selected snippet is stored in *piScore
  122650. ** before returning.
  122651. */
  122652. static int fts3BestSnippet(
  122653. int nSnippet, /* Desired snippet length */
  122654. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  122655. int iCol, /* Index of column to create snippet from */
  122656. u64 mCovered, /* Mask of phrases already covered */
  122657. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  122658. SnippetFragment *pFragment, /* OUT: Best snippet found */
  122659. int *piScore /* OUT: Score of snippet pFragment */
  122660. ){
  122661. int rc; /* Return Code */
  122662. int nList; /* Number of phrases in expression */
  122663. SnippetIter sIter; /* Iterates through snippet candidates */
  122664. int nByte; /* Number of bytes of space to allocate */
  122665. int iBestScore = -1; /* Best snippet score found so far */
  122666. int i; /* Loop counter */
  122667. memset(&sIter, 0, sizeof(sIter));
  122668. /* Iterate through the phrases in the expression to count them. The same
  122669. ** callback makes sure the doclists are loaded for each phrase.
  122670. */
  122671. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  122672. if( rc!=SQLITE_OK ){
  122673. return rc;
  122674. }
  122675. /* Now that it is known how many phrases there are, allocate and zero
  122676. ** the required space using malloc().
  122677. */
  122678. nByte = sizeof(SnippetPhrase) * nList;
  122679. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  122680. if( !sIter.aPhrase ){
  122681. return SQLITE_NOMEM;
  122682. }
  122683. memset(sIter.aPhrase, 0, nByte);
  122684. /* Initialize the contents of the SnippetIter object. Then iterate through
  122685. ** the set of phrases in the expression to populate the aPhrase[] array.
  122686. */
  122687. sIter.pCsr = pCsr;
  122688. sIter.iCol = iCol;
  122689. sIter.nSnippet = nSnippet;
  122690. sIter.nPhrase = nList;
  122691. sIter.iCurrent = -1;
  122692. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  122693. /* Set the *pmSeen output variable. */
  122694. for(i=0; i<nList; i++){
  122695. if( sIter.aPhrase[i].pHead ){
  122696. *pmSeen |= (u64)1 << i;
  122697. }
  122698. }
  122699. /* Loop through all candidate snippets. Store the best snippet in
  122700. ** *pFragment. Store its associated 'score' in iBestScore.
  122701. */
  122702. pFragment->iCol = iCol;
  122703. while( !fts3SnippetNextCandidate(&sIter) ){
  122704. int iPos;
  122705. int iScore;
  122706. u64 mCover;
  122707. u64 mHighlight;
  122708. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  122709. assert( iScore>=0 );
  122710. if( iScore>iBestScore ){
  122711. pFragment->iPos = iPos;
  122712. pFragment->hlmask = mHighlight;
  122713. pFragment->covered = mCover;
  122714. iBestScore = iScore;
  122715. }
  122716. }
  122717. sqlite3_free(sIter.aPhrase);
  122718. *piScore = iBestScore;
  122719. return SQLITE_OK;
  122720. }
  122721. /*
  122722. ** Append a string to the string-buffer passed as the first argument.
  122723. **
  122724. ** If nAppend is negative, then the length of the string zAppend is
  122725. ** determined using strlen().
  122726. */
  122727. static int fts3StringAppend(
  122728. StrBuffer *pStr, /* Buffer to append to */
  122729. const char *zAppend, /* Pointer to data to append to buffer */
  122730. int nAppend /* Size of zAppend in bytes (or -1) */
  122731. ){
  122732. if( nAppend<0 ){
  122733. nAppend = (int)strlen(zAppend);
  122734. }
  122735. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  122736. ** to grow the buffer until so that it is big enough to accomadate the
  122737. ** appended data.
  122738. */
  122739. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  122740. int nAlloc = pStr->nAlloc+nAppend+100;
  122741. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  122742. if( !zNew ){
  122743. return SQLITE_NOMEM;
  122744. }
  122745. pStr->z = zNew;
  122746. pStr->nAlloc = nAlloc;
  122747. }
  122748. /* Append the data to the string buffer. */
  122749. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  122750. pStr->n += nAppend;
  122751. pStr->z[pStr->n] = '\0';
  122752. return SQLITE_OK;
  122753. }
  122754. /*
  122755. ** The fts3BestSnippet() function often selects snippets that end with a
  122756. ** query term. That is, the final term of the snippet is always a term
  122757. ** that requires highlighting. For example, if 'X' is a highlighted term
  122758. ** and '.' is a non-highlighted term, BestSnippet() may select:
  122759. **
  122760. ** ........X.....X
  122761. **
  122762. ** This function "shifts" the beginning of the snippet forward in the
  122763. ** document so that there are approximately the same number of
  122764. ** non-highlighted terms to the right of the final highlighted term as there
  122765. ** are to the left of the first highlighted term. For example, to this:
  122766. **
  122767. ** ....X.....X....
  122768. **
  122769. ** This is done as part of extracting the snippet text, not when selecting
  122770. ** the snippet. Snippet selection is done based on doclists only, so there
  122771. ** is no way for fts3BestSnippet() to know whether or not the document
  122772. ** actually contains terms that follow the final highlighted term.
  122773. */
  122774. static int fts3SnippetShift(
  122775. Fts3Table *pTab, /* FTS3 table snippet comes from */
  122776. int iLangid, /* Language id to use in tokenizing */
  122777. int nSnippet, /* Number of tokens desired for snippet */
  122778. const char *zDoc, /* Document text to extract snippet from */
  122779. int nDoc, /* Size of buffer zDoc in bytes */
  122780. int *piPos, /* IN/OUT: First token of snippet */
  122781. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  122782. ){
  122783. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  122784. if( hlmask ){
  122785. int nLeft; /* Tokens to the left of first highlight */
  122786. int nRight; /* Tokens to the right of last highlight */
  122787. int nDesired; /* Ideal number of tokens to shift forward */
  122788. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  122789. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  122790. nDesired = (nLeft-nRight)/2;
  122791. /* Ideally, the start of the snippet should be pushed forward in the
  122792. ** document nDesired tokens. This block checks if there are actually
  122793. ** nDesired tokens to the right of the snippet. If so, *piPos and
  122794. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  122795. ** right. Otherwise, the snippet is shifted by the number of tokens
  122796. ** available.
  122797. */
  122798. if( nDesired>0 ){
  122799. int nShift; /* Number of tokens to shift snippet by */
  122800. int iCurrent = 0; /* Token counter */
  122801. int rc; /* Return Code */
  122802. sqlite3_tokenizer_module *pMod;
  122803. sqlite3_tokenizer_cursor *pC;
  122804. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  122805. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  122806. ** or more tokens in zDoc/nDoc.
  122807. */
  122808. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  122809. if( rc!=SQLITE_OK ){
  122810. return rc;
  122811. }
  122812. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  122813. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  122814. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  122815. }
  122816. pMod->xClose(pC);
  122817. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  122818. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  122819. assert( nShift<=nDesired );
  122820. if( nShift>0 ){
  122821. *piPos += nShift;
  122822. *pHlmask = hlmask >> nShift;
  122823. }
  122824. }
  122825. }
  122826. return SQLITE_OK;
  122827. }
  122828. /*
  122829. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  122830. ** append it to string buffer pOut.
  122831. */
  122832. static int fts3SnippetText(
  122833. Fts3Cursor *pCsr, /* FTS3 Cursor */
  122834. SnippetFragment *pFragment, /* Snippet to extract */
  122835. int iFragment, /* Fragment number */
  122836. int isLast, /* True for final fragment in snippet */
  122837. int nSnippet, /* Number of tokens in extracted snippet */
  122838. const char *zOpen, /* String inserted before highlighted term */
  122839. const char *zClose, /* String inserted after highlighted term */
  122840. const char *zEllipsis, /* String inserted between snippets */
  122841. StrBuffer *pOut /* Write output here */
  122842. ){
  122843. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122844. int rc; /* Return code */
  122845. const char *zDoc; /* Document text to extract snippet from */
  122846. int nDoc; /* Size of zDoc in bytes */
  122847. int iCurrent = 0; /* Current token number of document */
  122848. int iEnd = 0; /* Byte offset of end of current token */
  122849. int isShiftDone = 0; /* True after snippet is shifted */
  122850. int iPos = pFragment->iPos; /* First token of snippet */
  122851. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  122852. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  122853. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  122854. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  122855. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  122856. if( zDoc==0 ){
  122857. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  122858. return SQLITE_NOMEM;
  122859. }
  122860. return SQLITE_OK;
  122861. }
  122862. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  122863. /* Open a token cursor on the document. */
  122864. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  122865. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  122866. if( rc!=SQLITE_OK ){
  122867. return rc;
  122868. }
  122869. while( rc==SQLITE_OK ){
  122870. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  122871. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  122872. int iBegin = 0; /* Offset in zDoc of start of token */
  122873. int iFin = 0; /* Offset in zDoc of end of token */
  122874. int isHighlight = 0; /* True for highlighted terms */
  122875. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  122876. ** in the FTS code the variable that the third argument to xNext points to
  122877. ** is initialized to zero before the first (*but not necessarily
  122878. ** subsequent*) call to xNext(). This is done for a particular application
  122879. ** that needs to know whether or not the tokenizer is being used for
  122880. ** snippet generation or for some other purpose.
  122881. **
  122882. ** Extreme care is required when writing code to depend on this
  122883. ** initialization. It is not a documented part of the tokenizer interface.
  122884. ** If a tokenizer is used directly by any code outside of FTS, this
  122885. ** convention might not be respected. */
  122886. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  122887. if( rc!=SQLITE_OK ){
  122888. if( rc==SQLITE_DONE ){
  122889. /* Special case - the last token of the snippet is also the last token
  122890. ** of the column. Append any punctuation that occurred between the end
  122891. ** of the previous token and the end of the document to the output.
  122892. ** Then break out of the loop. */
  122893. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  122894. }
  122895. break;
  122896. }
  122897. if( iCurrent<iPos ){ continue; }
  122898. if( !isShiftDone ){
  122899. int n = nDoc - iBegin;
  122900. rc = fts3SnippetShift(
  122901. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  122902. );
  122903. isShiftDone = 1;
  122904. /* Now that the shift has been done, check if the initial "..." are
  122905. ** required. They are required if (a) this is not the first fragment,
  122906. ** or (b) this fragment does not begin at position 0 of its column.
  122907. */
  122908. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  122909. rc = fts3StringAppend(pOut, zEllipsis, -1);
  122910. }
  122911. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  122912. }
  122913. if( iCurrent>=(iPos+nSnippet) ){
  122914. if( isLast ){
  122915. rc = fts3StringAppend(pOut, zEllipsis, -1);
  122916. }
  122917. break;
  122918. }
  122919. /* Set isHighlight to true if this term should be highlighted. */
  122920. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  122921. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  122922. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  122923. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  122924. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  122925. iEnd = iFin;
  122926. }
  122927. pMod->xClose(pC);
  122928. return rc;
  122929. }
  122930. /*
  122931. ** This function is used to count the entries in a column-list (a
  122932. ** delta-encoded list of term offsets within a single column of a single
  122933. ** row). When this function is called, *ppCollist should point to the
  122934. ** beginning of the first varint in the column-list (the varint that
  122935. ** contains the position of the first matching term in the column data).
  122936. ** Before returning, *ppCollist is set to point to the first byte after
  122937. ** the last varint in the column-list (either the 0x00 signifying the end
  122938. ** of the position-list, or the 0x01 that precedes the column number of
  122939. ** the next column in the position-list).
  122940. **
  122941. ** The number of elements in the column-list is returned.
  122942. */
  122943. static int fts3ColumnlistCount(char **ppCollist){
  122944. char *pEnd = *ppCollist;
  122945. char c = 0;
  122946. int nEntry = 0;
  122947. /* A column-list is terminated by either a 0x01 or 0x00. */
  122948. while( 0xFE & (*pEnd | c) ){
  122949. c = *pEnd++ & 0x80;
  122950. if( !c ) nEntry++;
  122951. }
  122952. *ppCollist = pEnd;
  122953. return nEntry;
  122954. }
  122955. /*
  122956. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  122957. ** for a single query.
  122958. **
  122959. ** fts3ExprIterate() callback to load the 'global' elements of a
  122960. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  122961. ** of the matchinfo array that are constant for all rows returned by the
  122962. ** current query.
  122963. **
  122964. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  122965. ** function populates Matchinfo.aMatchinfo[] as follows:
  122966. **
  122967. ** for(iCol=0; iCol<nCol; iCol++){
  122968. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  122969. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  122970. ** }
  122971. **
  122972. ** where X is the number of matches for phrase iPhrase is column iCol of all
  122973. ** rows of the table. Y is the number of rows for which column iCol contains
  122974. ** at least one instance of phrase iPhrase.
  122975. **
  122976. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  122977. ** Y values are set to nDoc, where nDoc is the number of documents in the
  122978. ** file system. This is done because the full-text index doclist is required
  122979. ** to calculate these values properly, and the full-text index doclist is
  122980. ** not available for deferred tokens.
  122981. */
  122982. static int fts3ExprGlobalHitsCb(
  122983. Fts3Expr *pExpr, /* Phrase expression node */
  122984. int iPhrase, /* Phrase number (numbered from zero) */
  122985. void *pCtx /* Pointer to MatchInfo structure */
  122986. ){
  122987. MatchInfo *p = (MatchInfo *)pCtx;
  122988. return sqlite3Fts3EvalPhraseStats(
  122989. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  122990. );
  122991. }
  122992. /*
  122993. ** fts3ExprIterate() callback used to collect the "local" part of the
  122994. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  122995. ** array that are different for each row returned by the query.
  122996. */
  122997. static int fts3ExprLocalHitsCb(
  122998. Fts3Expr *pExpr, /* Phrase expression node */
  122999. int iPhrase, /* Phrase number */
  123000. void *pCtx /* Pointer to MatchInfo structure */
  123001. ){
  123002. int rc = SQLITE_OK;
  123003. MatchInfo *p = (MatchInfo *)pCtx;
  123004. int iStart = iPhrase * p->nCol * 3;
  123005. int i;
  123006. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  123007. char *pCsr;
  123008. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  123009. if( pCsr ){
  123010. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  123011. }else{
  123012. p->aMatchinfo[iStart+i*3] = 0;
  123013. }
  123014. }
  123015. return rc;
  123016. }
  123017. static int fts3MatchinfoCheck(
  123018. Fts3Table *pTab,
  123019. char cArg,
  123020. char **pzErr
  123021. ){
  123022. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  123023. || (cArg==FTS3_MATCHINFO_NCOL)
  123024. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  123025. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  123026. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  123027. || (cArg==FTS3_MATCHINFO_LCS)
  123028. || (cArg==FTS3_MATCHINFO_HITS)
  123029. ){
  123030. return SQLITE_OK;
  123031. }
  123032. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  123033. return SQLITE_ERROR;
  123034. }
  123035. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  123036. int nVal; /* Number of integers output by cArg */
  123037. switch( cArg ){
  123038. case FTS3_MATCHINFO_NDOC:
  123039. case FTS3_MATCHINFO_NPHRASE:
  123040. case FTS3_MATCHINFO_NCOL:
  123041. nVal = 1;
  123042. break;
  123043. case FTS3_MATCHINFO_AVGLENGTH:
  123044. case FTS3_MATCHINFO_LENGTH:
  123045. case FTS3_MATCHINFO_LCS:
  123046. nVal = pInfo->nCol;
  123047. break;
  123048. default:
  123049. assert( cArg==FTS3_MATCHINFO_HITS );
  123050. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  123051. break;
  123052. }
  123053. return nVal;
  123054. }
  123055. static int fts3MatchinfoSelectDoctotal(
  123056. Fts3Table *pTab,
  123057. sqlite3_stmt **ppStmt,
  123058. sqlite3_int64 *pnDoc,
  123059. const char **paLen
  123060. ){
  123061. sqlite3_stmt *pStmt;
  123062. const char *a;
  123063. sqlite3_int64 nDoc;
  123064. if( !*ppStmt ){
  123065. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  123066. if( rc!=SQLITE_OK ) return rc;
  123067. }
  123068. pStmt = *ppStmt;
  123069. assert( sqlite3_data_count(pStmt)==1 );
  123070. a = sqlite3_column_blob(pStmt, 0);
  123071. a += sqlite3Fts3GetVarint(a, &nDoc);
  123072. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  123073. *pnDoc = (u32)nDoc;
  123074. if( paLen ) *paLen = a;
  123075. return SQLITE_OK;
  123076. }
  123077. /*
  123078. ** An instance of the following structure is used to store state while
  123079. ** iterating through a multi-column position-list corresponding to the
  123080. ** hits for a single phrase on a single row in order to calculate the
  123081. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  123082. */
  123083. typedef struct LcsIterator LcsIterator;
  123084. struct LcsIterator {
  123085. Fts3Expr *pExpr; /* Pointer to phrase expression */
  123086. int iPosOffset; /* Tokens count up to end of this phrase */
  123087. char *pRead; /* Cursor used to iterate through aDoclist */
  123088. int iPos; /* Current position */
  123089. };
  123090. /*
  123091. ** If LcsIterator.iCol is set to the following value, the iterator has
  123092. ** finished iterating through all offsets for all columns.
  123093. */
  123094. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  123095. static int fts3MatchinfoLcsCb(
  123096. Fts3Expr *pExpr, /* Phrase expression node */
  123097. int iPhrase, /* Phrase number (numbered from zero) */
  123098. void *pCtx /* Pointer to MatchInfo structure */
  123099. ){
  123100. LcsIterator *aIter = (LcsIterator *)pCtx;
  123101. aIter[iPhrase].pExpr = pExpr;
  123102. return SQLITE_OK;
  123103. }
  123104. /*
  123105. ** Advance the iterator passed as an argument to the next position. Return
  123106. ** 1 if the iterator is at EOF or if it now points to the start of the
  123107. ** position list for the next column.
  123108. */
  123109. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  123110. char *pRead = pIter->pRead;
  123111. sqlite3_int64 iRead;
  123112. int rc = 0;
  123113. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  123114. if( iRead==0 || iRead==1 ){
  123115. pRead = 0;
  123116. rc = 1;
  123117. }else{
  123118. pIter->iPos += (int)(iRead-2);
  123119. }
  123120. pIter->pRead = pRead;
  123121. return rc;
  123122. }
  123123. /*
  123124. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  123125. **
  123126. ** If the call is successful, the longest-common-substring lengths for each
  123127. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  123128. ** array before returning. SQLITE_OK is returned in this case.
  123129. **
  123130. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  123131. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  123132. ** undefined.
  123133. */
  123134. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  123135. LcsIterator *aIter;
  123136. int i;
  123137. int iCol;
  123138. int nToken = 0;
  123139. /* Allocate and populate the array of LcsIterator objects. The array
  123140. ** contains one element for each matchable phrase in the query.
  123141. **/
  123142. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  123143. if( !aIter ) return SQLITE_NOMEM;
  123144. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  123145. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  123146. for(i=0; i<pInfo->nPhrase; i++){
  123147. LcsIterator *pIter = &aIter[i];
  123148. nToken -= pIter->pExpr->pPhrase->nToken;
  123149. pIter->iPosOffset = nToken;
  123150. }
  123151. for(iCol=0; iCol<pInfo->nCol; iCol++){
  123152. int nLcs = 0; /* LCS value for this column */
  123153. int nLive = 0; /* Number of iterators in aIter not at EOF */
  123154. for(i=0; i<pInfo->nPhrase; i++){
  123155. int rc;
  123156. LcsIterator *pIt = &aIter[i];
  123157. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  123158. if( rc!=SQLITE_OK ) return rc;
  123159. if( pIt->pRead ){
  123160. pIt->iPos = pIt->iPosOffset;
  123161. fts3LcsIteratorAdvance(&aIter[i]);
  123162. nLive++;
  123163. }
  123164. }
  123165. while( nLive>0 ){
  123166. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  123167. int nThisLcs = 0; /* LCS for the current iterator positions */
  123168. for(i=0; i<pInfo->nPhrase; i++){
  123169. LcsIterator *pIter = &aIter[i];
  123170. if( pIter->pRead==0 ){
  123171. /* This iterator is already at EOF for this column. */
  123172. nThisLcs = 0;
  123173. }else{
  123174. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  123175. pAdv = pIter;
  123176. }
  123177. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  123178. nThisLcs++;
  123179. }else{
  123180. nThisLcs = 1;
  123181. }
  123182. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  123183. }
  123184. }
  123185. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  123186. }
  123187. pInfo->aMatchinfo[iCol] = nLcs;
  123188. }
  123189. sqlite3_free(aIter);
  123190. return SQLITE_OK;
  123191. }
  123192. /*
  123193. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  123194. ** be returned by the matchinfo() function. Argument zArg contains the
  123195. ** format string passed as the second argument to matchinfo (or the
  123196. ** default value "pcx" if no second argument was specified). The format
  123197. ** string has already been validated and the pInfo->aMatchinfo[] array
  123198. ** is guaranteed to be large enough for the output.
  123199. **
  123200. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  123201. ** If it is false, then assume that those fields that do not change between
  123202. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  123203. ** have already been populated.
  123204. **
  123205. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  123206. ** occurs. If a value other than SQLITE_OK is returned, the state the
  123207. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  123208. */
  123209. static int fts3MatchinfoValues(
  123210. Fts3Cursor *pCsr, /* FTS3 cursor object */
  123211. int bGlobal, /* True to grab the global stats */
  123212. MatchInfo *pInfo, /* Matchinfo context object */
  123213. const char *zArg /* Matchinfo format string */
  123214. ){
  123215. int rc = SQLITE_OK;
  123216. int i;
  123217. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  123218. sqlite3_stmt *pSelect = 0;
  123219. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  123220. switch( zArg[i] ){
  123221. case FTS3_MATCHINFO_NPHRASE:
  123222. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  123223. break;
  123224. case FTS3_MATCHINFO_NCOL:
  123225. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  123226. break;
  123227. case FTS3_MATCHINFO_NDOC:
  123228. if( bGlobal ){
  123229. sqlite3_int64 nDoc = 0;
  123230. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  123231. pInfo->aMatchinfo[0] = (u32)nDoc;
  123232. }
  123233. break;
  123234. case FTS3_MATCHINFO_AVGLENGTH:
  123235. if( bGlobal ){
  123236. sqlite3_int64 nDoc; /* Number of rows in table */
  123237. const char *a; /* Aggregate column length array */
  123238. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  123239. if( rc==SQLITE_OK ){
  123240. int iCol;
  123241. for(iCol=0; iCol<pInfo->nCol; iCol++){
  123242. u32 iVal;
  123243. sqlite3_int64 nToken;
  123244. a += sqlite3Fts3GetVarint(a, &nToken);
  123245. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  123246. pInfo->aMatchinfo[iCol] = iVal;
  123247. }
  123248. }
  123249. }
  123250. break;
  123251. case FTS3_MATCHINFO_LENGTH: {
  123252. sqlite3_stmt *pSelectDocsize = 0;
  123253. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  123254. if( rc==SQLITE_OK ){
  123255. int iCol;
  123256. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  123257. for(iCol=0; iCol<pInfo->nCol; iCol++){
  123258. sqlite3_int64 nToken;
  123259. a += sqlite3Fts3GetVarint(a, &nToken);
  123260. pInfo->aMatchinfo[iCol] = (u32)nToken;
  123261. }
  123262. }
  123263. sqlite3_reset(pSelectDocsize);
  123264. break;
  123265. }
  123266. case FTS3_MATCHINFO_LCS:
  123267. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  123268. if( rc==SQLITE_OK ){
  123269. rc = fts3MatchinfoLcs(pCsr, pInfo);
  123270. }
  123271. break;
  123272. default: {
  123273. Fts3Expr *pExpr;
  123274. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  123275. pExpr = pCsr->pExpr;
  123276. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  123277. if( rc!=SQLITE_OK ) break;
  123278. if( bGlobal ){
  123279. if( pCsr->pDeferred ){
  123280. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  123281. if( rc!=SQLITE_OK ) break;
  123282. }
  123283. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  123284. if( rc!=SQLITE_OK ) break;
  123285. }
  123286. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  123287. break;
  123288. }
  123289. }
  123290. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  123291. }
  123292. sqlite3_reset(pSelect);
  123293. return rc;
  123294. }
  123295. /*
  123296. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  123297. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  123298. */
  123299. static int fts3GetMatchinfo(
  123300. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  123301. const char *zArg /* Second argument to matchinfo() function */
  123302. ){
  123303. MatchInfo sInfo;
  123304. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  123305. int rc = SQLITE_OK;
  123306. int bGlobal = 0; /* Collect 'global' stats as well as local */
  123307. memset(&sInfo, 0, sizeof(MatchInfo));
  123308. sInfo.pCursor = pCsr;
  123309. sInfo.nCol = pTab->nColumn;
  123310. /* If there is cached matchinfo() data, but the format string for the
  123311. ** cache does not match the format string for this request, discard
  123312. ** the cached data. */
  123313. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  123314. assert( pCsr->aMatchinfo );
  123315. sqlite3_free(pCsr->aMatchinfo);
  123316. pCsr->zMatchinfo = 0;
  123317. pCsr->aMatchinfo = 0;
  123318. }
  123319. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  123320. ** matchinfo function has been called for this query. In this case
  123321. ** allocate the array used to accumulate the matchinfo data and
  123322. ** initialize those elements that are constant for every row.
  123323. */
  123324. if( pCsr->aMatchinfo==0 ){
  123325. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  123326. int nArg; /* Bytes in zArg */
  123327. int i; /* Used to iterate through zArg */
  123328. /* Determine the number of phrases in the query */
  123329. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  123330. sInfo.nPhrase = pCsr->nPhrase;
  123331. /* Determine the number of integers in the buffer returned by this call. */
  123332. for(i=0; zArg[i]; i++){
  123333. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  123334. }
  123335. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  123336. nArg = (int)strlen(zArg);
  123337. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  123338. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  123339. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  123340. pCsr->nMatchinfo = nMatchinfo;
  123341. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  123342. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  123343. pCsr->isMatchinfoNeeded = 1;
  123344. bGlobal = 1;
  123345. }
  123346. sInfo.aMatchinfo = pCsr->aMatchinfo;
  123347. sInfo.nPhrase = pCsr->nPhrase;
  123348. if( pCsr->isMatchinfoNeeded ){
  123349. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  123350. pCsr->isMatchinfoNeeded = 0;
  123351. }
  123352. return rc;
  123353. }
  123354. /*
  123355. ** Implementation of snippet() function.
  123356. */
  123357. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  123358. sqlite3_context *pCtx, /* SQLite function call context */
  123359. Fts3Cursor *pCsr, /* Cursor object */
  123360. const char *zStart, /* Snippet start text - "<b>" */
  123361. const char *zEnd, /* Snippet end text - "</b>" */
  123362. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  123363. int iCol, /* Extract snippet from this column */
  123364. int nToken /* Approximate number of tokens in snippet */
  123365. ){
  123366. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  123367. int rc = SQLITE_OK;
  123368. int i;
  123369. StrBuffer res = {0, 0, 0};
  123370. /* The returned text includes up to four fragments of text extracted from
  123371. ** the data in the current row. The first iteration of the for(...) loop
  123372. ** below attempts to locate a single fragment of text nToken tokens in
  123373. ** size that contains at least one instance of all phrases in the query
  123374. ** expression that appear in the current row. If such a fragment of text
  123375. ** cannot be found, the second iteration of the loop attempts to locate
  123376. ** a pair of fragments, and so on.
  123377. */
  123378. int nSnippet = 0; /* Number of fragments in this snippet */
  123379. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  123380. int nFToken = -1; /* Number of tokens in each fragment */
  123381. if( !pCsr->pExpr ){
  123382. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  123383. return;
  123384. }
  123385. for(nSnippet=1; 1; nSnippet++){
  123386. int iSnip; /* Loop counter 0..nSnippet-1 */
  123387. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  123388. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  123389. if( nToken>=0 ){
  123390. nFToken = (nToken+nSnippet-1) / nSnippet;
  123391. }else{
  123392. nFToken = -1 * nToken;
  123393. }
  123394. for(iSnip=0; iSnip<nSnippet; iSnip++){
  123395. int iBestScore = -1; /* Best score of columns checked so far */
  123396. int iRead; /* Used to iterate through columns */
  123397. SnippetFragment *pFragment = &aSnippet[iSnip];
  123398. memset(pFragment, 0, sizeof(*pFragment));
  123399. /* Loop through all columns of the table being considered for snippets.
  123400. ** If the iCol argument to this function was negative, this means all
  123401. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  123402. */
  123403. for(iRead=0; iRead<pTab->nColumn; iRead++){
  123404. SnippetFragment sF = {0, 0, 0, 0};
  123405. int iS;
  123406. if( iCol>=0 && iRead!=iCol ) continue;
  123407. /* Find the best snippet of nFToken tokens in column iRead. */
  123408. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  123409. if( rc!=SQLITE_OK ){
  123410. goto snippet_out;
  123411. }
  123412. if( iS>iBestScore ){
  123413. *pFragment = sF;
  123414. iBestScore = iS;
  123415. }
  123416. }
  123417. mCovered |= pFragment->covered;
  123418. }
  123419. /* If all query phrases seen by fts3BestSnippet() are present in at least
  123420. ** one of the nSnippet snippet fragments, break out of the loop.
  123421. */
  123422. assert( (mCovered&mSeen)==mCovered );
  123423. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  123424. }
  123425. assert( nFToken>0 );
  123426. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  123427. rc = fts3SnippetText(pCsr, &aSnippet[i],
  123428. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  123429. );
  123430. }
  123431. snippet_out:
  123432. sqlite3Fts3SegmentsClose(pTab);
  123433. if( rc!=SQLITE_OK ){
  123434. sqlite3_result_error_code(pCtx, rc);
  123435. sqlite3_free(res.z);
  123436. }else{
  123437. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  123438. }
  123439. }
  123440. typedef struct TermOffset TermOffset;
  123441. typedef struct TermOffsetCtx TermOffsetCtx;
  123442. struct TermOffset {
  123443. char *pList; /* Position-list */
  123444. int iPos; /* Position just read from pList */
  123445. int iOff; /* Offset of this term from read positions */
  123446. };
  123447. struct TermOffsetCtx {
  123448. Fts3Cursor *pCsr;
  123449. int iCol; /* Column of table to populate aTerm for */
  123450. int iTerm;
  123451. sqlite3_int64 iDocid;
  123452. TermOffset *aTerm;
  123453. };
  123454. /*
  123455. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  123456. */
  123457. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  123458. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  123459. int nTerm; /* Number of tokens in phrase */
  123460. int iTerm; /* For looping through nTerm phrase terms */
  123461. char *pList; /* Pointer to position list for phrase */
  123462. int iPos = 0; /* First position in position-list */
  123463. int rc;
  123464. UNUSED_PARAMETER(iPhrase);
  123465. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  123466. nTerm = pExpr->pPhrase->nToken;
  123467. if( pList ){
  123468. fts3GetDeltaPosition(&pList, &iPos);
  123469. assert( iPos>=0 );
  123470. }
  123471. for(iTerm=0; iTerm<nTerm; iTerm++){
  123472. TermOffset *pT = &p->aTerm[p->iTerm++];
  123473. pT->iOff = nTerm-iTerm-1;
  123474. pT->pList = pList;
  123475. pT->iPos = iPos;
  123476. }
  123477. return rc;
  123478. }
  123479. /*
  123480. ** Implementation of offsets() function.
  123481. */
  123482. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  123483. sqlite3_context *pCtx, /* SQLite function call context */
  123484. Fts3Cursor *pCsr /* Cursor object */
  123485. ){
  123486. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  123487. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  123488. int rc; /* Return Code */
  123489. int nToken; /* Number of tokens in query */
  123490. int iCol; /* Column currently being processed */
  123491. StrBuffer res = {0, 0, 0}; /* Result string */
  123492. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  123493. if( !pCsr->pExpr ){
  123494. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  123495. return;
  123496. }
  123497. memset(&sCtx, 0, sizeof(sCtx));
  123498. assert( pCsr->isRequireSeek==0 );
  123499. /* Count the number of terms in the query */
  123500. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  123501. if( rc!=SQLITE_OK ) goto offsets_out;
  123502. /* Allocate the array of TermOffset iterators. */
  123503. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  123504. if( 0==sCtx.aTerm ){
  123505. rc = SQLITE_NOMEM;
  123506. goto offsets_out;
  123507. }
  123508. sCtx.iDocid = pCsr->iPrevId;
  123509. sCtx.pCsr = pCsr;
  123510. /* Loop through the table columns, appending offset information to
  123511. ** string-buffer res for each column.
  123512. */
  123513. for(iCol=0; iCol<pTab->nColumn; iCol++){
  123514. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  123515. const char *ZDUMMY; /* Dummy argument used with xNext() */
  123516. int NDUMMY = 0; /* Dummy argument used with xNext() */
  123517. int iStart = 0;
  123518. int iEnd = 0;
  123519. int iCurrent = 0;
  123520. const char *zDoc;
  123521. int nDoc;
  123522. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  123523. ** no way that this operation can fail, so the return code from
  123524. ** fts3ExprIterate() can be discarded.
  123525. */
  123526. sCtx.iCol = iCol;
  123527. sCtx.iTerm = 0;
  123528. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  123529. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  123530. ** in column iCol, jump immediately to the next iteration of the loop.
  123531. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  123532. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  123533. ** to the caller.
  123534. */
  123535. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  123536. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  123537. if( zDoc==0 ){
  123538. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  123539. continue;
  123540. }
  123541. rc = SQLITE_NOMEM;
  123542. goto offsets_out;
  123543. }
  123544. /* Initialize a tokenizer iterator to iterate through column iCol. */
  123545. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  123546. zDoc, nDoc, &pC
  123547. );
  123548. if( rc!=SQLITE_OK ) goto offsets_out;
  123549. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  123550. while( rc==SQLITE_OK ){
  123551. int i; /* Used to loop through terms */
  123552. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  123553. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  123554. for(i=0; i<nToken; i++){
  123555. TermOffset *pT = &sCtx.aTerm[i];
  123556. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  123557. iMinPos = pT->iPos-pT->iOff;
  123558. pTerm = pT;
  123559. }
  123560. }
  123561. if( !pTerm ){
  123562. /* All offsets for this column have been gathered. */
  123563. rc = SQLITE_DONE;
  123564. }else{
  123565. assert( iCurrent<=iMinPos );
  123566. if( 0==(0xFE&*pTerm->pList) ){
  123567. pTerm->pList = 0;
  123568. }else{
  123569. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  123570. }
  123571. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  123572. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  123573. }
  123574. if( rc==SQLITE_OK ){
  123575. char aBuffer[64];
  123576. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  123577. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  123578. );
  123579. rc = fts3StringAppend(&res, aBuffer, -1);
  123580. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  123581. rc = FTS_CORRUPT_VTAB;
  123582. }
  123583. }
  123584. }
  123585. if( rc==SQLITE_DONE ){
  123586. rc = SQLITE_OK;
  123587. }
  123588. pMod->xClose(pC);
  123589. if( rc!=SQLITE_OK ) goto offsets_out;
  123590. }
  123591. offsets_out:
  123592. sqlite3_free(sCtx.aTerm);
  123593. assert( rc!=SQLITE_DONE );
  123594. sqlite3Fts3SegmentsClose(pTab);
  123595. if( rc!=SQLITE_OK ){
  123596. sqlite3_result_error_code(pCtx, rc);
  123597. sqlite3_free(res.z);
  123598. }else{
  123599. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  123600. }
  123601. return;
  123602. }
  123603. /*
  123604. ** Implementation of matchinfo() function.
  123605. */
  123606. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  123607. sqlite3_context *pContext, /* Function call context */
  123608. Fts3Cursor *pCsr, /* FTS3 table cursor */
  123609. const char *zArg /* Second arg to matchinfo() function */
  123610. ){
  123611. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  123612. int rc;
  123613. int i;
  123614. const char *zFormat;
  123615. if( zArg ){
  123616. for(i=0; zArg[i]; i++){
  123617. char *zErr = 0;
  123618. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  123619. sqlite3_result_error(pContext, zErr, -1);
  123620. sqlite3_free(zErr);
  123621. return;
  123622. }
  123623. }
  123624. zFormat = zArg;
  123625. }else{
  123626. zFormat = FTS3_MATCHINFO_DEFAULT;
  123627. }
  123628. if( !pCsr->pExpr ){
  123629. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  123630. return;
  123631. }
  123632. /* Retrieve matchinfo() data. */
  123633. rc = fts3GetMatchinfo(pCsr, zFormat);
  123634. sqlite3Fts3SegmentsClose(pTab);
  123635. if( rc!=SQLITE_OK ){
  123636. sqlite3_result_error_code(pContext, rc);
  123637. }else{
  123638. int n = pCsr->nMatchinfo * sizeof(u32);
  123639. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  123640. }
  123641. }
  123642. #endif
  123643. /************** End of fts3_snippet.c ****************************************/
  123644. /************** Begin file fts3_unicode.c ************************************/
  123645. /*
  123646. ** 2012 May 24
  123647. **
  123648. ** The author disclaims copyright to this source code. In place of
  123649. ** a legal notice, here is a blessing:
  123650. **
  123651. ** May you do good and not evil.
  123652. ** May you find forgiveness for yourself and forgive others.
  123653. ** May you share freely, never taking more than you give.
  123654. **
  123655. ******************************************************************************
  123656. **
  123657. ** Implementation of the "unicode" full-text-search tokenizer.
  123658. */
  123659. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  123660. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  123661. /* #include <assert.h> */
  123662. /* #include <stdlib.h> */
  123663. /* #include <stdio.h> */
  123664. /* #include <string.h> */
  123665. /*
  123666. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  123667. ** from the sqlite3 source file utf.c. If this file is compiled as part
  123668. ** of the amalgamation, they are not required.
  123669. */
  123670. #ifndef SQLITE_AMALGAMATION
  123671. static const unsigned char sqlite3Utf8Trans1[] = {
  123672. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  123673. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  123674. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  123675. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  123676. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  123677. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  123678. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  123679. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  123680. };
  123681. #define READ_UTF8(zIn, zTerm, c) \
  123682. c = *(zIn++); \
  123683. if( c>=0xc0 ){ \
  123684. c = sqlite3Utf8Trans1[c-0xc0]; \
  123685. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  123686. c = (c<<6) + (0x3f & *(zIn++)); \
  123687. } \
  123688. if( c<0x80 \
  123689. || (c&0xFFFFF800)==0xD800 \
  123690. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  123691. }
  123692. #define WRITE_UTF8(zOut, c) { \
  123693. if( c<0x00080 ){ \
  123694. *zOut++ = (u8)(c&0xFF); \
  123695. } \
  123696. else if( c<0x00800 ){ \
  123697. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  123698. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  123699. } \
  123700. else if( c<0x10000 ){ \
  123701. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  123702. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  123703. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  123704. }else{ \
  123705. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  123706. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  123707. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  123708. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  123709. } \
  123710. }
  123711. #endif /* ifndef SQLITE_AMALGAMATION */
  123712. typedef struct unicode_tokenizer unicode_tokenizer;
  123713. typedef struct unicode_cursor unicode_cursor;
  123714. struct unicode_tokenizer {
  123715. sqlite3_tokenizer base;
  123716. int bRemoveDiacritic;
  123717. int nException;
  123718. int *aiException;
  123719. };
  123720. struct unicode_cursor {
  123721. sqlite3_tokenizer_cursor base;
  123722. const unsigned char *aInput; /* Input text being tokenized */
  123723. int nInput; /* Size of aInput[] in bytes */
  123724. int iOff; /* Current offset within aInput[] */
  123725. int iToken; /* Index of next token to be returned */
  123726. char *zToken; /* storage for current token */
  123727. int nAlloc; /* space allocated at zToken */
  123728. };
  123729. /*
  123730. ** Destroy a tokenizer allocated by unicodeCreate().
  123731. */
  123732. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  123733. if( pTokenizer ){
  123734. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  123735. sqlite3_free(p->aiException);
  123736. sqlite3_free(p);
  123737. }
  123738. return SQLITE_OK;
  123739. }
  123740. /*
  123741. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  123742. ** statement has specified that the tokenizer for this table shall consider
  123743. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  123744. ** token characters (if bAlnum==1).
  123745. **
  123746. ** For each codepoint in the zIn/nIn string, this function checks if the
  123747. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  123748. ** If so, no action is taken. Otherwise, the codepoint is added to the
  123749. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  123750. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  123751. ** codepoints in the aiException[] array.
  123752. **
  123753. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  123754. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  123755. ** It is not possible to change the behaviour of the tokenizer with respect
  123756. ** to these codepoints.
  123757. */
  123758. static int unicodeAddExceptions(
  123759. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  123760. int bAlnum, /* Replace Isalnum() return value with this */
  123761. const char *zIn, /* Array of characters to make exceptions */
  123762. int nIn /* Length of z in bytes */
  123763. ){
  123764. const unsigned char *z = (const unsigned char *)zIn;
  123765. const unsigned char *zTerm = &z[nIn];
  123766. int iCode;
  123767. int nEntry = 0;
  123768. assert( bAlnum==0 || bAlnum==1 );
  123769. while( z<zTerm ){
  123770. READ_UTF8(z, zTerm, iCode);
  123771. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  123772. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  123773. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  123774. ){
  123775. nEntry++;
  123776. }
  123777. }
  123778. if( nEntry ){
  123779. int *aNew; /* New aiException[] array */
  123780. int nNew; /* Number of valid entries in array aNew[] */
  123781. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  123782. if( aNew==0 ) return SQLITE_NOMEM;
  123783. nNew = p->nException;
  123784. z = (const unsigned char *)zIn;
  123785. while( z<zTerm ){
  123786. READ_UTF8(z, zTerm, iCode);
  123787. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  123788. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  123789. ){
  123790. int i, j;
  123791. for(i=0; i<nNew && aNew[i]<iCode; i++);
  123792. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  123793. aNew[i] = iCode;
  123794. nNew++;
  123795. }
  123796. }
  123797. p->aiException = aNew;
  123798. p->nException = nNew;
  123799. }
  123800. return SQLITE_OK;
  123801. }
  123802. /*
  123803. ** Return true if the p->aiException[] array contains the value iCode.
  123804. */
  123805. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  123806. if( p->nException>0 ){
  123807. int *a = p->aiException;
  123808. int iLo = 0;
  123809. int iHi = p->nException-1;
  123810. while( iHi>=iLo ){
  123811. int iTest = (iHi + iLo) / 2;
  123812. if( iCode==a[iTest] ){
  123813. return 1;
  123814. }else if( iCode>a[iTest] ){
  123815. iLo = iTest+1;
  123816. }else{
  123817. iHi = iTest-1;
  123818. }
  123819. }
  123820. }
  123821. return 0;
  123822. }
  123823. /*
  123824. ** Return true if, for the purposes of tokenization, codepoint iCode is
  123825. ** considered a token character (not a separator).
  123826. */
  123827. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  123828. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  123829. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  123830. }
  123831. /*
  123832. ** Create a new tokenizer instance.
  123833. */
  123834. static int unicodeCreate(
  123835. int nArg, /* Size of array argv[] */
  123836. const char * const *azArg, /* Tokenizer creation arguments */
  123837. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  123838. ){
  123839. unicode_tokenizer *pNew; /* New tokenizer object */
  123840. int i;
  123841. int rc = SQLITE_OK;
  123842. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  123843. if( pNew==NULL ) return SQLITE_NOMEM;
  123844. memset(pNew, 0, sizeof(unicode_tokenizer));
  123845. pNew->bRemoveDiacritic = 1;
  123846. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  123847. const char *z = azArg[i];
  123848. int n = strlen(z);
  123849. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  123850. pNew->bRemoveDiacritic = 1;
  123851. }
  123852. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  123853. pNew->bRemoveDiacritic = 0;
  123854. }
  123855. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  123856. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  123857. }
  123858. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  123859. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  123860. }
  123861. else{
  123862. /* Unrecognized argument */
  123863. rc = SQLITE_ERROR;
  123864. }
  123865. }
  123866. if( rc!=SQLITE_OK ){
  123867. unicodeDestroy((sqlite3_tokenizer *)pNew);
  123868. pNew = 0;
  123869. }
  123870. *pp = (sqlite3_tokenizer *)pNew;
  123871. return rc;
  123872. }
  123873. /*
  123874. ** Prepare to begin tokenizing a particular string. The input
  123875. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  123876. ** used to incrementally tokenize this string is returned in
  123877. ** *ppCursor.
  123878. */
  123879. static int unicodeOpen(
  123880. sqlite3_tokenizer *p, /* The tokenizer */
  123881. const char *aInput, /* Input string */
  123882. int nInput, /* Size of string aInput in bytes */
  123883. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  123884. ){
  123885. unicode_cursor *pCsr;
  123886. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  123887. if( pCsr==0 ){
  123888. return SQLITE_NOMEM;
  123889. }
  123890. memset(pCsr, 0, sizeof(unicode_cursor));
  123891. pCsr->aInput = (const unsigned char *)aInput;
  123892. if( aInput==0 ){
  123893. pCsr->nInput = 0;
  123894. }else if( nInput<0 ){
  123895. pCsr->nInput = (int)strlen(aInput);
  123896. }else{
  123897. pCsr->nInput = nInput;
  123898. }
  123899. *pp = &pCsr->base;
  123900. UNUSED_PARAMETER(p);
  123901. return SQLITE_OK;
  123902. }
  123903. /*
  123904. ** Close a tokenization cursor previously opened by a call to
  123905. ** simpleOpen() above.
  123906. */
  123907. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  123908. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  123909. sqlite3_free(pCsr->zToken);
  123910. sqlite3_free(pCsr);
  123911. return SQLITE_OK;
  123912. }
  123913. /*
  123914. ** Extract the next token from a tokenization cursor. The cursor must
  123915. ** have been opened by a prior call to simpleOpen().
  123916. */
  123917. static int unicodeNext(
  123918. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  123919. const char **paToken, /* OUT: Token text */
  123920. int *pnToken, /* OUT: Number of bytes at *paToken */
  123921. int *piStart, /* OUT: Starting offset of token */
  123922. int *piEnd, /* OUT: Ending offset of token */
  123923. int *piPos /* OUT: Position integer of token */
  123924. ){
  123925. unicode_cursor *pCsr = (unicode_cursor *)pC;
  123926. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  123927. int iCode;
  123928. char *zOut;
  123929. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  123930. const unsigned char *zStart = z;
  123931. const unsigned char *zEnd;
  123932. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  123933. /* Scan past any delimiter characters before the start of the next token.
  123934. ** Return SQLITE_DONE early if this takes us all the way to the end of
  123935. ** the input. */
  123936. while( z<zTerm ){
  123937. READ_UTF8(z, zTerm, iCode);
  123938. if( unicodeIsAlnum(p, iCode) ) break;
  123939. zStart = z;
  123940. }
  123941. if( zStart>=zTerm ) return SQLITE_DONE;
  123942. zOut = pCsr->zToken;
  123943. do {
  123944. int iOut;
  123945. /* Grow the output buffer if required. */
  123946. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  123947. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  123948. if( !zNew ) return SQLITE_NOMEM;
  123949. zOut = &zNew[zOut - pCsr->zToken];
  123950. pCsr->zToken = zNew;
  123951. pCsr->nAlloc += 64;
  123952. }
  123953. /* Write the folded case of the last character read to the output */
  123954. zEnd = z;
  123955. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  123956. if( iOut ){
  123957. WRITE_UTF8(zOut, iOut);
  123958. }
  123959. /* If the cursor is not at EOF, read the next character */
  123960. if( z>=zTerm ) break;
  123961. READ_UTF8(z, zTerm, iCode);
  123962. }while( unicodeIsAlnum(p, iCode)
  123963. || sqlite3FtsUnicodeIsdiacritic(iCode)
  123964. );
  123965. /* Set the output variables and return. */
  123966. pCsr->iOff = (z - pCsr->aInput);
  123967. *paToken = pCsr->zToken;
  123968. *pnToken = zOut - pCsr->zToken;
  123969. *piStart = (zStart - pCsr->aInput);
  123970. *piEnd = (zEnd - pCsr->aInput);
  123971. *piPos = pCsr->iToken++;
  123972. return SQLITE_OK;
  123973. }
  123974. /*
  123975. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  123976. ** structure for the unicode tokenizer.
  123977. */
  123978. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  123979. static const sqlite3_tokenizer_module module = {
  123980. 0,
  123981. unicodeCreate,
  123982. unicodeDestroy,
  123983. unicodeOpen,
  123984. unicodeClose,
  123985. unicodeNext,
  123986. 0,
  123987. };
  123988. *ppModule = &module;
  123989. }
  123990. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  123991. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  123992. /************** End of fts3_unicode.c ****************************************/
  123993. /************** Begin file fts3_unicode2.c ***********************************/
  123994. /*
  123995. ** 2012 May 25
  123996. **
  123997. ** The author disclaims copyright to this source code. In place of
  123998. ** a legal notice, here is a blessing:
  123999. **
  124000. ** May you do good and not evil.
  124001. ** May you find forgiveness for yourself and forgive others.
  124002. ** May you share freely, never taking more than you give.
  124003. **
  124004. ******************************************************************************
  124005. */
  124006. /*
  124007. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  124008. */
  124009. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  124010. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  124011. /* #include <assert.h> */
  124012. /*
  124013. ** Return true if the argument corresponds to a unicode codepoint
  124014. ** classified as either a letter or a number. Otherwise false.
  124015. **
  124016. ** The results are undefined if the value passed to this function
  124017. ** is less than zero.
  124018. */
  124019. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  124020. /* Each unsigned integer in the following array corresponds to a contiguous
  124021. ** range of unicode codepoints that are not either letters or numbers (i.e.
  124022. ** codepoints for which this function should return 0).
  124023. **
  124024. ** The most significant 22 bits in each 32-bit value contain the first
  124025. ** codepoint in the range. The least significant 10 bits are used to store
  124026. ** the size of the range (always at least 1). In other words, the value
  124027. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  124028. ** C. It is not possible to represent a range larger than 1023 codepoints
  124029. ** using this format.
  124030. */
  124031. const static unsigned int aEntry[] = {
  124032. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  124033. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  124034. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  124035. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  124036. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  124037. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  124038. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  124039. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  124040. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  124041. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  124042. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  124043. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  124044. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  124045. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  124046. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  124047. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  124048. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  124049. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  124050. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  124051. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  124052. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  124053. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  124054. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  124055. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  124056. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  124057. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  124058. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  124059. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  124060. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  124061. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  124062. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  124063. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  124064. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  124065. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  124066. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  124067. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  124068. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  124069. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  124070. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  124071. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  124072. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  124073. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  124074. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  124075. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  124076. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  124077. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  124078. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  124079. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  124080. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  124081. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  124082. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  124083. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  124084. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  124085. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  124086. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  124087. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  124088. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  124089. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  124090. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  124091. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  124092. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  124093. 0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
  124094. 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
  124095. 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
  124096. 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
  124097. 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
  124098. 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
  124099. 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
  124100. 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
  124101. 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
  124102. 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
  124103. 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
  124104. 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
  124105. 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
  124106. 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
  124107. 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
  124108. 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
  124109. 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
  124110. 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
  124111. 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
  124112. 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
  124113. 0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
  124114. 0x43FFF401,
  124115. };
  124116. static const unsigned int aAscii[4] = {
  124117. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  124118. };
  124119. if( c<128 ){
  124120. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  124121. }else if( c<(1<<22) ){
  124122. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  124123. int iRes;
  124124. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  124125. int iLo = 0;
  124126. while( iHi>=iLo ){
  124127. int iTest = (iHi + iLo) / 2;
  124128. if( key >= aEntry[iTest] ){
  124129. iRes = iTest;
  124130. iLo = iTest+1;
  124131. }else{
  124132. iHi = iTest-1;
  124133. }
  124134. }
  124135. assert( aEntry[0]<key );
  124136. assert( key>=aEntry[iRes] );
  124137. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  124138. }
  124139. return 1;
  124140. }
  124141. /*
  124142. ** If the argument is a codepoint corresponding to a lowercase letter
  124143. ** in the ASCII range with a diacritic added, return the codepoint
  124144. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  124145. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  124146. ** E"). The resuls of passing a codepoint that corresponds to an
  124147. ** uppercase letter are undefined.
  124148. */
  124149. static int remove_diacritic(int c){
  124150. unsigned short aDia[] = {
  124151. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  124152. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  124153. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  124154. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  124155. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  124156. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  124157. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  124158. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  124159. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  124160. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  124161. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  124162. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  124163. 62924, 63050, 63082, 63274, 63390,
  124164. };
  124165. char aChar[] = {
  124166. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  124167. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  124168. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  124169. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  124170. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  124171. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  124172. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  124173. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  124174. 'e', 'i', 'o', 'u', 'y',
  124175. };
  124176. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  124177. int iRes = 0;
  124178. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  124179. int iLo = 0;
  124180. while( iHi>=iLo ){
  124181. int iTest = (iHi + iLo) / 2;
  124182. if( key >= aDia[iTest] ){
  124183. iRes = iTest;
  124184. iLo = iTest+1;
  124185. }else{
  124186. iHi = iTest-1;
  124187. }
  124188. }
  124189. assert( key>=aDia[iRes] );
  124190. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  124191. };
  124192. /*
  124193. ** Return true if the argument interpreted as a unicode codepoint
  124194. ** is a diacritical modifier character.
  124195. */
  124196. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  124197. unsigned int mask0 = 0x08029FDF;
  124198. unsigned int mask1 = 0x000361F8;
  124199. if( c<768 || c>817 ) return 0;
  124200. return (c < 768+32) ?
  124201. (mask0 & (1 << (c-768))) :
  124202. (mask1 & (1 << (c-768-32)));
  124203. }
  124204. /*
  124205. ** Interpret the argument as a unicode codepoint. If the codepoint
  124206. ** is an upper case character that has a lower case equivalent,
  124207. ** return the codepoint corresponding to the lower case version.
  124208. ** Otherwise, return a copy of the argument.
  124209. **
  124210. ** The results are undefined if the value passed to this function
  124211. ** is less than zero.
  124212. */
  124213. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  124214. /* Each entry in the following array defines a rule for folding a range
  124215. ** of codepoints to lower case. The rule applies to a range of nRange
  124216. ** codepoints starting at codepoint iCode.
  124217. **
  124218. ** If the least significant bit in flags is clear, then the rule applies
  124219. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  124220. ** need to be folded). Or, if it is set, then the rule only applies to
  124221. ** every second codepoint in the range, starting with codepoint C.
  124222. **
  124223. ** The 7 most significant bits in flags are an index into the aiOff[]
  124224. ** array. If a specific codepoint C does require folding, then its lower
  124225. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  124226. **
  124227. ** The contents of this array are generated by parsing the CaseFolding.txt
  124228. ** file distributed as part of the "Unicode Character Database". See
  124229. ** http://www.unicode.org for details.
  124230. */
  124231. static const struct TableEntry {
  124232. unsigned short iCode;
  124233. unsigned char flags;
  124234. unsigned char nRange;
  124235. } aEntry[] = {
  124236. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  124237. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  124238. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  124239. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  124240. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  124241. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  124242. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  124243. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  124244. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  124245. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  124246. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  124247. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  124248. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  124249. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  124250. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  124251. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  124252. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  124253. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  124254. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  124255. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  124256. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  124257. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  124258. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  124259. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  124260. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  124261. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  124262. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  124263. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  124264. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  124265. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  124266. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  124267. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  124268. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  124269. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  124270. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  124271. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  124272. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  124273. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  124274. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  124275. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  124276. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  124277. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  124278. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  124279. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  124280. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  124281. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  124282. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  124283. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  124284. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  124285. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  124286. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  124287. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  124288. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  124289. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  124290. {65313, 14, 26},
  124291. };
  124292. static const unsigned short aiOff[] = {
  124293. 1, 2, 8, 15, 16, 26, 28, 32,
  124294. 37, 38, 40, 48, 63, 64, 69, 71,
  124295. 79, 80, 116, 202, 203, 205, 206, 207,
  124296. 209, 210, 211, 213, 214, 217, 218, 219,
  124297. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  124298. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  124299. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  124300. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  124301. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  124302. 65514, 65521, 65527, 65528, 65529,
  124303. };
  124304. int ret = c;
  124305. assert( c>=0 );
  124306. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  124307. if( c<128 ){
  124308. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  124309. }else if( c<65536 ){
  124310. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  124311. int iLo = 0;
  124312. int iRes = -1;
  124313. while( iHi>=iLo ){
  124314. int iTest = (iHi + iLo) / 2;
  124315. int cmp = (c - aEntry[iTest].iCode);
  124316. if( cmp>=0 ){
  124317. iRes = iTest;
  124318. iLo = iTest+1;
  124319. }else{
  124320. iHi = iTest-1;
  124321. }
  124322. }
  124323. assert( iRes<0 || c>=aEntry[iRes].iCode );
  124324. if( iRes>=0 ){
  124325. const struct TableEntry *p = &aEntry[iRes];
  124326. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  124327. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  124328. assert( ret>0 );
  124329. }
  124330. }
  124331. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  124332. }
  124333. else if( c>=66560 && c<66600 ){
  124334. ret = c + 40;
  124335. }
  124336. return ret;
  124337. }
  124338. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  124339. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  124340. /************** End of fts3_unicode2.c ***************************************/
  124341. /************** Begin file rtree.c *******************************************/
  124342. /*
  124343. ** 2001 September 15
  124344. **
  124345. ** The author disclaims copyright to this source code. In place of
  124346. ** a legal notice, here is a blessing:
  124347. **
  124348. ** May you do good and not evil.
  124349. ** May you find forgiveness for yourself and forgive others.
  124350. ** May you share freely, never taking more than you give.
  124351. **
  124352. *************************************************************************
  124353. ** This file contains code for implementations of the r-tree and r*-tree
  124354. ** algorithms packaged as an SQLite virtual table module.
  124355. */
  124356. /*
  124357. ** Database Format of R-Tree Tables
  124358. ** --------------------------------
  124359. **
  124360. ** The data structure for a single virtual r-tree table is stored in three
  124361. ** native SQLite tables declared as follows. In each case, the '%' character
  124362. ** in the table name is replaced with the user-supplied name of the r-tree
  124363. ** table.
  124364. **
  124365. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  124366. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  124367. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  124368. **
  124369. ** The data for each node of the r-tree structure is stored in the %_node
  124370. ** table. For each node that is not the root node of the r-tree, there is
  124371. ** an entry in the %_parent table associating the node with its parent.
  124372. ** And for each row of data in the table, there is an entry in the %_rowid
  124373. ** table that maps from the entries rowid to the id of the node that it
  124374. ** is stored on.
  124375. **
  124376. ** The root node of an r-tree always exists, even if the r-tree table is
  124377. ** empty. The nodeno of the root node is always 1. All other nodes in the
  124378. ** table must be the same size as the root node. The content of each node
  124379. ** is formatted as follows:
  124380. **
  124381. ** 1. If the node is the root node (node 1), then the first 2 bytes
  124382. ** of the node contain the tree depth as a big-endian integer.
  124383. ** For non-root nodes, the first 2 bytes are left unused.
  124384. **
  124385. ** 2. The next 2 bytes contain the number of entries currently
  124386. ** stored in the node.
  124387. **
  124388. ** 3. The remainder of the node contains the node entries. Each entry
  124389. ** consists of a single 8-byte integer followed by an even number
  124390. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  124391. ** of a record. For internal nodes it is the node number of a
  124392. ** child page.
  124393. */
  124394. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  124395. /*
  124396. ** This file contains an implementation of a couple of different variants
  124397. ** of the r-tree algorithm. See the README file for further details. The
  124398. ** same data-structure is used for all, but the algorithms for insert and
  124399. ** delete operations vary. The variants used are selected at compile time
  124400. ** by defining the following symbols:
  124401. */
  124402. /* Either, both or none of the following may be set to activate
  124403. ** r*tree variant algorithms.
  124404. */
  124405. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  124406. #define VARIANT_RSTARTREE_REINSERT 1
  124407. /*
  124408. ** Exactly one of the following must be set to 1.
  124409. */
  124410. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  124411. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  124412. #define VARIANT_RSTARTREE_SPLIT 1
  124413. #define VARIANT_GUTTMAN_SPLIT \
  124414. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  124415. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  124416. #define PickNext QuadraticPickNext
  124417. #define PickSeeds QuadraticPickSeeds
  124418. #define AssignCells splitNodeGuttman
  124419. #endif
  124420. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  124421. #define PickNext LinearPickNext
  124422. #define PickSeeds LinearPickSeeds
  124423. #define AssignCells splitNodeGuttman
  124424. #endif
  124425. #if VARIANT_RSTARTREE_SPLIT
  124426. #define AssignCells splitNodeStartree
  124427. #endif
  124428. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  124429. # define NDEBUG 1
  124430. #endif
  124431. #ifndef SQLITE_CORE
  124432. SQLITE_EXTENSION_INIT1
  124433. #else
  124434. #endif
  124435. /* #include <string.h> */
  124436. /* #include <assert.h> */
  124437. #ifndef SQLITE_AMALGAMATION
  124438. #include "sqlite3rtree.h"
  124439. typedef sqlite3_int64 i64;
  124440. typedef unsigned char u8;
  124441. typedef unsigned int u32;
  124442. #endif
  124443. /* The following macro is used to suppress compiler warnings.
  124444. */
  124445. #ifndef UNUSED_PARAMETER
  124446. # define UNUSED_PARAMETER(x) (void)(x)
  124447. #endif
  124448. typedef struct Rtree Rtree;
  124449. typedef struct RtreeCursor RtreeCursor;
  124450. typedef struct RtreeNode RtreeNode;
  124451. typedef struct RtreeCell RtreeCell;
  124452. typedef struct RtreeConstraint RtreeConstraint;
  124453. typedef struct RtreeMatchArg RtreeMatchArg;
  124454. typedef struct RtreeGeomCallback RtreeGeomCallback;
  124455. typedef union RtreeCoord RtreeCoord;
  124456. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  124457. #define RTREE_MAX_DIMENSIONS 5
  124458. /* Size of hash table Rtree.aHash. This hash table is not expected to
  124459. ** ever contain very many entries, so a fixed number of buckets is
  124460. ** used.
  124461. */
  124462. #define HASHSIZE 128
  124463. /*
  124464. ** An rtree virtual-table object.
  124465. */
  124466. struct Rtree {
  124467. sqlite3_vtab base;
  124468. sqlite3 *db; /* Host database connection */
  124469. int iNodeSize; /* Size in bytes of each node in the node table */
  124470. int nDim; /* Number of dimensions */
  124471. int nBytesPerCell; /* Bytes consumed per cell */
  124472. int iDepth; /* Current depth of the r-tree structure */
  124473. char *zDb; /* Name of database containing r-tree table */
  124474. char *zName; /* Name of r-tree table */
  124475. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  124476. int nBusy; /* Current number of users of this structure */
  124477. /* List of nodes removed during a CondenseTree operation. List is
  124478. ** linked together via the pointer normally used for hash chains -
  124479. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  124480. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  124481. */
  124482. RtreeNode *pDeleted;
  124483. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  124484. /* Statements to read/write/delete a record from xxx_node */
  124485. sqlite3_stmt *pReadNode;
  124486. sqlite3_stmt *pWriteNode;
  124487. sqlite3_stmt *pDeleteNode;
  124488. /* Statements to read/write/delete a record from xxx_rowid */
  124489. sqlite3_stmt *pReadRowid;
  124490. sqlite3_stmt *pWriteRowid;
  124491. sqlite3_stmt *pDeleteRowid;
  124492. /* Statements to read/write/delete a record from xxx_parent */
  124493. sqlite3_stmt *pReadParent;
  124494. sqlite3_stmt *pWriteParent;
  124495. sqlite3_stmt *pDeleteParent;
  124496. int eCoordType;
  124497. };
  124498. /* Possible values for eCoordType: */
  124499. #define RTREE_COORD_REAL32 0
  124500. #define RTREE_COORD_INT32 1
  124501. /*
  124502. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  124503. ** only deal with integer coordinates. No floating point operations
  124504. ** will be done.
  124505. */
  124506. #ifdef SQLITE_RTREE_INT_ONLY
  124507. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  124508. typedef int RtreeValue; /* Low accuracy coordinate */
  124509. #else
  124510. typedef double RtreeDValue; /* High accuracy coordinate */
  124511. typedef float RtreeValue; /* Low accuracy coordinate */
  124512. #endif
  124513. /*
  124514. ** The minimum number of cells allowed for a node is a third of the
  124515. ** maximum. In Gutman's notation:
  124516. **
  124517. ** m = M/3
  124518. **
  124519. ** If an R*-tree "Reinsert" operation is required, the same number of
  124520. ** cells are removed from the overfull node and reinserted into the tree.
  124521. */
  124522. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  124523. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  124524. #define RTREE_MAXCELLS 51
  124525. /*
  124526. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  124527. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  124528. ** Therefore all non-root nodes must contain at least 3 entries. Since
  124529. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  124530. ** 40 or less.
  124531. */
  124532. #define RTREE_MAX_DEPTH 40
  124533. /*
  124534. ** An rtree cursor object.
  124535. */
  124536. struct RtreeCursor {
  124537. sqlite3_vtab_cursor base;
  124538. RtreeNode *pNode; /* Node cursor is currently pointing at */
  124539. int iCell; /* Index of current cell in pNode */
  124540. int iStrategy; /* Copy of idxNum search parameter */
  124541. int nConstraint; /* Number of entries in aConstraint */
  124542. RtreeConstraint *aConstraint; /* Search constraints. */
  124543. };
  124544. union RtreeCoord {
  124545. RtreeValue f;
  124546. int i;
  124547. };
  124548. /*
  124549. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  124550. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  124551. ** variable pRtree points to the Rtree structure associated with the
  124552. ** RtreeCoord.
  124553. */
  124554. #ifdef SQLITE_RTREE_INT_ONLY
  124555. # define DCOORD(coord) ((RtreeDValue)coord.i)
  124556. #else
  124557. # define DCOORD(coord) ( \
  124558. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  124559. ((double)coord.f) : \
  124560. ((double)coord.i) \
  124561. )
  124562. #endif
  124563. /*
  124564. ** A search constraint.
  124565. */
  124566. struct RtreeConstraint {
  124567. int iCoord; /* Index of constrained coordinate */
  124568. int op; /* Constraining operation */
  124569. RtreeDValue rValue; /* Constraint value. */
  124570. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  124571. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  124572. };
  124573. /* Possible values for RtreeConstraint.op */
  124574. #define RTREE_EQ 0x41
  124575. #define RTREE_LE 0x42
  124576. #define RTREE_LT 0x43
  124577. #define RTREE_GE 0x44
  124578. #define RTREE_GT 0x45
  124579. #define RTREE_MATCH 0x46
  124580. /*
  124581. ** An rtree structure node.
  124582. */
  124583. struct RtreeNode {
  124584. RtreeNode *pParent; /* Parent node */
  124585. i64 iNode;
  124586. int nRef;
  124587. int isDirty;
  124588. u8 *zData;
  124589. RtreeNode *pNext; /* Next node in this hash chain */
  124590. };
  124591. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  124592. /*
  124593. ** Structure to store a deserialized rtree record.
  124594. */
  124595. struct RtreeCell {
  124596. i64 iRowid;
  124597. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  124598. };
  124599. /*
  124600. ** Value for the first field of every RtreeMatchArg object. The MATCH
  124601. ** operator tests that the first field of a blob operand matches this
  124602. ** value to avoid operating on invalid blobs (which could cause a segfault).
  124603. */
  124604. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  124605. /*
  124606. ** An instance of this structure must be supplied as a blob argument to
  124607. ** the right-hand-side of an SQL MATCH operator used to constrain an
  124608. ** r-tree query.
  124609. */
  124610. struct RtreeMatchArg {
  124611. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  124612. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  124613. void *pContext;
  124614. int nParam;
  124615. RtreeDValue aParam[1];
  124616. };
  124617. /*
  124618. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  124619. ** a single instance of the following structure is allocated. It is used
  124620. ** as the context for the user-function created by by s_r_g_c(). The object
  124621. ** is eventually deleted by the destructor mechanism provided by
  124622. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  124623. ** the geometry callback function).
  124624. */
  124625. struct RtreeGeomCallback {
  124626. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  124627. void *pContext;
  124628. };
  124629. #ifndef MAX
  124630. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  124631. #endif
  124632. #ifndef MIN
  124633. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  124634. #endif
  124635. /*
  124636. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  124637. ** 64 bit integer. The deserialized value is returned.
  124638. */
  124639. static int readInt16(u8 *p){
  124640. return (p[0]<<8) + p[1];
  124641. }
  124642. static void readCoord(u8 *p, RtreeCoord *pCoord){
  124643. u32 i = (
  124644. (((u32)p[0]) << 24) +
  124645. (((u32)p[1]) << 16) +
  124646. (((u32)p[2]) << 8) +
  124647. (((u32)p[3]) << 0)
  124648. );
  124649. *(u32 *)pCoord = i;
  124650. }
  124651. static i64 readInt64(u8 *p){
  124652. return (
  124653. (((i64)p[0]) << 56) +
  124654. (((i64)p[1]) << 48) +
  124655. (((i64)p[2]) << 40) +
  124656. (((i64)p[3]) << 32) +
  124657. (((i64)p[4]) << 24) +
  124658. (((i64)p[5]) << 16) +
  124659. (((i64)p[6]) << 8) +
  124660. (((i64)p[7]) << 0)
  124661. );
  124662. }
  124663. /*
  124664. ** Functions to serialize a 16 bit integer, 32 bit real number and
  124665. ** 64 bit integer. The value returned is the number of bytes written
  124666. ** to the argument buffer (always 2, 4 and 8 respectively).
  124667. */
  124668. static int writeInt16(u8 *p, int i){
  124669. p[0] = (i>> 8)&0xFF;
  124670. p[1] = (i>> 0)&0xFF;
  124671. return 2;
  124672. }
  124673. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  124674. u32 i;
  124675. assert( sizeof(RtreeCoord)==4 );
  124676. assert( sizeof(u32)==4 );
  124677. i = *(u32 *)pCoord;
  124678. p[0] = (i>>24)&0xFF;
  124679. p[1] = (i>>16)&0xFF;
  124680. p[2] = (i>> 8)&0xFF;
  124681. p[3] = (i>> 0)&0xFF;
  124682. return 4;
  124683. }
  124684. static int writeInt64(u8 *p, i64 i){
  124685. p[0] = (i>>56)&0xFF;
  124686. p[1] = (i>>48)&0xFF;
  124687. p[2] = (i>>40)&0xFF;
  124688. p[3] = (i>>32)&0xFF;
  124689. p[4] = (i>>24)&0xFF;
  124690. p[5] = (i>>16)&0xFF;
  124691. p[6] = (i>> 8)&0xFF;
  124692. p[7] = (i>> 0)&0xFF;
  124693. return 8;
  124694. }
  124695. /*
  124696. ** Increment the reference count of node p.
  124697. */
  124698. static void nodeReference(RtreeNode *p){
  124699. if( p ){
  124700. p->nRef++;
  124701. }
  124702. }
  124703. /*
  124704. ** Clear the content of node p (set all bytes to 0x00).
  124705. */
  124706. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  124707. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  124708. p->isDirty = 1;
  124709. }
  124710. /*
  124711. ** Given a node number iNode, return the corresponding key to use
  124712. ** in the Rtree.aHash table.
  124713. */
  124714. static int nodeHash(i64 iNode){
  124715. return (
  124716. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  124717. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  124718. ) % HASHSIZE;
  124719. }
  124720. /*
  124721. ** Search the node hash table for node iNode. If found, return a pointer
  124722. ** to it. Otherwise, return 0.
  124723. */
  124724. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  124725. RtreeNode *p;
  124726. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  124727. return p;
  124728. }
  124729. /*
  124730. ** Add node pNode to the node hash table.
  124731. */
  124732. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  124733. int iHash;
  124734. assert( pNode->pNext==0 );
  124735. iHash = nodeHash(pNode->iNode);
  124736. pNode->pNext = pRtree->aHash[iHash];
  124737. pRtree->aHash[iHash] = pNode;
  124738. }
  124739. /*
  124740. ** Remove node pNode from the node hash table.
  124741. */
  124742. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  124743. RtreeNode **pp;
  124744. if( pNode->iNode!=0 ){
  124745. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  124746. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  124747. *pp = pNode->pNext;
  124748. pNode->pNext = 0;
  124749. }
  124750. }
  124751. /*
  124752. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  124753. ** indicating that node has not yet been assigned a node number. It is
  124754. ** assigned a node number when nodeWrite() is called to write the
  124755. ** node contents out to the database.
  124756. */
  124757. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  124758. RtreeNode *pNode;
  124759. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  124760. if( pNode ){
  124761. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  124762. pNode->zData = (u8 *)&pNode[1];
  124763. pNode->nRef = 1;
  124764. pNode->pParent = pParent;
  124765. pNode->isDirty = 1;
  124766. nodeReference(pParent);
  124767. }
  124768. return pNode;
  124769. }
  124770. /*
  124771. ** Obtain a reference to an r-tree node.
  124772. */
  124773. static int
  124774. nodeAcquire(
  124775. Rtree *pRtree, /* R-tree structure */
  124776. i64 iNode, /* Node number to load */
  124777. RtreeNode *pParent, /* Either the parent node or NULL */
  124778. RtreeNode **ppNode /* OUT: Acquired node */
  124779. ){
  124780. int rc;
  124781. int rc2 = SQLITE_OK;
  124782. RtreeNode *pNode;
  124783. /* Check if the requested node is already in the hash table. If so,
  124784. ** increase its reference count and return it.
  124785. */
  124786. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  124787. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  124788. if( pParent && !pNode->pParent ){
  124789. nodeReference(pParent);
  124790. pNode->pParent = pParent;
  124791. }
  124792. pNode->nRef++;
  124793. *ppNode = pNode;
  124794. return SQLITE_OK;
  124795. }
  124796. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  124797. rc = sqlite3_step(pRtree->pReadNode);
  124798. if( rc==SQLITE_ROW ){
  124799. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  124800. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  124801. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  124802. if( !pNode ){
  124803. rc2 = SQLITE_NOMEM;
  124804. }else{
  124805. pNode->pParent = pParent;
  124806. pNode->zData = (u8 *)&pNode[1];
  124807. pNode->nRef = 1;
  124808. pNode->iNode = iNode;
  124809. pNode->isDirty = 0;
  124810. pNode->pNext = 0;
  124811. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  124812. nodeReference(pParent);
  124813. }
  124814. }
  124815. }
  124816. rc = sqlite3_reset(pRtree->pReadNode);
  124817. if( rc==SQLITE_OK ) rc = rc2;
  124818. /* If the root node was just loaded, set pRtree->iDepth to the height
  124819. ** of the r-tree structure. A height of zero means all data is stored on
  124820. ** the root node. A height of one means the children of the root node
  124821. ** are the leaves, and so on. If the depth as specified on the root node
  124822. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  124823. */
  124824. if( pNode && iNode==1 ){
  124825. pRtree->iDepth = readInt16(pNode->zData);
  124826. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  124827. rc = SQLITE_CORRUPT_VTAB;
  124828. }
  124829. }
  124830. /* If no error has occurred so far, check if the "number of entries"
  124831. ** field on the node is too large. If so, set the return code to
  124832. ** SQLITE_CORRUPT_VTAB.
  124833. */
  124834. if( pNode && rc==SQLITE_OK ){
  124835. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  124836. rc = SQLITE_CORRUPT_VTAB;
  124837. }
  124838. }
  124839. if( rc==SQLITE_OK ){
  124840. if( pNode!=0 ){
  124841. nodeHashInsert(pRtree, pNode);
  124842. }else{
  124843. rc = SQLITE_CORRUPT_VTAB;
  124844. }
  124845. *ppNode = pNode;
  124846. }else{
  124847. sqlite3_free(pNode);
  124848. *ppNode = 0;
  124849. }
  124850. return rc;
  124851. }
  124852. /*
  124853. ** Overwrite cell iCell of node pNode with the contents of pCell.
  124854. */
  124855. static void nodeOverwriteCell(
  124856. Rtree *pRtree,
  124857. RtreeNode *pNode,
  124858. RtreeCell *pCell,
  124859. int iCell
  124860. ){
  124861. int ii;
  124862. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  124863. p += writeInt64(p, pCell->iRowid);
  124864. for(ii=0; ii<(pRtree->nDim*2); ii++){
  124865. p += writeCoord(p, &pCell->aCoord[ii]);
  124866. }
  124867. pNode->isDirty = 1;
  124868. }
  124869. /*
  124870. ** Remove cell the cell with index iCell from node pNode.
  124871. */
  124872. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  124873. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  124874. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  124875. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  124876. memmove(pDst, pSrc, nByte);
  124877. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  124878. pNode->isDirty = 1;
  124879. }
  124880. /*
  124881. ** Insert the contents of cell pCell into node pNode. If the insert
  124882. ** is successful, return SQLITE_OK.
  124883. **
  124884. ** If there is not enough free space in pNode, return SQLITE_FULL.
  124885. */
  124886. static int
  124887. nodeInsertCell(
  124888. Rtree *pRtree,
  124889. RtreeNode *pNode,
  124890. RtreeCell *pCell
  124891. ){
  124892. int nCell; /* Current number of cells in pNode */
  124893. int nMaxCell; /* Maximum number of cells for pNode */
  124894. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  124895. nCell = NCELL(pNode);
  124896. assert( nCell<=nMaxCell );
  124897. if( nCell<nMaxCell ){
  124898. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  124899. writeInt16(&pNode->zData[2], nCell+1);
  124900. pNode->isDirty = 1;
  124901. }
  124902. return (nCell==nMaxCell);
  124903. }
  124904. /*
  124905. ** If the node is dirty, write it out to the database.
  124906. */
  124907. static int
  124908. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  124909. int rc = SQLITE_OK;
  124910. if( pNode->isDirty ){
  124911. sqlite3_stmt *p = pRtree->pWriteNode;
  124912. if( pNode->iNode ){
  124913. sqlite3_bind_int64(p, 1, pNode->iNode);
  124914. }else{
  124915. sqlite3_bind_null(p, 1);
  124916. }
  124917. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  124918. sqlite3_step(p);
  124919. pNode->isDirty = 0;
  124920. rc = sqlite3_reset(p);
  124921. if( pNode->iNode==0 && rc==SQLITE_OK ){
  124922. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  124923. nodeHashInsert(pRtree, pNode);
  124924. }
  124925. }
  124926. return rc;
  124927. }
  124928. /*
  124929. ** Release a reference to a node. If the node is dirty and the reference
  124930. ** count drops to zero, the node data is written to the database.
  124931. */
  124932. static int
  124933. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  124934. int rc = SQLITE_OK;
  124935. if( pNode ){
  124936. assert( pNode->nRef>0 );
  124937. pNode->nRef--;
  124938. if( pNode->nRef==0 ){
  124939. if( pNode->iNode==1 ){
  124940. pRtree->iDepth = -1;
  124941. }
  124942. if( pNode->pParent ){
  124943. rc = nodeRelease(pRtree, pNode->pParent);
  124944. }
  124945. if( rc==SQLITE_OK ){
  124946. rc = nodeWrite(pRtree, pNode);
  124947. }
  124948. nodeHashDelete(pRtree, pNode);
  124949. sqlite3_free(pNode);
  124950. }
  124951. }
  124952. return rc;
  124953. }
  124954. /*
  124955. ** Return the 64-bit integer value associated with cell iCell of
  124956. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  124957. ** an internal node, then the 64-bit integer is a child page number.
  124958. */
  124959. static i64 nodeGetRowid(
  124960. Rtree *pRtree,
  124961. RtreeNode *pNode,
  124962. int iCell
  124963. ){
  124964. assert( iCell<NCELL(pNode) );
  124965. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  124966. }
  124967. /*
  124968. ** Return coordinate iCoord from cell iCell in node pNode.
  124969. */
  124970. static void nodeGetCoord(
  124971. Rtree *pRtree,
  124972. RtreeNode *pNode,
  124973. int iCell,
  124974. int iCoord,
  124975. RtreeCoord *pCoord /* Space to write result to */
  124976. ){
  124977. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  124978. }
  124979. /*
  124980. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  124981. ** to by pCell with the results.
  124982. */
  124983. static void nodeGetCell(
  124984. Rtree *pRtree,
  124985. RtreeNode *pNode,
  124986. int iCell,
  124987. RtreeCell *pCell
  124988. ){
  124989. int ii;
  124990. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  124991. for(ii=0; ii<pRtree->nDim*2; ii++){
  124992. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  124993. }
  124994. }
  124995. /* Forward declaration for the function that does the work of
  124996. ** the virtual table module xCreate() and xConnect() methods.
  124997. */
  124998. static int rtreeInit(
  124999. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  125000. );
  125001. /*
  125002. ** Rtree virtual table module xCreate method.
  125003. */
  125004. static int rtreeCreate(
  125005. sqlite3 *db,
  125006. void *pAux,
  125007. int argc, const char *const*argv,
  125008. sqlite3_vtab **ppVtab,
  125009. char **pzErr
  125010. ){
  125011. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  125012. }
  125013. /*
  125014. ** Rtree virtual table module xConnect method.
  125015. */
  125016. static int rtreeConnect(
  125017. sqlite3 *db,
  125018. void *pAux,
  125019. int argc, const char *const*argv,
  125020. sqlite3_vtab **ppVtab,
  125021. char **pzErr
  125022. ){
  125023. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  125024. }
  125025. /*
  125026. ** Increment the r-tree reference count.
  125027. */
  125028. static void rtreeReference(Rtree *pRtree){
  125029. pRtree->nBusy++;
  125030. }
  125031. /*
  125032. ** Decrement the r-tree reference count. When the reference count reaches
  125033. ** zero the structure is deleted.
  125034. */
  125035. static void rtreeRelease(Rtree *pRtree){
  125036. pRtree->nBusy--;
  125037. if( pRtree->nBusy==0 ){
  125038. sqlite3_finalize(pRtree->pReadNode);
  125039. sqlite3_finalize(pRtree->pWriteNode);
  125040. sqlite3_finalize(pRtree->pDeleteNode);
  125041. sqlite3_finalize(pRtree->pReadRowid);
  125042. sqlite3_finalize(pRtree->pWriteRowid);
  125043. sqlite3_finalize(pRtree->pDeleteRowid);
  125044. sqlite3_finalize(pRtree->pReadParent);
  125045. sqlite3_finalize(pRtree->pWriteParent);
  125046. sqlite3_finalize(pRtree->pDeleteParent);
  125047. sqlite3_free(pRtree);
  125048. }
  125049. }
  125050. /*
  125051. ** Rtree virtual table module xDisconnect method.
  125052. */
  125053. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  125054. rtreeRelease((Rtree *)pVtab);
  125055. return SQLITE_OK;
  125056. }
  125057. /*
  125058. ** Rtree virtual table module xDestroy method.
  125059. */
  125060. static int rtreeDestroy(sqlite3_vtab *pVtab){
  125061. Rtree *pRtree = (Rtree *)pVtab;
  125062. int rc;
  125063. char *zCreate = sqlite3_mprintf(
  125064. "DROP TABLE '%q'.'%q_node';"
  125065. "DROP TABLE '%q'.'%q_rowid';"
  125066. "DROP TABLE '%q'.'%q_parent';",
  125067. pRtree->zDb, pRtree->zName,
  125068. pRtree->zDb, pRtree->zName,
  125069. pRtree->zDb, pRtree->zName
  125070. );
  125071. if( !zCreate ){
  125072. rc = SQLITE_NOMEM;
  125073. }else{
  125074. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  125075. sqlite3_free(zCreate);
  125076. }
  125077. if( rc==SQLITE_OK ){
  125078. rtreeRelease(pRtree);
  125079. }
  125080. return rc;
  125081. }
  125082. /*
  125083. ** Rtree virtual table module xOpen method.
  125084. */
  125085. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  125086. int rc = SQLITE_NOMEM;
  125087. RtreeCursor *pCsr;
  125088. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  125089. if( pCsr ){
  125090. memset(pCsr, 0, sizeof(RtreeCursor));
  125091. pCsr->base.pVtab = pVTab;
  125092. rc = SQLITE_OK;
  125093. }
  125094. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  125095. return rc;
  125096. }
  125097. /*
  125098. ** Free the RtreeCursor.aConstraint[] array and its contents.
  125099. */
  125100. static void freeCursorConstraints(RtreeCursor *pCsr){
  125101. if( pCsr->aConstraint ){
  125102. int i; /* Used to iterate through constraint array */
  125103. for(i=0; i<pCsr->nConstraint; i++){
  125104. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  125105. if( pGeom ){
  125106. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  125107. sqlite3_free(pGeom);
  125108. }
  125109. }
  125110. sqlite3_free(pCsr->aConstraint);
  125111. pCsr->aConstraint = 0;
  125112. }
  125113. }
  125114. /*
  125115. ** Rtree virtual table module xClose method.
  125116. */
  125117. static int rtreeClose(sqlite3_vtab_cursor *cur){
  125118. Rtree *pRtree = (Rtree *)(cur->pVtab);
  125119. int rc;
  125120. RtreeCursor *pCsr = (RtreeCursor *)cur;
  125121. freeCursorConstraints(pCsr);
  125122. rc = nodeRelease(pRtree, pCsr->pNode);
  125123. sqlite3_free(pCsr);
  125124. return rc;
  125125. }
  125126. /*
  125127. ** Rtree virtual table module xEof method.
  125128. **
  125129. ** Return non-zero if the cursor does not currently point to a valid
  125130. ** record (i.e if the scan has finished), or zero otherwise.
  125131. */
  125132. static int rtreeEof(sqlite3_vtab_cursor *cur){
  125133. RtreeCursor *pCsr = (RtreeCursor *)cur;
  125134. return (pCsr->pNode==0);
  125135. }
  125136. /*
  125137. ** The r-tree constraint passed as the second argument to this function is
  125138. ** guaranteed to be a MATCH constraint.
  125139. */
  125140. static int testRtreeGeom(
  125141. Rtree *pRtree, /* R-Tree object */
  125142. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  125143. RtreeCell *pCell, /* Cell to test */
  125144. int *pbRes /* OUT: Test result */
  125145. ){
  125146. int i;
  125147. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  125148. int nCoord = pRtree->nDim*2;
  125149. assert( pConstraint->op==RTREE_MATCH );
  125150. assert( pConstraint->pGeom );
  125151. for(i=0; i<nCoord; i++){
  125152. aCoord[i] = DCOORD(pCell->aCoord[i]);
  125153. }
  125154. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  125155. }
  125156. /*
  125157. ** Cursor pCursor currently points to a cell in a non-leaf page.
  125158. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  125159. ** (excluded) by the constraints in the pCursor->aConstraint[]
  125160. ** array, or false otherwise.
  125161. **
  125162. ** Return SQLITE_OK if successful or an SQLite error code if an error
  125163. ** occurs within a geometry callback.
  125164. */
  125165. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  125166. RtreeCell cell;
  125167. int ii;
  125168. int bRes = 0;
  125169. int rc = SQLITE_OK;
  125170. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  125171. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  125172. RtreeConstraint *p = &pCursor->aConstraint[ii];
  125173. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  125174. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  125175. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  125176. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  125177. );
  125178. switch( p->op ){
  125179. case RTREE_LE: case RTREE_LT:
  125180. bRes = p->rValue<cell_min;
  125181. break;
  125182. case RTREE_GE: case RTREE_GT:
  125183. bRes = p->rValue>cell_max;
  125184. break;
  125185. case RTREE_EQ:
  125186. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  125187. break;
  125188. default: {
  125189. assert( p->op==RTREE_MATCH );
  125190. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  125191. bRes = !bRes;
  125192. break;
  125193. }
  125194. }
  125195. }
  125196. *pbEof = bRes;
  125197. return rc;
  125198. }
  125199. /*
  125200. ** Test if the cell that cursor pCursor currently points to
  125201. ** would be filtered (excluded) by the constraints in the
  125202. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  125203. ** returning. If the cell is not filtered (excluded) by the constraints,
  125204. ** set pbEof to zero.
  125205. **
  125206. ** Return SQLITE_OK if successful or an SQLite error code if an error
  125207. ** occurs within a geometry callback.
  125208. **
  125209. ** This function assumes that the cell is part of a leaf node.
  125210. */
  125211. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  125212. RtreeCell cell;
  125213. int ii;
  125214. *pbEof = 0;
  125215. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  125216. for(ii=0; ii<pCursor->nConstraint; ii++){
  125217. RtreeConstraint *p = &pCursor->aConstraint[ii];
  125218. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  125219. int res;
  125220. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  125221. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  125222. );
  125223. switch( p->op ){
  125224. case RTREE_LE: res = (coord<=p->rValue); break;
  125225. case RTREE_LT: res = (coord<p->rValue); break;
  125226. case RTREE_GE: res = (coord>=p->rValue); break;
  125227. case RTREE_GT: res = (coord>p->rValue); break;
  125228. case RTREE_EQ: res = (coord==p->rValue); break;
  125229. default: {
  125230. int rc;
  125231. assert( p->op==RTREE_MATCH );
  125232. rc = testRtreeGeom(pRtree, p, &cell, &res);
  125233. if( rc!=SQLITE_OK ){
  125234. return rc;
  125235. }
  125236. break;
  125237. }
  125238. }
  125239. if( !res ){
  125240. *pbEof = 1;
  125241. return SQLITE_OK;
  125242. }
  125243. }
  125244. return SQLITE_OK;
  125245. }
  125246. /*
  125247. ** Cursor pCursor currently points at a node that heads a sub-tree of
  125248. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  125249. ** to point to the left-most cell of the sub-tree that matches the
  125250. ** configured constraints.
  125251. */
  125252. static int descendToCell(
  125253. Rtree *pRtree,
  125254. RtreeCursor *pCursor,
  125255. int iHeight,
  125256. int *pEof /* OUT: Set to true if cannot descend */
  125257. ){
  125258. int isEof;
  125259. int rc;
  125260. int ii;
  125261. RtreeNode *pChild;
  125262. sqlite3_int64 iRowid;
  125263. RtreeNode *pSavedNode = pCursor->pNode;
  125264. int iSavedCell = pCursor->iCell;
  125265. assert( iHeight>=0 );
  125266. if( iHeight==0 ){
  125267. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  125268. }else{
  125269. rc = testRtreeCell(pRtree, pCursor, &isEof);
  125270. }
  125271. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  125272. goto descend_to_cell_out;
  125273. }
  125274. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  125275. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  125276. if( rc!=SQLITE_OK ){
  125277. goto descend_to_cell_out;
  125278. }
  125279. nodeRelease(pRtree, pCursor->pNode);
  125280. pCursor->pNode = pChild;
  125281. isEof = 1;
  125282. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  125283. pCursor->iCell = ii;
  125284. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  125285. if( rc!=SQLITE_OK ){
  125286. goto descend_to_cell_out;
  125287. }
  125288. }
  125289. if( isEof ){
  125290. assert( pCursor->pNode==pChild );
  125291. nodeReference(pSavedNode);
  125292. nodeRelease(pRtree, pChild);
  125293. pCursor->pNode = pSavedNode;
  125294. pCursor->iCell = iSavedCell;
  125295. }
  125296. descend_to_cell_out:
  125297. *pEof = isEof;
  125298. return rc;
  125299. }
  125300. /*
  125301. ** One of the cells in node pNode is guaranteed to have a 64-bit
  125302. ** integer value equal to iRowid. Return the index of this cell.
  125303. */
  125304. static int nodeRowidIndex(
  125305. Rtree *pRtree,
  125306. RtreeNode *pNode,
  125307. i64 iRowid,
  125308. int *piIndex
  125309. ){
  125310. int ii;
  125311. int nCell = NCELL(pNode);
  125312. for(ii=0; ii<nCell; ii++){
  125313. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  125314. *piIndex = ii;
  125315. return SQLITE_OK;
  125316. }
  125317. }
  125318. return SQLITE_CORRUPT_VTAB;
  125319. }
  125320. /*
  125321. ** Return the index of the cell containing a pointer to node pNode
  125322. ** in its parent. If pNode is the root node, return -1.
  125323. */
  125324. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  125325. RtreeNode *pParent = pNode->pParent;
  125326. if( pParent ){
  125327. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  125328. }
  125329. *piIndex = -1;
  125330. return SQLITE_OK;
  125331. }
  125332. /*
  125333. ** Rtree virtual table module xNext method.
  125334. */
  125335. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  125336. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  125337. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  125338. int rc = SQLITE_OK;
  125339. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  125340. ** already at EOF. It is against the rules to call the xNext() method of
  125341. ** a cursor that has already reached EOF.
  125342. */
  125343. assert( pCsr->pNode );
  125344. if( pCsr->iStrategy==1 ){
  125345. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  125346. nodeRelease(pRtree, pCsr->pNode);
  125347. pCsr->pNode = 0;
  125348. }else{
  125349. /* Move to the next entry that matches the configured constraints. */
  125350. int iHeight = 0;
  125351. while( pCsr->pNode ){
  125352. RtreeNode *pNode = pCsr->pNode;
  125353. int nCell = NCELL(pNode);
  125354. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  125355. int isEof;
  125356. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  125357. if( rc!=SQLITE_OK || !isEof ){
  125358. return rc;
  125359. }
  125360. }
  125361. pCsr->pNode = pNode->pParent;
  125362. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  125363. if( rc!=SQLITE_OK ){
  125364. return rc;
  125365. }
  125366. nodeReference(pCsr->pNode);
  125367. nodeRelease(pRtree, pNode);
  125368. iHeight++;
  125369. }
  125370. }
  125371. return rc;
  125372. }
  125373. /*
  125374. ** Rtree virtual table module xRowid method.
  125375. */
  125376. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  125377. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  125378. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  125379. assert(pCsr->pNode);
  125380. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  125381. return SQLITE_OK;
  125382. }
  125383. /*
  125384. ** Rtree virtual table module xColumn method.
  125385. */
  125386. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  125387. Rtree *pRtree = (Rtree *)cur->pVtab;
  125388. RtreeCursor *pCsr = (RtreeCursor *)cur;
  125389. if( i==0 ){
  125390. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  125391. sqlite3_result_int64(ctx, iRowid);
  125392. }else{
  125393. RtreeCoord c;
  125394. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  125395. #ifndef SQLITE_RTREE_INT_ONLY
  125396. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  125397. sqlite3_result_double(ctx, c.f);
  125398. }else
  125399. #endif
  125400. {
  125401. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  125402. sqlite3_result_int(ctx, c.i);
  125403. }
  125404. }
  125405. return SQLITE_OK;
  125406. }
  125407. /*
  125408. ** Use nodeAcquire() to obtain the leaf node containing the record with
  125409. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  125410. ** return SQLITE_OK. If there is no such record in the table, set
  125411. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  125412. ** to zero and return an SQLite error code.
  125413. */
  125414. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  125415. int rc;
  125416. *ppLeaf = 0;
  125417. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  125418. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  125419. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  125420. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  125421. sqlite3_reset(pRtree->pReadRowid);
  125422. }else{
  125423. rc = sqlite3_reset(pRtree->pReadRowid);
  125424. }
  125425. return rc;
  125426. }
  125427. /*
  125428. ** This function is called to configure the RtreeConstraint object passed
  125429. ** as the second argument for a MATCH constraint. The value passed as the
  125430. ** first argument to this function is the right-hand operand to the MATCH
  125431. ** operator.
  125432. */
  125433. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  125434. RtreeMatchArg *p;
  125435. sqlite3_rtree_geometry *pGeom;
  125436. int nBlob;
  125437. /* Check that value is actually a blob. */
  125438. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  125439. /* Check that the blob is roughly the right size. */
  125440. nBlob = sqlite3_value_bytes(pValue);
  125441. if( nBlob<(int)sizeof(RtreeMatchArg)
  125442. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  125443. ){
  125444. return SQLITE_ERROR;
  125445. }
  125446. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  125447. sizeof(sqlite3_rtree_geometry) + nBlob
  125448. );
  125449. if( !pGeom ) return SQLITE_NOMEM;
  125450. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  125451. p = (RtreeMatchArg *)&pGeom[1];
  125452. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  125453. if( p->magic!=RTREE_GEOMETRY_MAGIC
  125454. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  125455. ){
  125456. sqlite3_free(pGeom);
  125457. return SQLITE_ERROR;
  125458. }
  125459. pGeom->pContext = p->pContext;
  125460. pGeom->nParam = p->nParam;
  125461. pGeom->aParam = p->aParam;
  125462. pCons->xGeom = p->xGeom;
  125463. pCons->pGeom = pGeom;
  125464. return SQLITE_OK;
  125465. }
  125466. /*
  125467. ** Rtree virtual table module xFilter method.
  125468. */
  125469. static int rtreeFilter(
  125470. sqlite3_vtab_cursor *pVtabCursor,
  125471. int idxNum, const char *idxStr,
  125472. int argc, sqlite3_value **argv
  125473. ){
  125474. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  125475. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  125476. RtreeNode *pRoot = 0;
  125477. int ii;
  125478. int rc = SQLITE_OK;
  125479. rtreeReference(pRtree);
  125480. freeCursorConstraints(pCsr);
  125481. pCsr->iStrategy = idxNum;
  125482. if( idxNum==1 ){
  125483. /* Special case - lookup by rowid. */
  125484. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  125485. i64 iRowid = sqlite3_value_int64(argv[0]);
  125486. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  125487. pCsr->pNode = pLeaf;
  125488. if( pLeaf ){
  125489. assert( rc==SQLITE_OK );
  125490. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  125491. }
  125492. }else{
  125493. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  125494. ** with the configured constraints.
  125495. */
  125496. if( argc>0 ){
  125497. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  125498. pCsr->nConstraint = argc;
  125499. if( !pCsr->aConstraint ){
  125500. rc = SQLITE_NOMEM;
  125501. }else{
  125502. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  125503. assert( (idxStr==0 && argc==0)
  125504. || (idxStr && (int)strlen(idxStr)==argc*2) );
  125505. for(ii=0; ii<argc; ii++){
  125506. RtreeConstraint *p = &pCsr->aConstraint[ii];
  125507. p->op = idxStr[ii*2];
  125508. p->iCoord = idxStr[ii*2+1]-'a';
  125509. if( p->op==RTREE_MATCH ){
  125510. /* A MATCH operator. The right-hand-side must be a blob that
  125511. ** can be cast into an RtreeMatchArg object. One created using
  125512. ** an sqlite3_rtree_geometry_callback() SQL user function.
  125513. */
  125514. rc = deserializeGeometry(argv[ii], p);
  125515. if( rc!=SQLITE_OK ){
  125516. break;
  125517. }
  125518. }else{
  125519. #ifdef SQLITE_RTREE_INT_ONLY
  125520. p->rValue = sqlite3_value_int64(argv[ii]);
  125521. #else
  125522. p->rValue = sqlite3_value_double(argv[ii]);
  125523. #endif
  125524. }
  125525. }
  125526. }
  125527. }
  125528. if( rc==SQLITE_OK ){
  125529. pCsr->pNode = 0;
  125530. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  125531. }
  125532. if( rc==SQLITE_OK ){
  125533. int isEof = 1;
  125534. int nCell = NCELL(pRoot);
  125535. pCsr->pNode = pRoot;
  125536. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  125537. assert( pCsr->pNode==pRoot );
  125538. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  125539. if( !isEof ){
  125540. break;
  125541. }
  125542. }
  125543. if( rc==SQLITE_OK && isEof ){
  125544. assert( pCsr->pNode==pRoot );
  125545. nodeRelease(pRtree, pRoot);
  125546. pCsr->pNode = 0;
  125547. }
  125548. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  125549. }
  125550. }
  125551. rtreeRelease(pRtree);
  125552. return rc;
  125553. }
  125554. /*
  125555. ** Rtree virtual table module xBestIndex method. There are three
  125556. ** table scan strategies to choose from (in order from most to
  125557. ** least desirable):
  125558. **
  125559. ** idxNum idxStr Strategy
  125560. ** ------------------------------------------------
  125561. ** 1 Unused Direct lookup by rowid.
  125562. ** 2 See below R-tree query or full-table scan.
  125563. ** ------------------------------------------------
  125564. **
  125565. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  125566. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  125567. ** constraint used. The first two bytes of idxStr correspond to
  125568. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  125569. ** (argvIndex==1) etc.
  125570. **
  125571. ** The first of each pair of bytes in idxStr identifies the constraint
  125572. ** operator as follows:
  125573. **
  125574. ** Operator Byte Value
  125575. ** ----------------------
  125576. ** = 0x41 ('A')
  125577. ** <= 0x42 ('B')
  125578. ** < 0x43 ('C')
  125579. ** >= 0x44 ('D')
  125580. ** > 0x45 ('E')
  125581. ** MATCH 0x46 ('F')
  125582. ** ----------------------
  125583. **
  125584. ** The second of each pair of bytes identifies the coordinate column
  125585. ** to which the constraint applies. The leftmost coordinate column
  125586. ** is 'a', the second from the left 'b' etc.
  125587. */
  125588. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  125589. int rc = SQLITE_OK;
  125590. int ii;
  125591. int iIdx = 0;
  125592. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  125593. memset(zIdxStr, 0, sizeof(zIdxStr));
  125594. UNUSED_PARAMETER(tab);
  125595. assert( pIdxInfo->idxStr==0 );
  125596. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  125597. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  125598. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  125599. /* We have an equality constraint on the rowid. Use strategy 1. */
  125600. int jj;
  125601. for(jj=0; jj<ii; jj++){
  125602. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  125603. pIdxInfo->aConstraintUsage[jj].omit = 0;
  125604. }
  125605. pIdxInfo->idxNum = 1;
  125606. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  125607. pIdxInfo->aConstraintUsage[jj].omit = 1;
  125608. /* This strategy involves a two rowid lookups on an B-Tree structures
  125609. ** and then a linear search of an R-Tree node. This should be
  125610. ** considered almost as quick as a direct rowid lookup (for which
  125611. ** sqlite uses an internal cost of 0.0).
  125612. */
  125613. pIdxInfo->estimatedCost = 10.0;
  125614. return SQLITE_OK;
  125615. }
  125616. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  125617. u8 op;
  125618. switch( p->op ){
  125619. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  125620. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  125621. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  125622. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  125623. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  125624. default:
  125625. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  125626. op = RTREE_MATCH;
  125627. break;
  125628. }
  125629. zIdxStr[iIdx++] = op;
  125630. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  125631. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  125632. pIdxInfo->aConstraintUsage[ii].omit = 1;
  125633. }
  125634. }
  125635. pIdxInfo->idxNum = 2;
  125636. pIdxInfo->needToFreeIdxStr = 1;
  125637. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  125638. return SQLITE_NOMEM;
  125639. }
  125640. assert( iIdx>=0 );
  125641. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  125642. return rc;
  125643. }
  125644. /*
  125645. ** Return the N-dimensional volumn of the cell stored in *p.
  125646. */
  125647. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  125648. RtreeDValue area = (RtreeDValue)1;
  125649. int ii;
  125650. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  125651. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  125652. }
  125653. return area;
  125654. }
  125655. /*
  125656. ** Return the margin length of cell p. The margin length is the sum
  125657. ** of the objects size in each dimension.
  125658. */
  125659. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  125660. RtreeDValue margin = (RtreeDValue)0;
  125661. int ii;
  125662. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  125663. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  125664. }
  125665. return margin;
  125666. }
  125667. /*
  125668. ** Store the union of cells p1 and p2 in p1.
  125669. */
  125670. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  125671. int ii;
  125672. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  125673. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  125674. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  125675. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  125676. }
  125677. }else{
  125678. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  125679. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  125680. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  125681. }
  125682. }
  125683. }
  125684. /*
  125685. ** Return true if the area covered by p2 is a subset of the area covered
  125686. ** by p1. False otherwise.
  125687. */
  125688. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  125689. int ii;
  125690. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  125691. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  125692. RtreeCoord *a1 = &p1->aCoord[ii];
  125693. RtreeCoord *a2 = &p2->aCoord[ii];
  125694. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  125695. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  125696. ){
  125697. return 0;
  125698. }
  125699. }
  125700. return 1;
  125701. }
  125702. /*
  125703. ** Return the amount cell p would grow by if it were unioned with pCell.
  125704. */
  125705. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  125706. RtreeDValue area;
  125707. RtreeCell cell;
  125708. memcpy(&cell, p, sizeof(RtreeCell));
  125709. area = cellArea(pRtree, &cell);
  125710. cellUnion(pRtree, &cell, pCell);
  125711. return (cellArea(pRtree, &cell)-area);
  125712. }
  125713. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  125714. static RtreeDValue cellOverlap(
  125715. Rtree *pRtree,
  125716. RtreeCell *p,
  125717. RtreeCell *aCell,
  125718. int nCell,
  125719. int iExclude
  125720. ){
  125721. int ii;
  125722. RtreeDValue overlap = 0.0;
  125723. for(ii=0; ii<nCell; ii++){
  125724. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  125725. if( ii!=iExclude )
  125726. #else
  125727. assert( iExclude==-1 );
  125728. UNUSED_PARAMETER(iExclude);
  125729. #endif
  125730. {
  125731. int jj;
  125732. RtreeDValue o = (RtreeDValue)1;
  125733. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  125734. RtreeDValue x1, x2;
  125735. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  125736. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  125737. if( x2<x1 ){
  125738. o = 0.0;
  125739. break;
  125740. }else{
  125741. o = o * (x2-x1);
  125742. }
  125743. }
  125744. overlap += o;
  125745. }
  125746. }
  125747. return overlap;
  125748. }
  125749. #endif
  125750. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  125751. static RtreeDValue cellOverlapEnlargement(
  125752. Rtree *pRtree,
  125753. RtreeCell *p,
  125754. RtreeCell *pInsert,
  125755. RtreeCell *aCell,
  125756. int nCell,
  125757. int iExclude
  125758. ){
  125759. RtreeDValue before, after;
  125760. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  125761. cellUnion(pRtree, p, pInsert);
  125762. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  125763. return (after-before);
  125764. }
  125765. #endif
  125766. /*
  125767. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  125768. ** ChooseSubTree in r*tree terminology.
  125769. */
  125770. static int ChooseLeaf(
  125771. Rtree *pRtree, /* Rtree table */
  125772. RtreeCell *pCell, /* Cell to insert into rtree */
  125773. int iHeight, /* Height of sub-tree rooted at pCell */
  125774. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  125775. ){
  125776. int rc;
  125777. int ii;
  125778. RtreeNode *pNode;
  125779. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  125780. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  125781. int iCell;
  125782. sqlite3_int64 iBest = 0;
  125783. RtreeDValue fMinGrowth = 0.0;
  125784. RtreeDValue fMinArea = 0.0;
  125785. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  125786. RtreeDValue fMinOverlap = 0.0;
  125787. RtreeDValue overlap;
  125788. #endif
  125789. int nCell = NCELL(pNode);
  125790. RtreeCell cell;
  125791. RtreeNode *pChild;
  125792. RtreeCell *aCell = 0;
  125793. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  125794. if( ii==(pRtree->iDepth-1) ){
  125795. int jj;
  125796. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  125797. if( !aCell ){
  125798. rc = SQLITE_NOMEM;
  125799. nodeRelease(pRtree, pNode);
  125800. pNode = 0;
  125801. continue;
  125802. }
  125803. for(jj=0; jj<nCell; jj++){
  125804. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  125805. }
  125806. }
  125807. #endif
  125808. /* Select the child node which will be enlarged the least if pCell
  125809. ** is inserted into it. Resolve ties by choosing the entry with
  125810. ** the smallest area.
  125811. */
  125812. for(iCell=0; iCell<nCell; iCell++){
  125813. int bBest = 0;
  125814. RtreeDValue growth;
  125815. RtreeDValue area;
  125816. nodeGetCell(pRtree, pNode, iCell, &cell);
  125817. growth = cellGrowth(pRtree, &cell, pCell);
  125818. area = cellArea(pRtree, &cell);
  125819. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  125820. if( ii==(pRtree->iDepth-1) ){
  125821. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  125822. }else{
  125823. overlap = 0.0;
  125824. }
  125825. if( (iCell==0)
  125826. || (overlap<fMinOverlap)
  125827. || (overlap==fMinOverlap && growth<fMinGrowth)
  125828. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  125829. ){
  125830. bBest = 1;
  125831. fMinOverlap = overlap;
  125832. }
  125833. #else
  125834. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  125835. bBest = 1;
  125836. }
  125837. #endif
  125838. if( bBest ){
  125839. fMinGrowth = growth;
  125840. fMinArea = area;
  125841. iBest = cell.iRowid;
  125842. }
  125843. }
  125844. sqlite3_free(aCell);
  125845. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  125846. nodeRelease(pRtree, pNode);
  125847. pNode = pChild;
  125848. }
  125849. *ppLeaf = pNode;
  125850. return rc;
  125851. }
  125852. /*
  125853. ** A cell with the same content as pCell has just been inserted into
  125854. ** the node pNode. This function updates the bounding box cells in
  125855. ** all ancestor elements.
  125856. */
  125857. static int AdjustTree(
  125858. Rtree *pRtree, /* Rtree table */
  125859. RtreeNode *pNode, /* Adjust ancestry of this node. */
  125860. RtreeCell *pCell /* This cell was just inserted */
  125861. ){
  125862. RtreeNode *p = pNode;
  125863. while( p->pParent ){
  125864. RtreeNode *pParent = p->pParent;
  125865. RtreeCell cell;
  125866. int iCell;
  125867. if( nodeParentIndex(pRtree, p, &iCell) ){
  125868. return SQLITE_CORRUPT_VTAB;
  125869. }
  125870. nodeGetCell(pRtree, pParent, iCell, &cell);
  125871. if( !cellContains(pRtree, &cell, pCell) ){
  125872. cellUnion(pRtree, &cell, pCell);
  125873. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  125874. }
  125875. p = pParent;
  125876. }
  125877. return SQLITE_OK;
  125878. }
  125879. /*
  125880. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  125881. */
  125882. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  125883. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  125884. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  125885. sqlite3_step(pRtree->pWriteRowid);
  125886. return sqlite3_reset(pRtree->pWriteRowid);
  125887. }
  125888. /*
  125889. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  125890. */
  125891. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  125892. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  125893. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  125894. sqlite3_step(pRtree->pWriteParent);
  125895. return sqlite3_reset(pRtree->pWriteParent);
  125896. }
  125897. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  125898. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  125899. /*
  125900. ** Implementation of the linear variant of the PickNext() function from
  125901. ** Guttman[84].
  125902. */
  125903. static RtreeCell *LinearPickNext(
  125904. Rtree *pRtree,
  125905. RtreeCell *aCell,
  125906. int nCell,
  125907. RtreeCell *pLeftBox,
  125908. RtreeCell *pRightBox,
  125909. int *aiUsed
  125910. ){
  125911. int ii;
  125912. for(ii=0; aiUsed[ii]; ii++);
  125913. aiUsed[ii] = 1;
  125914. return &aCell[ii];
  125915. }
  125916. /*
  125917. ** Implementation of the linear variant of the PickSeeds() function from
  125918. ** Guttman[84].
  125919. */
  125920. static void LinearPickSeeds(
  125921. Rtree *pRtree,
  125922. RtreeCell *aCell,
  125923. int nCell,
  125924. int *piLeftSeed,
  125925. int *piRightSeed
  125926. ){
  125927. int i;
  125928. int iLeftSeed = 0;
  125929. int iRightSeed = 1;
  125930. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  125931. /* Pick two "seed" cells from the array of cells. The algorithm used
  125932. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  125933. ** indices of the two seed cells in the array are stored in local
  125934. ** variables iLeftSeek and iRightSeed.
  125935. */
  125936. for(i=0; i<pRtree->nDim; i++){
  125937. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  125938. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  125939. RtreeDValue x3 = x1;
  125940. RtreeDValue x4 = x2;
  125941. int jj;
  125942. int iCellLeft = 0;
  125943. int iCellRight = 0;
  125944. for(jj=1; jj<nCell; jj++){
  125945. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  125946. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  125947. if( left<x1 ) x1 = left;
  125948. if( right>x4 ) x4 = right;
  125949. if( left>x3 ){
  125950. x3 = left;
  125951. iCellRight = jj;
  125952. }
  125953. if( right<x2 ){
  125954. x2 = right;
  125955. iCellLeft = jj;
  125956. }
  125957. }
  125958. if( x4!=x1 ){
  125959. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  125960. if( normalwidth>maxNormalInnerWidth ){
  125961. iLeftSeed = iCellLeft;
  125962. iRightSeed = iCellRight;
  125963. }
  125964. }
  125965. }
  125966. *piLeftSeed = iLeftSeed;
  125967. *piRightSeed = iRightSeed;
  125968. }
  125969. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  125970. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  125971. /*
  125972. ** Implementation of the quadratic variant of the PickNext() function from
  125973. ** Guttman[84].
  125974. */
  125975. static RtreeCell *QuadraticPickNext(
  125976. Rtree *pRtree,
  125977. RtreeCell *aCell,
  125978. int nCell,
  125979. RtreeCell *pLeftBox,
  125980. RtreeCell *pRightBox,
  125981. int *aiUsed
  125982. ){
  125983. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  125984. int iSelect = -1;
  125985. RtreeDValue fDiff;
  125986. int ii;
  125987. for(ii=0; ii<nCell; ii++){
  125988. if( aiUsed[ii]==0 ){
  125989. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  125990. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  125991. RtreeDValue diff = FABS(right-left);
  125992. if( iSelect<0 || diff>fDiff ){
  125993. fDiff = diff;
  125994. iSelect = ii;
  125995. }
  125996. }
  125997. }
  125998. aiUsed[iSelect] = 1;
  125999. return &aCell[iSelect];
  126000. }
  126001. /*
  126002. ** Implementation of the quadratic variant of the PickSeeds() function from
  126003. ** Guttman[84].
  126004. */
  126005. static void QuadraticPickSeeds(
  126006. Rtree *pRtree,
  126007. RtreeCell *aCell,
  126008. int nCell,
  126009. int *piLeftSeed,
  126010. int *piRightSeed
  126011. ){
  126012. int ii;
  126013. int jj;
  126014. int iLeftSeed = 0;
  126015. int iRightSeed = 1;
  126016. RtreeDValue fWaste = 0.0;
  126017. for(ii=0; ii<nCell; ii++){
  126018. for(jj=ii+1; jj<nCell; jj++){
  126019. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  126020. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  126021. RtreeDValue waste = growth - right;
  126022. if( waste>fWaste ){
  126023. iLeftSeed = ii;
  126024. iRightSeed = jj;
  126025. fWaste = waste;
  126026. }
  126027. }
  126028. }
  126029. *piLeftSeed = iLeftSeed;
  126030. *piRightSeed = iRightSeed;
  126031. }
  126032. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  126033. /*
  126034. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  126035. ** nIdx. The aIdx array contains the set of integers from 0 to
  126036. ** (nIdx-1) in no particular order. This function sorts the values
  126037. ** in aIdx according to the indexed values in aDistance. For
  126038. ** example, assuming the inputs:
  126039. **
  126040. ** aIdx = { 0, 1, 2, 3 }
  126041. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  126042. **
  126043. ** this function sets the aIdx array to contain:
  126044. **
  126045. ** aIdx = { 0, 1, 2, 3 }
  126046. **
  126047. ** The aSpare array is used as temporary working space by the
  126048. ** sorting algorithm.
  126049. */
  126050. static void SortByDistance(
  126051. int *aIdx,
  126052. int nIdx,
  126053. RtreeDValue *aDistance,
  126054. int *aSpare
  126055. ){
  126056. if( nIdx>1 ){
  126057. int iLeft = 0;
  126058. int iRight = 0;
  126059. int nLeft = nIdx/2;
  126060. int nRight = nIdx-nLeft;
  126061. int *aLeft = aIdx;
  126062. int *aRight = &aIdx[nLeft];
  126063. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  126064. SortByDistance(aRight, nRight, aDistance, aSpare);
  126065. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  126066. aLeft = aSpare;
  126067. while( iLeft<nLeft || iRight<nRight ){
  126068. if( iLeft==nLeft ){
  126069. aIdx[iLeft+iRight] = aRight[iRight];
  126070. iRight++;
  126071. }else if( iRight==nRight ){
  126072. aIdx[iLeft+iRight] = aLeft[iLeft];
  126073. iLeft++;
  126074. }else{
  126075. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  126076. RtreeDValue fRight = aDistance[aRight[iRight]];
  126077. if( fLeft<fRight ){
  126078. aIdx[iLeft+iRight] = aLeft[iLeft];
  126079. iLeft++;
  126080. }else{
  126081. aIdx[iLeft+iRight] = aRight[iRight];
  126082. iRight++;
  126083. }
  126084. }
  126085. }
  126086. #if 0
  126087. /* Check that the sort worked */
  126088. {
  126089. int jj;
  126090. for(jj=1; jj<nIdx; jj++){
  126091. RtreeDValue left = aDistance[aIdx[jj-1]];
  126092. RtreeDValue right = aDistance[aIdx[jj]];
  126093. assert( left<=right );
  126094. }
  126095. }
  126096. #endif
  126097. }
  126098. }
  126099. /*
  126100. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  126101. ** nIdx. The aIdx array contains the set of integers from 0 to
  126102. ** (nIdx-1) in no particular order. This function sorts the values
  126103. ** in aIdx according to dimension iDim of the cells in aCell. The
  126104. ** minimum value of dimension iDim is considered first, the
  126105. ** maximum used to break ties.
  126106. **
  126107. ** The aSpare array is used as temporary working space by the
  126108. ** sorting algorithm.
  126109. */
  126110. static void SortByDimension(
  126111. Rtree *pRtree,
  126112. int *aIdx,
  126113. int nIdx,
  126114. int iDim,
  126115. RtreeCell *aCell,
  126116. int *aSpare
  126117. ){
  126118. if( nIdx>1 ){
  126119. int iLeft = 0;
  126120. int iRight = 0;
  126121. int nLeft = nIdx/2;
  126122. int nRight = nIdx-nLeft;
  126123. int *aLeft = aIdx;
  126124. int *aRight = &aIdx[nLeft];
  126125. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  126126. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  126127. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  126128. aLeft = aSpare;
  126129. while( iLeft<nLeft || iRight<nRight ){
  126130. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  126131. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  126132. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  126133. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  126134. if( (iLeft!=nLeft) && ((iRight==nRight)
  126135. || (xleft1<xright1)
  126136. || (xleft1==xright1 && xleft2<xright2)
  126137. )){
  126138. aIdx[iLeft+iRight] = aLeft[iLeft];
  126139. iLeft++;
  126140. }else{
  126141. aIdx[iLeft+iRight] = aRight[iRight];
  126142. iRight++;
  126143. }
  126144. }
  126145. #if 0
  126146. /* Check that the sort worked */
  126147. {
  126148. int jj;
  126149. for(jj=1; jj<nIdx; jj++){
  126150. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  126151. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  126152. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  126153. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  126154. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  126155. }
  126156. }
  126157. #endif
  126158. }
  126159. }
  126160. #if VARIANT_RSTARTREE_SPLIT
  126161. /*
  126162. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  126163. */
  126164. static int splitNodeStartree(
  126165. Rtree *pRtree,
  126166. RtreeCell *aCell,
  126167. int nCell,
  126168. RtreeNode *pLeft,
  126169. RtreeNode *pRight,
  126170. RtreeCell *pBboxLeft,
  126171. RtreeCell *pBboxRight
  126172. ){
  126173. int **aaSorted;
  126174. int *aSpare;
  126175. int ii;
  126176. int iBestDim = 0;
  126177. int iBestSplit = 0;
  126178. RtreeDValue fBestMargin = 0.0;
  126179. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  126180. aaSorted = (int **)sqlite3_malloc(nByte);
  126181. if( !aaSorted ){
  126182. return SQLITE_NOMEM;
  126183. }
  126184. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  126185. memset(aaSorted, 0, nByte);
  126186. for(ii=0; ii<pRtree->nDim; ii++){
  126187. int jj;
  126188. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  126189. for(jj=0; jj<nCell; jj++){
  126190. aaSorted[ii][jj] = jj;
  126191. }
  126192. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  126193. }
  126194. for(ii=0; ii<pRtree->nDim; ii++){
  126195. RtreeDValue margin = 0.0;
  126196. RtreeDValue fBestOverlap = 0.0;
  126197. RtreeDValue fBestArea = 0.0;
  126198. int iBestLeft = 0;
  126199. int nLeft;
  126200. for(
  126201. nLeft=RTREE_MINCELLS(pRtree);
  126202. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  126203. nLeft++
  126204. ){
  126205. RtreeCell left;
  126206. RtreeCell right;
  126207. int kk;
  126208. RtreeDValue overlap;
  126209. RtreeDValue area;
  126210. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  126211. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  126212. for(kk=1; kk<(nCell-1); kk++){
  126213. if( kk<nLeft ){
  126214. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  126215. }else{
  126216. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  126217. }
  126218. }
  126219. margin += cellMargin(pRtree, &left);
  126220. margin += cellMargin(pRtree, &right);
  126221. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  126222. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  126223. if( (nLeft==RTREE_MINCELLS(pRtree))
  126224. || (overlap<fBestOverlap)
  126225. || (overlap==fBestOverlap && area<fBestArea)
  126226. ){
  126227. iBestLeft = nLeft;
  126228. fBestOverlap = overlap;
  126229. fBestArea = area;
  126230. }
  126231. }
  126232. if( ii==0 || margin<fBestMargin ){
  126233. iBestDim = ii;
  126234. fBestMargin = margin;
  126235. iBestSplit = iBestLeft;
  126236. }
  126237. }
  126238. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  126239. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  126240. for(ii=0; ii<nCell; ii++){
  126241. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  126242. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  126243. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  126244. nodeInsertCell(pRtree, pTarget, pCell);
  126245. cellUnion(pRtree, pBbox, pCell);
  126246. }
  126247. sqlite3_free(aaSorted);
  126248. return SQLITE_OK;
  126249. }
  126250. #endif
  126251. #if VARIANT_GUTTMAN_SPLIT
  126252. /*
  126253. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  126254. */
  126255. static int splitNodeGuttman(
  126256. Rtree *pRtree,
  126257. RtreeCell *aCell,
  126258. int nCell,
  126259. RtreeNode *pLeft,
  126260. RtreeNode *pRight,
  126261. RtreeCell *pBboxLeft,
  126262. RtreeCell *pBboxRight
  126263. ){
  126264. int iLeftSeed = 0;
  126265. int iRightSeed = 1;
  126266. int *aiUsed;
  126267. int i;
  126268. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  126269. if( !aiUsed ){
  126270. return SQLITE_NOMEM;
  126271. }
  126272. memset(aiUsed, 0, sizeof(int)*nCell);
  126273. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  126274. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  126275. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  126276. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  126277. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  126278. aiUsed[iLeftSeed] = 1;
  126279. aiUsed[iRightSeed] = 1;
  126280. for(i=nCell-2; i>0; i--){
  126281. RtreeCell *pNext;
  126282. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  126283. RtreeDValue diff =
  126284. cellGrowth(pRtree, pBboxLeft, pNext) -
  126285. cellGrowth(pRtree, pBboxRight, pNext)
  126286. ;
  126287. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  126288. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  126289. ){
  126290. nodeInsertCell(pRtree, pRight, pNext);
  126291. cellUnion(pRtree, pBboxRight, pNext);
  126292. }else{
  126293. nodeInsertCell(pRtree, pLeft, pNext);
  126294. cellUnion(pRtree, pBboxLeft, pNext);
  126295. }
  126296. }
  126297. sqlite3_free(aiUsed);
  126298. return SQLITE_OK;
  126299. }
  126300. #endif
  126301. static int updateMapping(
  126302. Rtree *pRtree,
  126303. i64 iRowid,
  126304. RtreeNode *pNode,
  126305. int iHeight
  126306. ){
  126307. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  126308. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  126309. if( iHeight>0 ){
  126310. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  126311. if( pChild ){
  126312. nodeRelease(pRtree, pChild->pParent);
  126313. nodeReference(pNode);
  126314. pChild->pParent = pNode;
  126315. }
  126316. }
  126317. return xSetMapping(pRtree, iRowid, pNode->iNode);
  126318. }
  126319. static int SplitNode(
  126320. Rtree *pRtree,
  126321. RtreeNode *pNode,
  126322. RtreeCell *pCell,
  126323. int iHeight
  126324. ){
  126325. int i;
  126326. int newCellIsRight = 0;
  126327. int rc = SQLITE_OK;
  126328. int nCell = NCELL(pNode);
  126329. RtreeCell *aCell;
  126330. int *aiUsed;
  126331. RtreeNode *pLeft = 0;
  126332. RtreeNode *pRight = 0;
  126333. RtreeCell leftbbox;
  126334. RtreeCell rightbbox;
  126335. /* Allocate an array and populate it with a copy of pCell and
  126336. ** all cells from node pLeft. Then zero the original node.
  126337. */
  126338. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  126339. if( !aCell ){
  126340. rc = SQLITE_NOMEM;
  126341. goto splitnode_out;
  126342. }
  126343. aiUsed = (int *)&aCell[nCell+1];
  126344. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  126345. for(i=0; i<nCell; i++){
  126346. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  126347. }
  126348. nodeZero(pRtree, pNode);
  126349. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  126350. nCell++;
  126351. if( pNode->iNode==1 ){
  126352. pRight = nodeNew(pRtree, pNode);
  126353. pLeft = nodeNew(pRtree, pNode);
  126354. pRtree->iDepth++;
  126355. pNode->isDirty = 1;
  126356. writeInt16(pNode->zData, pRtree->iDepth);
  126357. }else{
  126358. pLeft = pNode;
  126359. pRight = nodeNew(pRtree, pLeft->pParent);
  126360. nodeReference(pLeft);
  126361. }
  126362. if( !pLeft || !pRight ){
  126363. rc = SQLITE_NOMEM;
  126364. goto splitnode_out;
  126365. }
  126366. memset(pLeft->zData, 0, pRtree->iNodeSize);
  126367. memset(pRight->zData, 0, pRtree->iNodeSize);
  126368. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  126369. if( rc!=SQLITE_OK ){
  126370. goto splitnode_out;
  126371. }
  126372. /* Ensure both child nodes have node numbers assigned to them by calling
  126373. ** nodeWrite(). Node pRight always needs a node number, as it was created
  126374. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  126375. ** In this case avoid the all to nodeWrite().
  126376. */
  126377. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  126378. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  126379. ){
  126380. goto splitnode_out;
  126381. }
  126382. rightbbox.iRowid = pRight->iNode;
  126383. leftbbox.iRowid = pLeft->iNode;
  126384. if( pNode->iNode==1 ){
  126385. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  126386. if( rc!=SQLITE_OK ){
  126387. goto splitnode_out;
  126388. }
  126389. }else{
  126390. RtreeNode *pParent = pLeft->pParent;
  126391. int iCell;
  126392. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  126393. if( rc==SQLITE_OK ){
  126394. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  126395. rc = AdjustTree(pRtree, pParent, &leftbbox);
  126396. }
  126397. if( rc!=SQLITE_OK ){
  126398. goto splitnode_out;
  126399. }
  126400. }
  126401. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  126402. goto splitnode_out;
  126403. }
  126404. for(i=0; i<NCELL(pRight); i++){
  126405. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  126406. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  126407. if( iRowid==pCell->iRowid ){
  126408. newCellIsRight = 1;
  126409. }
  126410. if( rc!=SQLITE_OK ){
  126411. goto splitnode_out;
  126412. }
  126413. }
  126414. if( pNode->iNode==1 ){
  126415. for(i=0; i<NCELL(pLeft); i++){
  126416. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  126417. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  126418. if( rc!=SQLITE_OK ){
  126419. goto splitnode_out;
  126420. }
  126421. }
  126422. }else if( newCellIsRight==0 ){
  126423. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  126424. }
  126425. if( rc==SQLITE_OK ){
  126426. rc = nodeRelease(pRtree, pRight);
  126427. pRight = 0;
  126428. }
  126429. if( rc==SQLITE_OK ){
  126430. rc = nodeRelease(pRtree, pLeft);
  126431. pLeft = 0;
  126432. }
  126433. splitnode_out:
  126434. nodeRelease(pRtree, pRight);
  126435. nodeRelease(pRtree, pLeft);
  126436. sqlite3_free(aCell);
  126437. return rc;
  126438. }
  126439. /*
  126440. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  126441. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  126442. ** the pLeaf->pParent chain all the way up to the root node.
  126443. **
  126444. ** This operation is required when a row is deleted (or updated - an update
  126445. ** is implemented as a delete followed by an insert). SQLite provides the
  126446. ** rowid of the row to delete, which can be used to find the leaf on which
  126447. ** the entry resides (argument pLeaf). Once the leaf is located, this
  126448. ** function is called to determine its ancestry.
  126449. */
  126450. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  126451. int rc = SQLITE_OK;
  126452. RtreeNode *pChild = pLeaf;
  126453. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  126454. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  126455. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  126456. rc = sqlite3_step(pRtree->pReadParent);
  126457. if( rc==SQLITE_ROW ){
  126458. RtreeNode *pTest; /* Used to test for reference loops */
  126459. i64 iNode; /* Node number of parent node */
  126460. /* Before setting pChild->pParent, test that we are not creating a
  126461. ** loop of references (as we would if, say, pChild==pParent). We don't
  126462. ** want to do this as it leads to a memory leak when trying to delete
  126463. ** the referenced counted node structures.
  126464. */
  126465. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  126466. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  126467. if( !pTest ){
  126468. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  126469. }
  126470. }
  126471. rc = sqlite3_reset(pRtree->pReadParent);
  126472. if( rc==SQLITE_OK ) rc = rc2;
  126473. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  126474. pChild = pChild->pParent;
  126475. }
  126476. return rc;
  126477. }
  126478. static int deleteCell(Rtree *, RtreeNode *, int, int);
  126479. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  126480. int rc;
  126481. int rc2;
  126482. RtreeNode *pParent = 0;
  126483. int iCell;
  126484. assert( pNode->nRef==1 );
  126485. /* Remove the entry in the parent cell. */
  126486. rc = nodeParentIndex(pRtree, pNode, &iCell);
  126487. if( rc==SQLITE_OK ){
  126488. pParent = pNode->pParent;
  126489. pNode->pParent = 0;
  126490. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  126491. }
  126492. rc2 = nodeRelease(pRtree, pParent);
  126493. if( rc==SQLITE_OK ){
  126494. rc = rc2;
  126495. }
  126496. if( rc!=SQLITE_OK ){
  126497. return rc;
  126498. }
  126499. /* Remove the xxx_node entry. */
  126500. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  126501. sqlite3_step(pRtree->pDeleteNode);
  126502. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  126503. return rc;
  126504. }
  126505. /* Remove the xxx_parent entry. */
  126506. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  126507. sqlite3_step(pRtree->pDeleteParent);
  126508. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  126509. return rc;
  126510. }
  126511. /* Remove the node from the in-memory hash table and link it into
  126512. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  126513. */
  126514. nodeHashDelete(pRtree, pNode);
  126515. pNode->iNode = iHeight;
  126516. pNode->pNext = pRtree->pDeleted;
  126517. pNode->nRef++;
  126518. pRtree->pDeleted = pNode;
  126519. return SQLITE_OK;
  126520. }
  126521. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  126522. RtreeNode *pParent = pNode->pParent;
  126523. int rc = SQLITE_OK;
  126524. if( pParent ){
  126525. int ii;
  126526. int nCell = NCELL(pNode);
  126527. RtreeCell box; /* Bounding box for pNode */
  126528. nodeGetCell(pRtree, pNode, 0, &box);
  126529. for(ii=1; ii<nCell; ii++){
  126530. RtreeCell cell;
  126531. nodeGetCell(pRtree, pNode, ii, &cell);
  126532. cellUnion(pRtree, &box, &cell);
  126533. }
  126534. box.iRowid = pNode->iNode;
  126535. rc = nodeParentIndex(pRtree, pNode, &ii);
  126536. if( rc==SQLITE_OK ){
  126537. nodeOverwriteCell(pRtree, pParent, &box, ii);
  126538. rc = fixBoundingBox(pRtree, pParent);
  126539. }
  126540. }
  126541. return rc;
  126542. }
  126543. /*
  126544. ** Delete the cell at index iCell of node pNode. After removing the
  126545. ** cell, adjust the r-tree data structure if required.
  126546. */
  126547. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  126548. RtreeNode *pParent;
  126549. int rc;
  126550. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  126551. return rc;
  126552. }
  126553. /* Remove the cell from the node. This call just moves bytes around
  126554. ** the in-memory node image, so it cannot fail.
  126555. */
  126556. nodeDeleteCell(pRtree, pNode, iCell);
  126557. /* If the node is not the tree root and now has less than the minimum
  126558. ** number of cells, remove it from the tree. Otherwise, update the
  126559. ** cell in the parent node so that it tightly contains the updated
  126560. ** node.
  126561. */
  126562. pParent = pNode->pParent;
  126563. assert( pParent || pNode->iNode==1 );
  126564. if( pParent ){
  126565. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  126566. rc = removeNode(pRtree, pNode, iHeight);
  126567. }else{
  126568. rc = fixBoundingBox(pRtree, pNode);
  126569. }
  126570. }
  126571. return rc;
  126572. }
  126573. static int Reinsert(
  126574. Rtree *pRtree,
  126575. RtreeNode *pNode,
  126576. RtreeCell *pCell,
  126577. int iHeight
  126578. ){
  126579. int *aOrder;
  126580. int *aSpare;
  126581. RtreeCell *aCell;
  126582. RtreeDValue *aDistance;
  126583. int nCell;
  126584. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  126585. int iDim;
  126586. int ii;
  126587. int rc = SQLITE_OK;
  126588. int n;
  126589. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  126590. nCell = NCELL(pNode)+1;
  126591. n = (nCell+1)&(~1);
  126592. /* Allocate the buffers used by this operation. The allocation is
  126593. ** relinquished before this function returns.
  126594. */
  126595. aCell = (RtreeCell *)sqlite3_malloc(n * (
  126596. sizeof(RtreeCell) + /* aCell array */
  126597. sizeof(int) + /* aOrder array */
  126598. sizeof(int) + /* aSpare array */
  126599. sizeof(RtreeDValue) /* aDistance array */
  126600. ));
  126601. if( !aCell ){
  126602. return SQLITE_NOMEM;
  126603. }
  126604. aOrder = (int *)&aCell[n];
  126605. aSpare = (int *)&aOrder[n];
  126606. aDistance = (RtreeDValue *)&aSpare[n];
  126607. for(ii=0; ii<nCell; ii++){
  126608. if( ii==(nCell-1) ){
  126609. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  126610. }else{
  126611. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  126612. }
  126613. aOrder[ii] = ii;
  126614. for(iDim=0; iDim<pRtree->nDim; iDim++){
  126615. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  126616. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  126617. }
  126618. }
  126619. for(iDim=0; iDim<pRtree->nDim; iDim++){
  126620. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  126621. }
  126622. for(ii=0; ii<nCell; ii++){
  126623. aDistance[ii] = 0.0;
  126624. for(iDim=0; iDim<pRtree->nDim; iDim++){
  126625. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  126626. DCOORD(aCell[ii].aCoord[iDim*2]));
  126627. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  126628. }
  126629. }
  126630. SortByDistance(aOrder, nCell, aDistance, aSpare);
  126631. nodeZero(pRtree, pNode);
  126632. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  126633. RtreeCell *p = &aCell[aOrder[ii]];
  126634. nodeInsertCell(pRtree, pNode, p);
  126635. if( p->iRowid==pCell->iRowid ){
  126636. if( iHeight==0 ){
  126637. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  126638. }else{
  126639. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  126640. }
  126641. }
  126642. }
  126643. if( rc==SQLITE_OK ){
  126644. rc = fixBoundingBox(pRtree, pNode);
  126645. }
  126646. for(; rc==SQLITE_OK && ii<nCell; ii++){
  126647. /* Find a node to store this cell in. pNode->iNode currently contains
  126648. ** the height of the sub-tree headed by the cell.
  126649. */
  126650. RtreeNode *pInsert;
  126651. RtreeCell *p = &aCell[aOrder[ii]];
  126652. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  126653. if( rc==SQLITE_OK ){
  126654. int rc2;
  126655. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  126656. rc2 = nodeRelease(pRtree, pInsert);
  126657. if( rc==SQLITE_OK ){
  126658. rc = rc2;
  126659. }
  126660. }
  126661. }
  126662. sqlite3_free(aCell);
  126663. return rc;
  126664. }
  126665. /*
  126666. ** Insert cell pCell into node pNode. Node pNode is the head of a
  126667. ** subtree iHeight high (leaf nodes have iHeight==0).
  126668. */
  126669. static int rtreeInsertCell(
  126670. Rtree *pRtree,
  126671. RtreeNode *pNode,
  126672. RtreeCell *pCell,
  126673. int iHeight
  126674. ){
  126675. int rc = SQLITE_OK;
  126676. if( iHeight>0 ){
  126677. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  126678. if( pChild ){
  126679. nodeRelease(pRtree, pChild->pParent);
  126680. nodeReference(pNode);
  126681. pChild->pParent = pNode;
  126682. }
  126683. }
  126684. if( nodeInsertCell(pRtree, pNode, pCell) ){
  126685. #if VARIANT_RSTARTREE_REINSERT
  126686. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  126687. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  126688. }else{
  126689. pRtree->iReinsertHeight = iHeight;
  126690. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  126691. }
  126692. #else
  126693. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  126694. #endif
  126695. }else{
  126696. rc = AdjustTree(pRtree, pNode, pCell);
  126697. if( rc==SQLITE_OK ){
  126698. if( iHeight==0 ){
  126699. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  126700. }else{
  126701. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  126702. }
  126703. }
  126704. }
  126705. return rc;
  126706. }
  126707. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  126708. int ii;
  126709. int rc = SQLITE_OK;
  126710. int nCell = NCELL(pNode);
  126711. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  126712. RtreeNode *pInsert;
  126713. RtreeCell cell;
  126714. nodeGetCell(pRtree, pNode, ii, &cell);
  126715. /* Find a node to store this cell in. pNode->iNode currently contains
  126716. ** the height of the sub-tree headed by the cell.
  126717. */
  126718. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  126719. if( rc==SQLITE_OK ){
  126720. int rc2;
  126721. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  126722. rc2 = nodeRelease(pRtree, pInsert);
  126723. if( rc==SQLITE_OK ){
  126724. rc = rc2;
  126725. }
  126726. }
  126727. }
  126728. return rc;
  126729. }
  126730. /*
  126731. ** Select a currently unused rowid for a new r-tree record.
  126732. */
  126733. static int newRowid(Rtree *pRtree, i64 *piRowid){
  126734. int rc;
  126735. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  126736. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  126737. sqlite3_step(pRtree->pWriteRowid);
  126738. rc = sqlite3_reset(pRtree->pWriteRowid);
  126739. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  126740. return rc;
  126741. }
  126742. /*
  126743. ** Remove the entry with rowid=iDelete from the r-tree structure.
  126744. */
  126745. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  126746. int rc; /* Return code */
  126747. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  126748. int iCell; /* Index of iDelete cell in pLeaf */
  126749. RtreeNode *pRoot; /* Root node of rtree structure */
  126750. /* Obtain a reference to the root node to initialise Rtree.iDepth */
  126751. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  126752. /* Obtain a reference to the leaf node that contains the entry
  126753. ** about to be deleted.
  126754. */
  126755. if( rc==SQLITE_OK ){
  126756. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  126757. }
  126758. /* Delete the cell in question from the leaf node. */
  126759. if( rc==SQLITE_OK ){
  126760. int rc2;
  126761. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  126762. if( rc==SQLITE_OK ){
  126763. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  126764. }
  126765. rc2 = nodeRelease(pRtree, pLeaf);
  126766. if( rc==SQLITE_OK ){
  126767. rc = rc2;
  126768. }
  126769. }
  126770. /* Delete the corresponding entry in the <rtree>_rowid table. */
  126771. if( rc==SQLITE_OK ){
  126772. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  126773. sqlite3_step(pRtree->pDeleteRowid);
  126774. rc = sqlite3_reset(pRtree->pDeleteRowid);
  126775. }
  126776. /* Check if the root node now has exactly one child. If so, remove
  126777. ** it, schedule the contents of the child for reinsertion and
  126778. ** reduce the tree height by one.
  126779. **
  126780. ** This is equivalent to copying the contents of the child into
  126781. ** the root node (the operation that Gutman's paper says to perform
  126782. ** in this scenario).
  126783. */
  126784. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  126785. int rc2;
  126786. RtreeNode *pChild;
  126787. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  126788. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  126789. if( rc==SQLITE_OK ){
  126790. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  126791. }
  126792. rc2 = nodeRelease(pRtree, pChild);
  126793. if( rc==SQLITE_OK ) rc = rc2;
  126794. if( rc==SQLITE_OK ){
  126795. pRtree->iDepth--;
  126796. writeInt16(pRoot->zData, pRtree->iDepth);
  126797. pRoot->isDirty = 1;
  126798. }
  126799. }
  126800. /* Re-insert the contents of any underfull nodes removed from the tree. */
  126801. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  126802. if( rc==SQLITE_OK ){
  126803. rc = reinsertNodeContent(pRtree, pLeaf);
  126804. }
  126805. pRtree->pDeleted = pLeaf->pNext;
  126806. sqlite3_free(pLeaf);
  126807. }
  126808. /* Release the reference to the root node. */
  126809. if( rc==SQLITE_OK ){
  126810. rc = nodeRelease(pRtree, pRoot);
  126811. }else{
  126812. nodeRelease(pRtree, pRoot);
  126813. }
  126814. return rc;
  126815. }
  126816. /*
  126817. ** Rounding constants for float->double conversion.
  126818. */
  126819. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  126820. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  126821. #if !defined(SQLITE_RTREE_INT_ONLY)
  126822. /*
  126823. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  126824. ** while taking care to round toward negative or positive, respectively.
  126825. */
  126826. static RtreeValue rtreeValueDown(sqlite3_value *v){
  126827. double d = sqlite3_value_double(v);
  126828. float f = (float)d;
  126829. if( f>d ){
  126830. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  126831. }
  126832. return f;
  126833. }
  126834. static RtreeValue rtreeValueUp(sqlite3_value *v){
  126835. double d = sqlite3_value_double(v);
  126836. float f = (float)d;
  126837. if( f<d ){
  126838. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  126839. }
  126840. return f;
  126841. }
  126842. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  126843. /*
  126844. ** The xUpdate method for rtree module virtual tables.
  126845. */
  126846. static int rtreeUpdate(
  126847. sqlite3_vtab *pVtab,
  126848. int nData,
  126849. sqlite3_value **azData,
  126850. sqlite_int64 *pRowid
  126851. ){
  126852. Rtree *pRtree = (Rtree *)pVtab;
  126853. int rc = SQLITE_OK;
  126854. RtreeCell cell; /* New cell to insert if nData>1 */
  126855. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  126856. rtreeReference(pRtree);
  126857. assert(nData>=1);
  126858. /* Constraint handling. A write operation on an r-tree table may return
  126859. ** SQLITE_CONSTRAINT for two reasons:
  126860. **
  126861. ** 1. A duplicate rowid value, or
  126862. ** 2. The supplied data violates the "x2>=x1" constraint.
  126863. **
  126864. ** In the first case, if the conflict-handling mode is REPLACE, then
  126865. ** the conflicting row can be removed before proceeding. In the second
  126866. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  126867. ** conflict-handling mode specified by the user.
  126868. */
  126869. if( nData>1 ){
  126870. int ii;
  126871. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  126872. assert( nData==(pRtree->nDim*2 + 3) );
  126873. #ifndef SQLITE_RTREE_INT_ONLY
  126874. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  126875. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  126876. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  126877. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  126878. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  126879. rc = SQLITE_CONSTRAINT;
  126880. goto constraint;
  126881. }
  126882. }
  126883. }else
  126884. #endif
  126885. {
  126886. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  126887. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  126888. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  126889. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  126890. rc = SQLITE_CONSTRAINT;
  126891. goto constraint;
  126892. }
  126893. }
  126894. }
  126895. /* If a rowid value was supplied, check if it is already present in
  126896. ** the table. If so, the constraint has failed. */
  126897. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  126898. cell.iRowid = sqlite3_value_int64(azData[2]);
  126899. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  126900. || sqlite3_value_int64(azData[0])!=cell.iRowid
  126901. ){
  126902. int steprc;
  126903. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  126904. steprc = sqlite3_step(pRtree->pReadRowid);
  126905. rc = sqlite3_reset(pRtree->pReadRowid);
  126906. if( SQLITE_ROW==steprc ){
  126907. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  126908. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  126909. }else{
  126910. rc = SQLITE_CONSTRAINT;
  126911. goto constraint;
  126912. }
  126913. }
  126914. }
  126915. bHaveRowid = 1;
  126916. }
  126917. }
  126918. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  126919. ** record to delete from the r-tree table. The following block does
  126920. ** just that.
  126921. */
  126922. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  126923. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  126924. }
  126925. /* If the azData[] array contains more than one element, elements
  126926. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  126927. ** the r-tree structure.
  126928. */
  126929. if( rc==SQLITE_OK && nData>1 ){
  126930. /* Insert the new record into the r-tree */
  126931. RtreeNode *pLeaf = 0;
  126932. /* Figure out the rowid of the new row. */
  126933. if( bHaveRowid==0 ){
  126934. rc = newRowid(pRtree, &cell.iRowid);
  126935. }
  126936. *pRowid = cell.iRowid;
  126937. if( rc==SQLITE_OK ){
  126938. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  126939. }
  126940. if( rc==SQLITE_OK ){
  126941. int rc2;
  126942. pRtree->iReinsertHeight = -1;
  126943. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  126944. rc2 = nodeRelease(pRtree, pLeaf);
  126945. if( rc==SQLITE_OK ){
  126946. rc = rc2;
  126947. }
  126948. }
  126949. }
  126950. constraint:
  126951. rtreeRelease(pRtree);
  126952. return rc;
  126953. }
  126954. /*
  126955. ** The xRename method for rtree module virtual tables.
  126956. */
  126957. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  126958. Rtree *pRtree = (Rtree *)pVtab;
  126959. int rc = SQLITE_NOMEM;
  126960. char *zSql = sqlite3_mprintf(
  126961. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  126962. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  126963. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  126964. , pRtree->zDb, pRtree->zName, zNewName
  126965. , pRtree->zDb, pRtree->zName, zNewName
  126966. , pRtree->zDb, pRtree->zName, zNewName
  126967. );
  126968. if( zSql ){
  126969. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  126970. sqlite3_free(zSql);
  126971. }
  126972. return rc;
  126973. }
  126974. static sqlite3_module rtreeModule = {
  126975. 0, /* iVersion */
  126976. rtreeCreate, /* xCreate - create a table */
  126977. rtreeConnect, /* xConnect - connect to an existing table */
  126978. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  126979. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  126980. rtreeDestroy, /* xDestroy - Drop a table */
  126981. rtreeOpen, /* xOpen - open a cursor */
  126982. rtreeClose, /* xClose - close a cursor */
  126983. rtreeFilter, /* xFilter - configure scan constraints */
  126984. rtreeNext, /* xNext - advance a cursor */
  126985. rtreeEof, /* xEof */
  126986. rtreeColumn, /* xColumn - read data */
  126987. rtreeRowid, /* xRowid - read data */
  126988. rtreeUpdate, /* xUpdate - write data */
  126989. 0, /* xBegin - begin transaction */
  126990. 0, /* xSync - sync transaction */
  126991. 0, /* xCommit - commit transaction */
  126992. 0, /* xRollback - rollback transaction */
  126993. 0, /* xFindFunction - function overloading */
  126994. rtreeRename, /* xRename - rename the table */
  126995. 0, /* xSavepoint */
  126996. 0, /* xRelease */
  126997. 0 /* xRollbackTo */
  126998. };
  126999. static int rtreeSqlInit(
  127000. Rtree *pRtree,
  127001. sqlite3 *db,
  127002. const char *zDb,
  127003. const char *zPrefix,
  127004. int isCreate
  127005. ){
  127006. int rc = SQLITE_OK;
  127007. #define N_STATEMENT 9
  127008. static const char *azSql[N_STATEMENT] = {
  127009. /* Read and write the xxx_node table */
  127010. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  127011. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  127012. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  127013. /* Read and write the xxx_rowid table */
  127014. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  127015. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  127016. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  127017. /* Read and write the xxx_parent table */
  127018. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  127019. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  127020. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  127021. };
  127022. sqlite3_stmt **appStmt[N_STATEMENT];
  127023. int i;
  127024. pRtree->db = db;
  127025. if( isCreate ){
  127026. char *zCreate = sqlite3_mprintf(
  127027. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  127028. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  127029. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  127030. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  127031. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  127032. );
  127033. if( !zCreate ){
  127034. return SQLITE_NOMEM;
  127035. }
  127036. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  127037. sqlite3_free(zCreate);
  127038. if( rc!=SQLITE_OK ){
  127039. return rc;
  127040. }
  127041. }
  127042. appStmt[0] = &pRtree->pReadNode;
  127043. appStmt[1] = &pRtree->pWriteNode;
  127044. appStmt[2] = &pRtree->pDeleteNode;
  127045. appStmt[3] = &pRtree->pReadRowid;
  127046. appStmt[4] = &pRtree->pWriteRowid;
  127047. appStmt[5] = &pRtree->pDeleteRowid;
  127048. appStmt[6] = &pRtree->pReadParent;
  127049. appStmt[7] = &pRtree->pWriteParent;
  127050. appStmt[8] = &pRtree->pDeleteParent;
  127051. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  127052. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  127053. if( zSql ){
  127054. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  127055. }else{
  127056. rc = SQLITE_NOMEM;
  127057. }
  127058. sqlite3_free(zSql);
  127059. }
  127060. return rc;
  127061. }
  127062. /*
  127063. ** The second argument to this function contains the text of an SQL statement
  127064. ** that returns a single integer value. The statement is compiled and executed
  127065. ** using database connection db. If successful, the integer value returned
  127066. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  127067. ** code is returned and the value of *piVal after returning is not defined.
  127068. */
  127069. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  127070. int rc = SQLITE_NOMEM;
  127071. if( zSql ){
  127072. sqlite3_stmt *pStmt = 0;
  127073. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  127074. if( rc==SQLITE_OK ){
  127075. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  127076. *piVal = sqlite3_column_int(pStmt, 0);
  127077. }
  127078. rc = sqlite3_finalize(pStmt);
  127079. }
  127080. }
  127081. return rc;
  127082. }
  127083. /*
  127084. ** This function is called from within the xConnect() or xCreate() method to
  127085. ** determine the node-size used by the rtree table being created or connected
  127086. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  127087. ** Otherwise, an SQLite error code is returned.
  127088. **
  127089. ** If this function is being called as part of an xConnect(), then the rtree
  127090. ** table already exists. In this case the node-size is determined by inspecting
  127091. ** the root node of the tree.
  127092. **
  127093. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  127094. ** This ensures that each node is stored on a single database page. If the
  127095. ** database page-size is so large that more than RTREE_MAXCELLS entries
  127096. ** would fit in a single node, use a smaller node-size.
  127097. */
  127098. static int getNodeSize(
  127099. sqlite3 *db, /* Database handle */
  127100. Rtree *pRtree, /* Rtree handle */
  127101. int isCreate /* True for xCreate, false for xConnect */
  127102. ){
  127103. int rc;
  127104. char *zSql;
  127105. if( isCreate ){
  127106. int iPageSize = 0;
  127107. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  127108. rc = getIntFromStmt(db, zSql, &iPageSize);
  127109. if( rc==SQLITE_OK ){
  127110. pRtree->iNodeSize = iPageSize-64;
  127111. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  127112. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  127113. }
  127114. }
  127115. }else{
  127116. zSql = sqlite3_mprintf(
  127117. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  127118. pRtree->zDb, pRtree->zName
  127119. );
  127120. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  127121. }
  127122. sqlite3_free(zSql);
  127123. return rc;
  127124. }
  127125. /*
  127126. ** This function is the implementation of both the xConnect and xCreate
  127127. ** methods of the r-tree virtual table.
  127128. **
  127129. ** argv[0] -> module name
  127130. ** argv[1] -> database name
  127131. ** argv[2] -> table name
  127132. ** argv[...] -> column names...
  127133. */
  127134. static int rtreeInit(
  127135. sqlite3 *db, /* Database connection */
  127136. void *pAux, /* One of the RTREE_COORD_* constants */
  127137. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  127138. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  127139. char **pzErr, /* OUT: Error message, if any */
  127140. int isCreate /* True for xCreate, false for xConnect */
  127141. ){
  127142. int rc = SQLITE_OK;
  127143. Rtree *pRtree;
  127144. int nDb; /* Length of string argv[1] */
  127145. int nName; /* Length of string argv[2] */
  127146. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  127147. const char *aErrMsg[] = {
  127148. 0, /* 0 */
  127149. "Wrong number of columns for an rtree table", /* 1 */
  127150. "Too few columns for an rtree table", /* 2 */
  127151. "Too many columns for an rtree table" /* 3 */
  127152. };
  127153. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  127154. if( aErrMsg[iErr] ){
  127155. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  127156. return SQLITE_ERROR;
  127157. }
  127158. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  127159. /* Allocate the sqlite3_vtab structure */
  127160. nDb = (int)strlen(argv[1]);
  127161. nName = (int)strlen(argv[2]);
  127162. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  127163. if( !pRtree ){
  127164. return SQLITE_NOMEM;
  127165. }
  127166. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  127167. pRtree->nBusy = 1;
  127168. pRtree->base.pModule = &rtreeModule;
  127169. pRtree->zDb = (char *)&pRtree[1];
  127170. pRtree->zName = &pRtree->zDb[nDb+1];
  127171. pRtree->nDim = (argc-4)/2;
  127172. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  127173. pRtree->eCoordType = eCoordType;
  127174. memcpy(pRtree->zDb, argv[1], nDb);
  127175. memcpy(pRtree->zName, argv[2], nName);
  127176. /* Figure out the node size to use. */
  127177. rc = getNodeSize(db, pRtree, isCreate);
  127178. /* Create/Connect to the underlying relational database schema. If
  127179. ** that is successful, call sqlite3_declare_vtab() to configure
  127180. ** the r-tree table schema.
  127181. */
  127182. if( rc==SQLITE_OK ){
  127183. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  127184. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  127185. }else{
  127186. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  127187. char *zTmp;
  127188. int ii;
  127189. for(ii=4; zSql && ii<argc; ii++){
  127190. zTmp = zSql;
  127191. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  127192. sqlite3_free(zTmp);
  127193. }
  127194. if( zSql ){
  127195. zTmp = zSql;
  127196. zSql = sqlite3_mprintf("%s);", zTmp);
  127197. sqlite3_free(zTmp);
  127198. }
  127199. if( !zSql ){
  127200. rc = SQLITE_NOMEM;
  127201. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  127202. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  127203. }
  127204. sqlite3_free(zSql);
  127205. }
  127206. }
  127207. if( rc==SQLITE_OK ){
  127208. *ppVtab = (sqlite3_vtab *)pRtree;
  127209. }else{
  127210. rtreeRelease(pRtree);
  127211. }
  127212. return rc;
  127213. }
  127214. /*
  127215. ** Implementation of a scalar function that decodes r-tree nodes to
  127216. ** human readable strings. This can be used for debugging and analysis.
  127217. **
  127218. ** The scalar function takes two arguments, a blob of data containing
  127219. ** an r-tree node, and the number of dimensions the r-tree indexes.
  127220. ** For a two-dimensional r-tree structure called "rt", to deserialize
  127221. ** all nodes, a statement like:
  127222. **
  127223. ** SELECT rtreenode(2, data) FROM rt_node;
  127224. **
  127225. ** The human readable string takes the form of a Tcl list with one
  127226. ** entry for each cell in the r-tree node. Each entry is itself a
  127227. ** list, containing the 8-byte rowid/pageno followed by the
  127228. ** <num-dimension>*2 coordinates.
  127229. */
  127230. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  127231. char *zText = 0;
  127232. RtreeNode node;
  127233. Rtree tree;
  127234. int ii;
  127235. UNUSED_PARAMETER(nArg);
  127236. memset(&node, 0, sizeof(RtreeNode));
  127237. memset(&tree, 0, sizeof(Rtree));
  127238. tree.nDim = sqlite3_value_int(apArg[0]);
  127239. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  127240. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  127241. for(ii=0; ii<NCELL(&node); ii++){
  127242. char zCell[512];
  127243. int nCell = 0;
  127244. RtreeCell cell;
  127245. int jj;
  127246. nodeGetCell(&tree, &node, ii, &cell);
  127247. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  127248. nCell = (int)strlen(zCell);
  127249. for(jj=0; jj<tree.nDim*2; jj++){
  127250. #ifndef SQLITE_RTREE_INT_ONLY
  127251. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  127252. (double)cell.aCoord[jj].f);
  127253. #else
  127254. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  127255. cell.aCoord[jj].i);
  127256. #endif
  127257. nCell = (int)strlen(zCell);
  127258. }
  127259. if( zText ){
  127260. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  127261. sqlite3_free(zText);
  127262. zText = zTextNew;
  127263. }else{
  127264. zText = sqlite3_mprintf("{%s}", zCell);
  127265. }
  127266. }
  127267. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  127268. }
  127269. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  127270. UNUSED_PARAMETER(nArg);
  127271. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  127272. || sqlite3_value_bytes(apArg[0])<2
  127273. ){
  127274. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  127275. }else{
  127276. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  127277. sqlite3_result_int(ctx, readInt16(zBlob));
  127278. }
  127279. }
  127280. /*
  127281. ** Register the r-tree module with database handle db. This creates the
  127282. ** virtual table module "rtree" and the debugging/analysis scalar
  127283. ** function "rtreenode".
  127284. */
  127285. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  127286. const int utf8 = SQLITE_UTF8;
  127287. int rc;
  127288. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  127289. if( rc==SQLITE_OK ){
  127290. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  127291. }
  127292. if( rc==SQLITE_OK ){
  127293. #ifdef SQLITE_RTREE_INT_ONLY
  127294. void *c = (void *)RTREE_COORD_INT32;
  127295. #else
  127296. void *c = (void *)RTREE_COORD_REAL32;
  127297. #endif
  127298. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  127299. }
  127300. if( rc==SQLITE_OK ){
  127301. void *c = (void *)RTREE_COORD_INT32;
  127302. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  127303. }
  127304. return rc;
  127305. }
  127306. /*
  127307. ** A version of sqlite3_free() that can be used as a callback. This is used
  127308. ** in two places - as the destructor for the blob value returned by the
  127309. ** invocation of a geometry function, and as the destructor for the geometry
  127310. ** functions themselves.
  127311. */
  127312. static void doSqlite3Free(void *p){
  127313. sqlite3_free(p);
  127314. }
  127315. /*
  127316. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  127317. ** scalar user function. This C function is the callback used for all such
  127318. ** registered SQL functions.
  127319. **
  127320. ** The scalar user functions return a blob that is interpreted by r-tree
  127321. ** table MATCH operators.
  127322. */
  127323. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  127324. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  127325. RtreeMatchArg *pBlob;
  127326. int nBlob;
  127327. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  127328. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  127329. if( !pBlob ){
  127330. sqlite3_result_error_nomem(ctx);
  127331. }else{
  127332. int i;
  127333. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  127334. pBlob->xGeom = pGeomCtx->xGeom;
  127335. pBlob->pContext = pGeomCtx->pContext;
  127336. pBlob->nParam = nArg;
  127337. for(i=0; i<nArg; i++){
  127338. #ifdef SQLITE_RTREE_INT_ONLY
  127339. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  127340. #else
  127341. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  127342. #endif
  127343. }
  127344. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  127345. }
  127346. }
  127347. /*
  127348. ** Register a new geometry function for use with the r-tree MATCH operator.
  127349. */
  127350. SQLITE_API int sqlite3_rtree_geometry_callback(
  127351. sqlite3 *db,
  127352. const char *zGeom,
  127353. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  127354. void *pContext
  127355. ){
  127356. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  127357. /* Allocate and populate the context object. */
  127358. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  127359. if( !pGeomCtx ) return SQLITE_NOMEM;
  127360. pGeomCtx->xGeom = xGeom;
  127361. pGeomCtx->pContext = pContext;
  127362. /* Create the new user-function. Register a destructor function to delete
  127363. ** the context object when it is no longer required. */
  127364. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  127365. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  127366. );
  127367. }
  127368. #if !SQLITE_CORE
  127369. SQLITE_API int sqlite3_extension_init(
  127370. sqlite3 *db,
  127371. char **pzErrMsg,
  127372. const sqlite3_api_routines *pApi
  127373. ){
  127374. SQLITE_EXTENSION_INIT2(pApi)
  127375. return sqlite3RtreeInit(db);
  127376. }
  127377. #endif
  127378. #endif
  127379. /************** End of rtree.c ***********************************************/
  127380. /************** Begin file icu.c *********************************************/
  127381. /*
  127382. ** 2007 May 6
  127383. **
  127384. ** The author disclaims copyright to this source code. In place of
  127385. ** a legal notice, here is a blessing:
  127386. **
  127387. ** May you do good and not evil.
  127388. ** May you find forgiveness for yourself and forgive others.
  127389. ** May you share freely, never taking more than you give.
  127390. **
  127391. *************************************************************************
  127392. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  127393. **
  127394. ** This file implements an integration between the ICU library
  127395. ** ("International Components for Unicode", an open-source library
  127396. ** for handling unicode data) and SQLite. The integration uses
  127397. ** ICU to provide the following to SQLite:
  127398. **
  127399. ** * An implementation of the SQL regexp() function (and hence REGEXP
  127400. ** operator) using the ICU uregex_XX() APIs.
  127401. **
  127402. ** * Implementations of the SQL scalar upper() and lower() functions
  127403. ** for case mapping.
  127404. **
  127405. ** * Integration of ICU and SQLite collation seqences.
  127406. **
  127407. ** * An implementation of the LIKE operator that uses ICU to
  127408. ** provide case-independent matching.
  127409. */
  127410. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  127411. /* Include ICU headers */
  127412. #include <unicode/utypes.h>
  127413. #include <unicode/uregex.h>
  127414. #include <unicode/ustring.h>
  127415. #include <unicode/ucol.h>
  127416. /* #include <assert.h> */
  127417. #ifndef SQLITE_CORE
  127418. SQLITE_EXTENSION_INIT1
  127419. #else
  127420. #endif
  127421. /*
  127422. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  127423. ** operator.
  127424. */
  127425. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  127426. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  127427. #endif
  127428. /*
  127429. ** Version of sqlite3_free() that is always a function, never a macro.
  127430. */
  127431. static void xFree(void *p){
  127432. sqlite3_free(p);
  127433. }
  127434. /*
  127435. ** Compare two UTF-8 strings for equality where the first string is
  127436. ** a "LIKE" expression. Return true (1) if they are the same and
  127437. ** false (0) if they are different.
  127438. */
  127439. static int icuLikeCompare(
  127440. const uint8_t *zPattern, /* LIKE pattern */
  127441. const uint8_t *zString, /* The UTF-8 string to compare against */
  127442. const UChar32 uEsc /* The escape character */
  127443. ){
  127444. static const int MATCH_ONE = (UChar32)'_';
  127445. static const int MATCH_ALL = (UChar32)'%';
  127446. int iPattern = 0; /* Current byte index in zPattern */
  127447. int iString = 0; /* Current byte index in zString */
  127448. int prevEscape = 0; /* True if the previous character was uEsc */
  127449. while( zPattern[iPattern]!=0 ){
  127450. /* Read (and consume) the next character from the input pattern. */
  127451. UChar32 uPattern;
  127452. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  127453. assert(uPattern!=0);
  127454. /* There are now 4 possibilities:
  127455. **
  127456. ** 1. uPattern is an unescaped match-all character "%",
  127457. ** 2. uPattern is an unescaped match-one character "_",
  127458. ** 3. uPattern is an unescaped escape character, or
  127459. ** 4. uPattern is to be handled as an ordinary character
  127460. */
  127461. if( !prevEscape && uPattern==MATCH_ALL ){
  127462. /* Case 1. */
  127463. uint8_t c;
  127464. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  127465. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  127466. ** test string.
  127467. */
  127468. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  127469. if( c==MATCH_ONE ){
  127470. if( zString[iString]==0 ) return 0;
  127471. U8_FWD_1_UNSAFE(zString, iString);
  127472. }
  127473. iPattern++;
  127474. }
  127475. if( zPattern[iPattern]==0 ) return 1;
  127476. while( zString[iString] ){
  127477. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  127478. return 1;
  127479. }
  127480. U8_FWD_1_UNSAFE(zString, iString);
  127481. }
  127482. return 0;
  127483. }else if( !prevEscape && uPattern==MATCH_ONE ){
  127484. /* Case 2. */
  127485. if( zString[iString]==0 ) return 0;
  127486. U8_FWD_1_UNSAFE(zString, iString);
  127487. }else if( !prevEscape && uPattern==uEsc){
  127488. /* Case 3. */
  127489. prevEscape = 1;
  127490. }else{
  127491. /* Case 4. */
  127492. UChar32 uString;
  127493. U8_NEXT_UNSAFE(zString, iString, uString);
  127494. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  127495. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  127496. if( uString!=uPattern ){
  127497. return 0;
  127498. }
  127499. prevEscape = 0;
  127500. }
  127501. }
  127502. return zString[iString]==0;
  127503. }
  127504. /*
  127505. ** Implementation of the like() SQL function. This function implements
  127506. ** the build-in LIKE operator. The first argument to the function is the
  127507. ** pattern and the second argument is the string. So, the SQL statements:
  127508. **
  127509. ** A LIKE B
  127510. **
  127511. ** is implemented as like(B, A). If there is an escape character E,
  127512. **
  127513. ** A LIKE B ESCAPE E
  127514. **
  127515. ** is mapped to like(B, A, E).
  127516. */
  127517. static void icuLikeFunc(
  127518. sqlite3_context *context,
  127519. int argc,
  127520. sqlite3_value **argv
  127521. ){
  127522. const unsigned char *zA = sqlite3_value_text(argv[0]);
  127523. const unsigned char *zB = sqlite3_value_text(argv[1]);
  127524. UChar32 uEsc = 0;
  127525. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  127526. ** of deep recursion and N*N behavior in patternCompare().
  127527. */
  127528. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  127529. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  127530. return;
  127531. }
  127532. if( argc==3 ){
  127533. /* The escape character string must consist of a single UTF-8 character.
  127534. ** Otherwise, return an error.
  127535. */
  127536. int nE= sqlite3_value_bytes(argv[2]);
  127537. const unsigned char *zE = sqlite3_value_text(argv[2]);
  127538. int i = 0;
  127539. if( zE==0 ) return;
  127540. U8_NEXT(zE, i, nE, uEsc);
  127541. if( i!=nE){
  127542. sqlite3_result_error(context,
  127543. "ESCAPE expression must be a single character", -1);
  127544. return;
  127545. }
  127546. }
  127547. if( zA && zB ){
  127548. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  127549. }
  127550. }
  127551. /*
  127552. ** This function is called when an ICU function called from within
  127553. ** the implementation of an SQL scalar function returns an error.
  127554. **
  127555. ** The scalar function context passed as the first argument is
  127556. ** loaded with an error message based on the following two args.
  127557. */
  127558. static void icuFunctionError(
  127559. sqlite3_context *pCtx, /* SQLite scalar function context */
  127560. const char *zName, /* Name of ICU function that failed */
  127561. UErrorCode e /* Error code returned by ICU function */
  127562. ){
  127563. char zBuf[128];
  127564. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  127565. zBuf[127] = '\0';
  127566. sqlite3_result_error(pCtx, zBuf, -1);
  127567. }
  127568. /*
  127569. ** Function to delete compiled regexp objects. Registered as
  127570. ** a destructor function with sqlite3_set_auxdata().
  127571. */
  127572. static void icuRegexpDelete(void *p){
  127573. URegularExpression *pExpr = (URegularExpression *)p;
  127574. uregex_close(pExpr);
  127575. }
  127576. /*
  127577. ** Implementation of SQLite REGEXP operator. This scalar function takes
  127578. ** two arguments. The first is a regular expression pattern to compile
  127579. ** the second is a string to match against that pattern. If either
  127580. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  127581. ** is 1 if the string matches the pattern, or 0 otherwise.
  127582. **
  127583. ** SQLite maps the regexp() function to the regexp() operator such
  127584. ** that the following two are equivalent:
  127585. **
  127586. ** zString REGEXP zPattern
  127587. ** regexp(zPattern, zString)
  127588. **
  127589. ** Uses the following ICU regexp APIs:
  127590. **
  127591. ** uregex_open()
  127592. ** uregex_matches()
  127593. ** uregex_close()
  127594. */
  127595. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  127596. UErrorCode status = U_ZERO_ERROR;
  127597. URegularExpression *pExpr;
  127598. UBool res;
  127599. const UChar *zString = sqlite3_value_text16(apArg[1]);
  127600. (void)nArg; /* Unused parameter */
  127601. /* If the left hand side of the regexp operator is NULL,
  127602. ** then the result is also NULL.
  127603. */
  127604. if( !zString ){
  127605. return;
  127606. }
  127607. pExpr = sqlite3_get_auxdata(p, 0);
  127608. if( !pExpr ){
  127609. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  127610. if( !zPattern ){
  127611. return;
  127612. }
  127613. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  127614. if( U_SUCCESS(status) ){
  127615. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  127616. }else{
  127617. assert(!pExpr);
  127618. icuFunctionError(p, "uregex_open", status);
  127619. return;
  127620. }
  127621. }
  127622. /* Configure the text that the regular expression operates on. */
  127623. uregex_setText(pExpr, zString, -1, &status);
  127624. if( !U_SUCCESS(status) ){
  127625. icuFunctionError(p, "uregex_setText", status);
  127626. return;
  127627. }
  127628. /* Attempt the match */
  127629. res = uregex_matches(pExpr, 0, &status);
  127630. if( !U_SUCCESS(status) ){
  127631. icuFunctionError(p, "uregex_matches", status);
  127632. return;
  127633. }
  127634. /* Set the text that the regular expression operates on to a NULL
  127635. ** pointer. This is not really necessary, but it is tidier than
  127636. ** leaving the regular expression object configured with an invalid
  127637. ** pointer after this function returns.
  127638. */
  127639. uregex_setText(pExpr, 0, 0, &status);
  127640. /* Return 1 or 0. */
  127641. sqlite3_result_int(p, res ? 1 : 0);
  127642. }
  127643. /*
  127644. ** Implementations of scalar functions for case mapping - upper() and
  127645. ** lower(). Function upper() converts its input to upper-case (ABC).
  127646. ** Function lower() converts to lower-case (abc).
  127647. **
  127648. ** ICU provides two types of case mapping, "general" case mapping and
  127649. ** "language specific". Refer to ICU documentation for the differences
  127650. ** between the two.
  127651. **
  127652. ** To utilise "general" case mapping, the upper() or lower() scalar
  127653. ** functions are invoked with one argument:
  127654. **
  127655. ** upper('ABC') -> 'abc'
  127656. ** lower('abc') -> 'ABC'
  127657. **
  127658. ** To access ICU "language specific" case mapping, upper() or lower()
  127659. ** should be invoked with two arguments. The second argument is the name
  127660. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  127661. ** as the second argument is the same as invoking the 1 argument version
  127662. ** of upper() or lower().
  127663. **
  127664. ** lower('I', 'en_us') -> 'i'
  127665. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  127666. **
  127667. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  127668. */
  127669. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  127670. const UChar *zInput;
  127671. UChar *zOutput;
  127672. int nInput;
  127673. int nOutput;
  127674. UErrorCode status = U_ZERO_ERROR;
  127675. const char *zLocale = 0;
  127676. assert(nArg==1 || nArg==2);
  127677. if( nArg==2 ){
  127678. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  127679. }
  127680. zInput = sqlite3_value_text16(apArg[0]);
  127681. if( !zInput ){
  127682. return;
  127683. }
  127684. nInput = sqlite3_value_bytes16(apArg[0]);
  127685. nOutput = nInput * 2 + 2;
  127686. zOutput = sqlite3_malloc(nOutput);
  127687. if( !zOutput ){
  127688. return;
  127689. }
  127690. if( sqlite3_user_data(p) ){
  127691. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  127692. }else{
  127693. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  127694. }
  127695. if( !U_SUCCESS(status) ){
  127696. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  127697. return;
  127698. }
  127699. sqlite3_result_text16(p, zOutput, -1, xFree);
  127700. }
  127701. /*
  127702. ** Collation sequence destructor function. The pCtx argument points to
  127703. ** a UCollator structure previously allocated using ucol_open().
  127704. */
  127705. static void icuCollationDel(void *pCtx){
  127706. UCollator *p = (UCollator *)pCtx;
  127707. ucol_close(p);
  127708. }
  127709. /*
  127710. ** Collation sequence comparison function. The pCtx argument points to
  127711. ** a UCollator structure previously allocated using ucol_open().
  127712. */
  127713. static int icuCollationColl(
  127714. void *pCtx,
  127715. int nLeft,
  127716. const void *zLeft,
  127717. int nRight,
  127718. const void *zRight
  127719. ){
  127720. UCollationResult res;
  127721. UCollator *p = (UCollator *)pCtx;
  127722. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  127723. switch( res ){
  127724. case UCOL_LESS: return -1;
  127725. case UCOL_GREATER: return +1;
  127726. case UCOL_EQUAL: return 0;
  127727. }
  127728. assert(!"Unexpected return value from ucol_strcoll()");
  127729. return 0;
  127730. }
  127731. /*
  127732. ** Implementation of the scalar function icu_load_collation().
  127733. **
  127734. ** This scalar function is used to add ICU collation based collation
  127735. ** types to an SQLite database connection. It is intended to be called
  127736. ** as follows:
  127737. **
  127738. ** SELECT icu_load_collation(<locale>, <collation-name>);
  127739. **
  127740. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  127741. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  127742. ** collation sequence to create.
  127743. */
  127744. static void icuLoadCollation(
  127745. sqlite3_context *p,
  127746. int nArg,
  127747. sqlite3_value **apArg
  127748. ){
  127749. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  127750. UErrorCode status = U_ZERO_ERROR;
  127751. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  127752. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  127753. UCollator *pUCollator; /* ICU library collation object */
  127754. int rc; /* Return code from sqlite3_create_collation_x() */
  127755. assert(nArg==2);
  127756. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  127757. zName = (const char *)sqlite3_value_text(apArg[1]);
  127758. if( !zLocale || !zName ){
  127759. return;
  127760. }
  127761. pUCollator = ucol_open(zLocale, &status);
  127762. if( !U_SUCCESS(status) ){
  127763. icuFunctionError(p, "ucol_open", status);
  127764. return;
  127765. }
  127766. assert(p);
  127767. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  127768. icuCollationColl, icuCollationDel
  127769. );
  127770. if( rc!=SQLITE_OK ){
  127771. ucol_close(pUCollator);
  127772. sqlite3_result_error(p, "Error registering collation function", -1);
  127773. }
  127774. }
  127775. /*
  127776. ** Register the ICU extension functions with database db.
  127777. */
  127778. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  127779. struct IcuScalar {
  127780. const char *zName; /* Function name */
  127781. int nArg; /* Number of arguments */
  127782. int enc; /* Optimal text encoding */
  127783. void *pContext; /* sqlite3_user_data() context */
  127784. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  127785. } scalars[] = {
  127786. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  127787. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  127788. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  127789. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  127790. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  127791. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  127792. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  127793. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  127794. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  127795. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  127796. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  127797. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  127798. };
  127799. int rc = SQLITE_OK;
  127800. int i;
  127801. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  127802. struct IcuScalar *p = &scalars[i];
  127803. rc = sqlite3_create_function(
  127804. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  127805. );
  127806. }
  127807. return rc;
  127808. }
  127809. #if !SQLITE_CORE
  127810. SQLITE_API int sqlite3_extension_init(
  127811. sqlite3 *db,
  127812. char **pzErrMsg,
  127813. const sqlite3_api_routines *pApi
  127814. ){
  127815. SQLITE_EXTENSION_INIT2(pApi)
  127816. return sqlite3IcuInit(db);
  127817. }
  127818. #endif
  127819. #endif
  127820. /************** End of icu.c *************************************************/
  127821. /************** Begin file fts3_icu.c ****************************************/
  127822. /*
  127823. ** 2007 June 22
  127824. **
  127825. ** The author disclaims copyright to this source code. In place of
  127826. ** a legal notice, here is a blessing:
  127827. **
  127828. ** May you do good and not evil.
  127829. ** May you find forgiveness for yourself and forgive others.
  127830. ** May you share freely, never taking more than you give.
  127831. **
  127832. *************************************************************************
  127833. ** This file implements a tokenizer for fts3 based on the ICU library.
  127834. */
  127835. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  127836. #ifdef SQLITE_ENABLE_ICU
  127837. /* #include <assert.h> */
  127838. /* #include <string.h> */
  127839. #include <unicode/ubrk.h>
  127840. /* #include <unicode/ucol.h> */
  127841. /* #include <unicode/ustring.h> */
  127842. #include <unicode/utf16.h>
  127843. typedef struct IcuTokenizer IcuTokenizer;
  127844. typedef struct IcuCursor IcuCursor;
  127845. struct IcuTokenizer {
  127846. sqlite3_tokenizer base;
  127847. char *zLocale;
  127848. };
  127849. struct IcuCursor {
  127850. sqlite3_tokenizer_cursor base;
  127851. UBreakIterator *pIter; /* ICU break-iterator object */
  127852. int nChar; /* Number of UChar elements in pInput */
  127853. UChar *aChar; /* Copy of input using utf-16 encoding */
  127854. int *aOffset; /* Offsets of each character in utf-8 input */
  127855. int nBuffer;
  127856. char *zBuffer;
  127857. int iToken;
  127858. };
  127859. /*
  127860. ** Create a new tokenizer instance.
  127861. */
  127862. static int icuCreate(
  127863. int argc, /* Number of entries in argv[] */
  127864. const char * const *argv, /* Tokenizer creation arguments */
  127865. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  127866. ){
  127867. IcuTokenizer *p;
  127868. int n = 0;
  127869. if( argc>0 ){
  127870. n = strlen(argv[0])+1;
  127871. }
  127872. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  127873. if( !p ){
  127874. return SQLITE_NOMEM;
  127875. }
  127876. memset(p, 0, sizeof(IcuTokenizer));
  127877. if( n ){
  127878. p->zLocale = (char *)&p[1];
  127879. memcpy(p->zLocale, argv[0], n);
  127880. }
  127881. *ppTokenizer = (sqlite3_tokenizer *)p;
  127882. return SQLITE_OK;
  127883. }
  127884. /*
  127885. ** Destroy a tokenizer
  127886. */
  127887. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  127888. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  127889. sqlite3_free(p);
  127890. return SQLITE_OK;
  127891. }
  127892. /*
  127893. ** Prepare to begin tokenizing a particular string. The input
  127894. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  127895. ** used to incrementally tokenize this string is returned in
  127896. ** *ppCursor.
  127897. */
  127898. static int icuOpen(
  127899. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  127900. const char *zInput, /* Input string */
  127901. int nInput, /* Length of zInput in bytes */
  127902. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  127903. ){
  127904. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  127905. IcuCursor *pCsr;
  127906. const int32_t opt = U_FOLD_CASE_DEFAULT;
  127907. UErrorCode status = U_ZERO_ERROR;
  127908. int nChar;
  127909. UChar32 c;
  127910. int iInput = 0;
  127911. int iOut = 0;
  127912. *ppCursor = 0;
  127913. if( zInput==0 ){
  127914. nInput = 0;
  127915. zInput = "";
  127916. }else if( nInput<0 ){
  127917. nInput = strlen(zInput);
  127918. }
  127919. nChar = nInput+1;
  127920. pCsr = (IcuCursor *)sqlite3_malloc(
  127921. sizeof(IcuCursor) + /* IcuCursor */
  127922. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  127923. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  127924. );
  127925. if( !pCsr ){
  127926. return SQLITE_NOMEM;
  127927. }
  127928. memset(pCsr, 0, sizeof(IcuCursor));
  127929. pCsr->aChar = (UChar *)&pCsr[1];
  127930. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  127931. pCsr->aOffset[iOut] = iInput;
  127932. U8_NEXT(zInput, iInput, nInput, c);
  127933. while( c>0 ){
  127934. int isError = 0;
  127935. c = u_foldCase(c, opt);
  127936. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  127937. if( isError ){
  127938. sqlite3_free(pCsr);
  127939. return SQLITE_ERROR;
  127940. }
  127941. pCsr->aOffset[iOut] = iInput;
  127942. if( iInput<nInput ){
  127943. U8_NEXT(zInput, iInput, nInput, c);
  127944. }else{
  127945. c = 0;
  127946. }
  127947. }
  127948. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  127949. if( !U_SUCCESS(status) ){
  127950. sqlite3_free(pCsr);
  127951. return SQLITE_ERROR;
  127952. }
  127953. pCsr->nChar = iOut;
  127954. ubrk_first(pCsr->pIter);
  127955. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  127956. return SQLITE_OK;
  127957. }
  127958. /*
  127959. ** Close a tokenization cursor previously opened by a call to icuOpen().
  127960. */
  127961. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  127962. IcuCursor *pCsr = (IcuCursor *)pCursor;
  127963. ubrk_close(pCsr->pIter);
  127964. sqlite3_free(pCsr->zBuffer);
  127965. sqlite3_free(pCsr);
  127966. return SQLITE_OK;
  127967. }
  127968. /*
  127969. ** Extract the next token from a tokenization cursor.
  127970. */
  127971. static int icuNext(
  127972. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  127973. const char **ppToken, /* OUT: *ppToken is the token text */
  127974. int *pnBytes, /* OUT: Number of bytes in token */
  127975. int *piStartOffset, /* OUT: Starting offset of token */
  127976. int *piEndOffset, /* OUT: Ending offset of token */
  127977. int *piPosition /* OUT: Position integer of token */
  127978. ){
  127979. IcuCursor *pCsr = (IcuCursor *)pCursor;
  127980. int iStart = 0;
  127981. int iEnd = 0;
  127982. int nByte = 0;
  127983. while( iStart==iEnd ){
  127984. UChar32 c;
  127985. iStart = ubrk_current(pCsr->pIter);
  127986. iEnd = ubrk_next(pCsr->pIter);
  127987. if( iEnd==UBRK_DONE ){
  127988. return SQLITE_DONE;
  127989. }
  127990. while( iStart<iEnd ){
  127991. int iWhite = iStart;
  127992. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  127993. if( u_isspace(c) ){
  127994. iStart = iWhite;
  127995. }else{
  127996. break;
  127997. }
  127998. }
  127999. assert(iStart<=iEnd);
  128000. }
  128001. do {
  128002. UErrorCode status = U_ZERO_ERROR;
  128003. if( nByte ){
  128004. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  128005. if( !zNew ){
  128006. return SQLITE_NOMEM;
  128007. }
  128008. pCsr->zBuffer = zNew;
  128009. pCsr->nBuffer = nByte;
  128010. }
  128011. u_strToUTF8(
  128012. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  128013. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  128014. &status /* Output success/failure */
  128015. );
  128016. } while( nByte>pCsr->nBuffer );
  128017. *ppToken = pCsr->zBuffer;
  128018. *pnBytes = nByte;
  128019. *piStartOffset = pCsr->aOffset[iStart];
  128020. *piEndOffset = pCsr->aOffset[iEnd];
  128021. *piPosition = pCsr->iToken++;
  128022. return SQLITE_OK;
  128023. }
  128024. /*
  128025. ** The set of routines that implement the simple tokenizer
  128026. */
  128027. static const sqlite3_tokenizer_module icuTokenizerModule = {
  128028. 0, /* iVersion */
  128029. icuCreate, /* xCreate */
  128030. icuDestroy, /* xCreate */
  128031. icuOpen, /* xOpen */
  128032. icuClose, /* xClose */
  128033. icuNext, /* xNext */
  128034. };
  128035. /*
  128036. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  128037. */
  128038. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  128039. sqlite3_tokenizer_module const**ppModule
  128040. ){
  128041. *ppModule = &icuTokenizerModule;
  128042. }
  128043. #endif /* defined(SQLITE_ENABLE_ICU) */
  128044. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  128045. /************** End of fts3_icu.c ********************************************/